Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .ai/contexts/trigger-watcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ Main-process modules `trigger-watcher.js` and `trigger-context.js` live in
| `src/main/triggers/trigger-watcher.js` | The watcher core: directory setup, `fs.watch` listener, idle-wait logic, single + chained trigger processing, submit-with-verify busy-rise/fall polling, input validation, PTY write, result file. |
| `src/main/triggers/trigger-name.js` | The new-session name rules: unpaired-surrogate test, `requestedName`/`actualName` result fields, marker naming provenance and its recovery validation (see "Naming a new session"). |
| `src/main/triggers/trigger-context.js` | `createTriggerContext({ activeSessions, log, getCliStatus, projectsDir, lifecycle, sessionRequests, statusSources, getLiveDescriptor, resolveSessionId, remote })` — builds the whole `ctx` object out of `main.js`'s session map, including the pinned per-tab delivery binding (`pinDelivery`) and the descriptor fallback lookup (`lookupDeliveryFallback`). |
| `src/main/triggers/trigger-actions.js` | Versioned (`version`/`action`) requests: `validateTrigger`, `resolveProject` (with its transient-conflict retry), the new-session limiter, open/new/stop execution (`createTriggerActions`). |
| `src/main/triggers/trigger-actions.js` | Versioned (`version`/`action`) requests: `validateTrigger`, `resolveProject` (with its transient-conflict retry), the new-session limiter, open/new/stop execution (`createTriggerActions`), and the stop final check: `finalCheck.notePath` on stop, `runStopCheck` running the global `stopCheckCommand` argv in `--sample-final` then `--check-final` mode (contract in `docs/automation.md`). |
| `src/main/triggers/trigger-launch.js` | `acquireOpen` (per-id open FIFO) and `validateTriggerOpen`, the main-process launch checks. |
| `src/main/triggers/trigger-renderer-bridge.js` | `createTriggerRendererBridge`: the renderer broker for open/new and stop (see "Renderer broker and open lifecycle"). |
| `src/main/triggers/session-request-contract.js` | The typed request parser (`parseSessionRequest`, `statusEnvelope`, `openRefusal`). |
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ What changes for you in each release of Switchboard. How to write an entry: [doc
## Unreleased

### New
- A trigger stop can ask for a final check before the session ends: with `"finalCheck":{"notePath":…}` and the new **stopCheckCommand** setting, Switchboard runs that command to confirm the note and the last turn just before stopping, and refuses the stop with `stop check refused`, `failed`, `timed out` or `unavailable` otherwise. Stops without `finalCheck` are unchanged. (#1405)
- Moving a session to the background now asks whether to stop or keep an older job for the same conversation when Switchboard cannot tell if it is still running; Stop checks again before moving, and Cancel quietly keeps that session in the foreground while the rest of the batch continues. Cancellations from Claude and refusals after a choice still show their reason; Keep also checks for live jobs known only from the Agents list. Cancelled questions close, and waiting for a choice does not shorten the move’s confirmation time. (#1295)

### Changed
Expand Down
34 changes: 34 additions & 0 deletions docs/automation.md
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,40 @@ content. Failure returns `note step not finished` with `delivery` diagnostics
and leaves the session running. A newly started turn after the note refuses
`session busy` instead of terminating it.

#### Stop final check

A stop request may include `"finalCheck":{"notePath":"/absolute/path/to/note.md"}`.
The field is valid only on stop and contains only `notePath`. The path must be
absolute, at most 4096 characters, and free of control characters. Switchboard
reads the persisted global `stopCheckCommand` setting for this request. Its
default is `null`; configure it as an argv array whose first element is an
absolute executable path, for example
`["/usr/bin/python3","-B","/absolute/path/to/lifecycle_stop.py"]`.
The array accepts at most 32 strings, 4096 characters per string and 8192
characters in total; control characters are refused.
The configured program must support `--sample-final` and `--check-final`.
Switchboard supplies the session ID, note path, and sampled evidence tokens as
separate arguments. Trigger files cannot supply command arguments.

```text
<stopCheckCommand argv> --sample-final --session-id <target id> --note <notePath>
<stopCheckCommand argv> --check-final --session-id <target id> --note <notePath> --expected-note-commit <hex40> --expected-transcript-turn <hex64>
```

After any `before` delivery and the final idle and composer check, Switchboard
samples note and transcript evidence once, verifies it once, then synchronously
rechecks the target, idle status, composer, and deadline before requesting one
stop. A validator refusal returns `stop check refused` with its first stdout
line in `detail`. A nonzero validator error or malformed sample returns
`stop check failed`; an expired deadline returns `stop check timed out`; an
unset or invalid command or a spawn failure returns `stop check unavailable`.
These results do not request a stop and retain any completed `before` delivery
evidence. The check observes the note and transcript before the stop request;
later writes to those files are outside that observation.
On POSIX, an expired or overproducing validator terminates its process group.
On Windows, termination targets the direct child only; descendants may remain
running, but their inherited output streams cannot delay the stop result.

Stop never opens a closed session or stops siblings in a merged row. Remote,
scheduled, background/attach and plain-terminal targets remain unsupported.
`expectedCwd` is supported for stop and rechecked before termination. `closed`
Expand Down
4 changes: 4 additions & 0 deletions docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ explicit action. See [Activity trace](activity-trace.md#deleting-older-log-files
**Dangerous Skip** applies to one launch.
- `remoteTriggers` (default off): lets a trigger reach a session of an enabled
remote host — see [Automation](automation.md#remote-trigger-targets).
- `stopCheckCommand` (default none): the argv array of the command a stop
trigger with `finalCheck` runs to confirm the session's note and last turn
before stopping it; no settings field sets it — see
[Automation](automation.md#stop-final-check).
- `lastSeenVersion` (default none): the last version whose **What's new** was
shown — see [Changelog](changelog.md#whats-new-in-the-app).

Expand Down
2 changes: 1 addition & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -861,7 +861,7 @@ module.exports = [

// Tests: node:test, Node globals
{
files: ['test/**/*.js', 'test/**/*.test.js', 'test/fixtures/trigger-*.cjs', 'test/get-projects-handler.cjs'],
files: ['test/**/*.js', 'test/**/*.test.js', 'test/fixtures/trigger-*.cjs', 'test/fixtures/assert-named-test-blocked.cjs', 'test/fixtures/assert-named-test-overflow.cjs', 'test/get-projects-handler.cjs'],
languageOptions: {
ecmaVersion: 2024,
sourceType: 'commonjs',
Expand Down
15 changes: 13 additions & 2 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,14 @@
}

// Shell profiles → shell-profiles.js
const { discoverShellProfiles, getShellProfiles, resolveShell, isWindows, isWslShell, windowsToWslPath, shellArgs, quoteArgvForShell, claudeCommand, headlessClaudeLaunch, customArgsForLaunch } = require('./src/main/terminals/shell-profiles');

Check warning on line 89 in main.js

View workflow job for this annotation

GitHub Actions / lint

'discoverShellProfiles' is assigned a value but never used. Allowed unused vars must match /^_/u
const { startScheduler, scheduleLaunchRefusal, resolveScheduleSandbox, initialScheduleProjects, scanSchedules, setScheduleEnabled, listScheduleFiles } = require('./src/main/schedules/schedule-runner');
const { createScheduleHistoryImport } = require('./src/main/schedules/schedule-history-import');
const { buildScheduleList } = require('./src/main/schedules/schedule-list');
const { migrateSchedulesTabWithinBound } = require('./src/main/schedules/schedules-tab-migration');
const { archivePlanForGroups, validArchiveGroups } = require('./archived-projects');
const { encodeProjectPath } = require('./encode-project-path');
const { SETTING_DEFAULTS, normalizeBrowserSettings,
const { SETTING_DEFAULTS, normalizeBrowserSettings, validateStopCheckCommand,
PROJECT_DELETE_WORKTREE_INSPECTION_TIMEOUT_MS, PROJECT_DELETE_WORKTREE_REMOVE_TIMEOUT_MS } = require('./public/setting-defaults');
const { isSensitivePath, isSensitivePathAsync, isAllowedMemoryPath: _isAllowedMemoryPath, resolveAllowedMemoryPath: _resolveAllowedMemoryPath, isKnownProjectRoot: _isKnownProjectRoot } = require('./src/main/shared/ipc-path-validator');
const { validatePreLaunchCmd } = require('./src/main/terminals/pre-launch-cmd-guard');
Expand Down Expand Up @@ -656,8 +656,8 @@
getMainWindow: () => mainWindow,
log,
});
const { readSessionFile, readFolderFromFilesystem,

Check warning on line 659 in main.js

View workflow job for this annotation

GitHub Actions / lint

'readFolderFromFilesystem' is assigned a value but never used. Allowed unused vars must match /^_/u

Check warning on line 659 in main.js

View workflow job for this annotation

GitHub Actions / lint

'readSessionFile' is assigned a value but never used. Allowed unused vars must match /^_/u
backfillEntrypoints, backfillCustomTitles, revealIfSdkSession, notifyRendererProjectsChanged, sendStatus, populateCacheViaWorker,

Check warning on line 660 in main.js

View workflow job for this annotation

GitHub Actions / lint

'sendStatus' is assigned a value but never used. Allowed unused vars must match /^_/u
scanFoldersViaWorker, setRemoteRoots, resolveFolderDir, isIndexingFinished, coldScanInFlight } = sessionCache;
// see .ai/contexts/session-cache.md ("Projects query worker")
const { createProjectsWorkerClient } = require('./projects-worker-client');
Expand Down Expand Up @@ -2014,13 +2014,23 @@
}

ipcMain.handle('set-setting', async (_event, key, value) => {
if (key === 'global') await writeGlobalSettings(async () => { await setSetting(key, value); return value; });
if (key === 'global') {
if (value && Object.hasOwn(value, 'stopCheckCommand')) {
const checked = validateStopCheckCommand(value.stopCheckCommand);
if (!checked.ok) throw new TypeError(checked.error);
}
await writeGlobalSettings(async () => { await setSetting(key, value); return value; });
}
else await setSetting(key, value);
return { ok: true };
});

ipcMain.handle('merge-global-settings', async (_event, patch, remove) => {
if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new TypeError('Invalid global settings patch');
if (Object.hasOwn(patch, 'stopCheckCommand')) {
const checked = validateStopCheckCommand(patch.stopCheckCommand);
if (!checked.ok) throw new TypeError(checked.error);
}
const keys = Array.isArray(remove) ? remove.filter(key => typeof key === 'string') : [];
await writeGlobalSettings(() => writer.mergeGlobal(patch, keys));
return { ok: true };
Expand Down Expand Up @@ -3466,7 +3476,7 @@
// WSL profiles only work for plain terminals — Claude CLI sessions need the
// Windows shell because session data lives on the Windows filesystem.
const requestedProfile = resolveShell(effectiveProfileId);
const useWslProfile = isWslShell(requestedProfile.path) && isPlainTerminal;

Check warning on line 3479 in main.js

View workflow job for this annotation

GitHub Actions / lint

'useWslProfile' is assigned a value but never used. Allowed unused vars must match /^_/u
const shellProfile = (isWslShell(requestedProfile.path) && !isPlainTerminal)
? resolveShell('auto')
: requestedProfile;
Expand Down Expand Up @@ -4811,6 +4821,7 @@
try {
require('./src/main/triggers/trigger-watcher').start(createTriggerContext({
activeSessions, log, getCliStatus: (id) => cliSessionState.getStatus(id), projectsDir: PROJECTS_DIR,
getStopCheckCommand: () => (getSetting('global') || {}).stopCheckCommand ?? SETTING_DEFAULTS.stopCheckCommand,
lifecycle: triggerLifecycleDeps(),
sessionRequests: writer,
statusSources: {
Expand Down
13 changes: 12 additions & 1 deletion public/setting-defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const SETTING_DEFAULTS = {
activityReporting: false, // see .ai/contexts/activitywatch.md
logRetentionDays: 14,
remoteTriggers: false,
stopCheckCommand: null,
remoteHosts: [],
remoteRefreshMs: 300000,
schedulesTab: true,
Expand Down Expand Up @@ -93,8 +94,18 @@ function validateCustomArgs(value) {
return { ok: true };
}

function validateStopCheckCommand(value) {
if (value === null) return { ok: true };
if (!Array.isArray(value) || value.length < 1 || value.length > 32) return { ok: false, error: 'stopCheckCommand must be a nonempty argv array (max 32 elements)' };
if (typeof value[0] !== 'string' || !(typeof module !== 'undefined' && module.require ? module.require('path').isAbsolute(value[0])
: /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(value[0]))) return { ok: false, error: 'stopCheckCommand executable must be an absolute path' };
if (value.some(arg => typeof arg !== 'string' || arg.length > 4096 || /[\x00-\x1f\x7f-\x9f]/.test(arg))
|| value.reduce((length, arg) => length + arg.length, 0) > 8192) return { ok: false, error: 'stopCheckCommand arguments must be bounded strings without controls' };
return { ok: true };
}

if (typeof module !== 'undefined' && module.exports) {
module.exports = { SETTING_DEFAULTS, THEME_CHOICES, CODEX_CHOICES, BROWSER_MODES, normalizeBrowserSettings, validateCustomArgs,
module.exports = { SETTING_DEFAULTS, THEME_CHOICES, CODEX_CHOICES, BROWSER_MODES, normalizeBrowserSettings, validateCustomArgs, validateStopCheckCommand,
PROJECT_DELETE_PREVIEW_TIMEOUT_MS, PROJECT_DELETE_DIALOG_TIMEOUT_MS, PROJECT_DELETE_FOLLOWUP_TIMEOUT_MS,
PROJECT_DELETE_WORKTREE_INSPECTION_TIMEOUT_MS, PROJECT_DELETE_WORKTREE_REMOVE_TIMEOUT_MS, DIRECTORY_SCAN_MS };
}
56 changes: 56 additions & 0 deletions scripts/assert-named-test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#!/usr/bin/env node
'use strict';

const { spawn } = require('node:child_process');

const [, , name, file] = process.argv;
if (!name || !file) {
console.error('Usage: assert-named-test.cjs <exact test name> <file>');
process.exitCode = 2;
} else {
const timeoutMs = Number(process.env.ASSERT_NAMED_TEST_TIMEOUT_MS) || 60000;
const pattern = '^' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$';
const env = { ...process.env };
delete env.NODE_TEST_CONTEXT;
const child = spawn(process.execPath, ['--test-reporter=tap', '--test-name-pattern=' + pattern, file], {
stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32', env,
});
let timedOut = false, overflow = false, size = 0;
const chunks = [];
const kill = () => {
try { if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL'); else child.kill('SIGKILL'); }
catch { child.kill('SIGKILL'); }
};
process.once('SIGTERM', () => {
kill();
process.exit(143);
});
const collect = chunk => {
if (overflow) return;
size += chunk.length;
if (size > 1024 * 1024) {
overflow = true; kill();
child.stdout.destroy(); child.stderr.destroy();
} else chunks.push(chunk);
};
child.stdout.on('data', collect);
child.stderr.on('data', collect);
const timer = setTimeout(() => { timedOut = true; kill(); child.stdout.destroy(); child.stderr.destroy(); }, timeoutMs);
let spawnError = '';
child.on('error', error => { spawnError = error.message; });
child.on('close', code => {
clearTimeout(timer);
const output = spawnError || (overflow ? '' : Buffer.concat(chunks).toString('utf8'));
const records = output.split(/\r?\n/).filter(line => /^ok \d+ - /.test(line));
const matched = records.filter(line => line.replace(/^ok \d+ - /, '').replace(/ # SKIP\b.*$/, '') === name);
const skipped = matched.some(line => / # SKIP\b/.test(line));
const executed = matched.filter(line => !/ # SKIP\b/.test(line)).length;
if (!timedOut && !overflow && code === 0 && executed > 0 && !skipped) {
console.log(`PASS ${name} (${executed} executed, 0 failed)`);
} else {
console.error(`FAIL ${name}${timedOut ? ' timed out' : overflow ? ' output exceeded limit' : ' absent or failed'}`);
if (!timedOut && !overflow) console.error(output.slice(-4000));
process.exitCode = 1;
}
});
}
Loading
Loading