The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Windows: no window flashes, Codex's hooks review, held agents come back (#3085)
lingrd1347c248102d
diff --git a/AGENTS.md b/AGENTS.mdindex be453231e..561453e90 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -82,6 +82,21 @@ For product names, terminology, and visible copy, follow theautomatically reuses matching Desktop build inputs/version and otherwise buildsnormally; unrelated CLI, firmware or documentation merges do not force a rebuild.+# Windows rules++Details, measurements and sources: [docs/windows-rules.md](docs/windows-rules.md). Read it before changing code+that starts a process or before testing on Windows. Every feature must look and work on Windows as it does on a Mac.++1. Harness never opens a window the person did not ask for, not even for a moment. On Windows, `detached: true`+ makes everything the child starts flash a console window, and `windowsHide: true` does not fix it. Use+ `ownProcessGroup()` in the CLI and `startHidden`/`runHidden` in Desktop.+2. Your test scripts follow rule 1 too: a window from a test looks like a window from the product.+3. Prove it by recording the windows through the flow, in the person's session and on the signed build. Tests over SSH+ cannot see windows, and a detached PowerShell exits 0 having run nothing.+4. Found a new Windows mistake? Add it to the rules in the same change, with a test that fails if it comes back.+5. Meet a problem on Windows? First read how the Mac path solves it, and do the same thing the Windows way. The Mac is the+ reference for what the person sees; only the mechanism differs.+# Feature design rulesDetails, incidents and a checklist to copy: [docs/feature-design-rules.md](docs/feature-design-rules.md).diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 374e99a22..1a772fc36 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import { storeOldLeads } from './leads.test-support.js'import { applyCommand, assertUniqueMessageIds, commandSchema, LOOP_NOTICE_AT, swarmGridName, withoutCredentials, type Command, type CommandContext } from './commands.js'import { CREDENTIAL_MARKER, type CredentialKind } from './credentials.js'+import { readsRawReason } from './startFailure.js'import { sweepLiveness } from './liveness.js'import { SWITCH_UNCLAIMED_MS } from './tidy.js'import { defaultProfileId, hostLocalGrid, machineSlots, removalPreview, swarmGridRow } from './machines.js'@@ -3391,6 +3392,39 @@ describe('a failed start\'s reason', () => {f.state.starts![0]!.error = 'Its machine was removed from the Swarm.'expect(read(owner)).toBe('Its machine was removed from the Swarm.')})++ // The reported dead end: a Buddy's owner read only "its machine could not prepare or launch it", while the chat told them+ // the starter and the PM could read why. A Buddy chat is private to its owner, so the reason belongs there whole.+ it('writes a Buddy start\'s reason whole in its owner\'s chat, never the group line', () => {+ const f = fixture(); f.invite()+ const generation = f.state.people[0]!.generation+ const chat = { id: 'buddy-chat', kind: 'buddy', number: 1, title: "owner's Buddy", leadId: null, agentIds: [],+ archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0,+ audience: { people: [{ id: 'owner', generation }] } }+ f.state.conversations.push(chat as never)+ f.state.starts = [{ id: 's1', actorKey: 'person:owner', contributorId: 'owner', membershipGeneration: generation,+ machineOwnerId: 'owner', request: { conversationId: chat.id, machineId: 'mac', name: "nsonha777's Buddy",+ buddyOf: { personId: 'owner', generation } }, harnessId: null, dispatched: true, error: null }] as never+ const [notice] = f.run({ type: 'agent.startFailed', startId: 's1', error: RAW }, owner).messages+ expect(notice!.conversationId).toBe(chat.id)+ expect(notice!.text).toBe(`Could not start nsonha777's Buddy: ${RAW}`)+ expect(notice!.text).not.toContain('Whoever started it')+ })++ it('lets a Buddy chat\'s owner read the raw reason even when an agent made the start on another machine', () => {+ const f = fixture(); f.invite()+ const generation = f.state.people[0]!.generation+ const chat = { id: 'buddy-chat', kind: 'buddy', number: 1, title: "owner's Buddy", leadId: null, agentIds: [],+ archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0,+ audience: { people: [{ id: 'owner', generation }] } }+ f.state.conversations.push(chat as never)+ f.state.starts = [{ id: 's1', actorKey: 'agent:someone', contributorId: 'owner', membershipGeneration: generation,+ machineOwnerId: 'someone-else', request: { conversationId: chat.id, machineId: 'host-mac', name: "nsonha777's Buddy",+ buddyOf: { personId: 'owner', generation } }, harnessId: null, dispatched: true, error: RAW }] as never+ expect(visibleState(f.state, owner).starts![0]!.error).toBe(RAW)+ // A Swarm member who is not that chat's owner still reads only what the reason means.+ expect(readsRawReason(peer, f.state.starts![0]!, chat as never)).toBe(false)+ })})describe('the owner\'s rules, after review', () => {diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 82d880905..c757a3217 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -2858,6 +2858,14 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,// decision 18): nothing is started elsewhere. Written for nobody, this notice once left the round-device group without// a worker for an hour (2026-10-27).const group = conversation(state, start.request.conversationId)+ // A Buddy chat is read only by its owner (and its Buddy), so the reason their own Buddy did not start is written+ // whole, as liveness.ts's buddyNotice does for a start that timed out. The group notice below names neither the+ // machine nor the folder and promises its starter the reason somewhere they may not be allowed to read it.+ if (start.request.buddyOf) {+ message(group.id, `Could not start ${start.request.name}: ${command.error}${suspended ? `\n\n${suspended}` : ''}`,+ [], null, SYSTEM_ROW)+ break+ }// The failure that suspends its engine there says so once, and tags the machine's owner (engineHealth.ts).const failed = `${failureNotice(start.request.name, command.error, askedModel(start), isSwarmBuddyChat(group) ? undefined : coordinatorNameOf(groupProject(state, group)))}${suspended ? `\n\n${suspended}` : ''}`const told = failureRecipients(start, group)diff --git a/backend/src/superTabs/startFailure.ts b/backend/src/superTabs/startFailure.tsindex 36de97d94..f865b7289 100644--- a/backend/src/superTabs/startFailure.ts+++ b/backend/src/superTabs/startFailure.ts@@ -79,8 +79,12 @@ export function coordinatorCopy(state: SuperTabState, group: Conversation, recipreturn chat && coordinator && chat.id !== group.id && !recipients.includes(coordinator) ? { conversationId: chat.id, coordinator } : null}-/** Who reads a start's raw reason: whoever made it, its group's coordinator, and its machine's owner. */+/** Who reads a start's raw reason: whoever made it, its group's coordinator, its machine's owner, and a Buddy chat's owner. */export function readsRawReason(actor: Actor, start: AgentStart, group: Conversation | undefined): boolean {if (start.actorKey === actorKey(actor)) return true- return actor.kind === 'agent' ? !!group?.leadId && group.leadId === actor.agentId : actor.userId === start.machineOwnerId+ if (actor.kind === 'agent') return !!group?.leadId && group.leadId === actor.agentId+ if (actor.userId === start.machineOwnerId) return true+ // A Buddy chat is read only by its owner (buddies.ts openBuddyChat), so its owner reads why their own Buddy did not+ // start even when an agent made the start for them or the machine belongs to someone else.+ return !!group && isBuddyChat(group) && group.audience?.people.some(p => p.id === actor.userId) === true}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex be8d7e44b..1e3422fd4 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -80,6 +80,7 @@ import { probeThisMaster, startMaster, startMasterInForeground } from './masterPimport { startServiceProcess } from './serviceProcess.js'import { askDataFolderServer, isLocalSocketName, localSocketPath, refuseServedDataFolder, shortSocketFolder, servedFolderDeps } from './lib/localSocket.js'import { legacyDaemonStatus, localDaemonCall, localDaemonStatus } from './lib/daemonEndpoint.js'+import { ownProcessGroup } from './lib/windows/noWindow.js'import { PipeUnproven } from './lib/windows/pipeClient.js'import { ptyManifestUrl, ptyPlatformKey, type PtyEntry } from './lib/windows/ptyPayload.js'import { newerPtyForUpdate } from './lib/windows/ptyUpdateCommand.js'@@ -1095,7 +1096,7 @@ function promptForCallbackUrl(redirectUri: string): {function openInBrowser(url: string): void {const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'try {- const child = spawn(cmd, [url], { stdio: 'ignore', detached: true, shell: process.platform === 'win32' })+ const child = spawn(cmd, [url], { stdio: 'ignore', ...ownProcessGroup(), shell: process.platform === 'win32' })child.on('error', () => { /* no browser here (headless/ssh) — the printed URL is the fallback */ })child.unref()} catch { /* ignore */ }diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 8125bf23a..9f0aeaadf 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -767,8 +767,8 @@ describe('creating an agent', () => {} finally { Object.defineProperty(process, 'platform', platform) }// The launch's cleared names too, which the host must keep from its own environment (a grid launch's keys).const cleared = (vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1] as { clearEnv?: string[] }).clearEnv ?? []- expect(vi.mocked(createAndRegisterPane).mock.calls[0][0].paneLaunch).toEqual({ cwd: input.cwd, afterExit: windowsAfterExit('claude'),- ...(cleared.length ? { clearInherited: cleared } : {}) })+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0].paneLaunch).toMatchObject({ cwd: input.cwd, afterExit: windowsAfterExit('claude'),+ ...(cleared.length ? { clearInherited: cleared } : {}), env: { GRID_NO_UPDATE_CHECK: '1' } })expect(await setup().create(request())).toMatchObject({ ok: true })expect(vi.mocked(createAndRegisterPane).mock.calls[1][0].paneLaunch).toEqual({})})diff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.tsindex 41dbc4f65..ae72f68b5 100644--- a/cli/src/core/agents/fork.spec.ts+++ b/cli/src/core/agents/fork.spec.ts@@ -212,8 +212,8 @@ describe('forking an agent', () => {expect(await setup(source()).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ ok: true })} finally { Object.defineProperty(process, 'platform', platform) }const cleared = (vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1] as { clearEnv?: string[] }).clearEnv ?? []- expect(vi.mocked(createAndRegisterPane).mock.calls[0]![0].paneLaunch).toEqual({ cwd: work, afterExit: windowsAfterExit('claude'),- ...(cleared.length ? { clearInherited: cleared } : {}) })+ expect(vi.mocked(createAndRegisterPane).mock.calls[0]![0].paneLaunch).toMatchObject({ cwd: work, afterExit: windowsAfterExit('claude'),+ ...(cleared.length ? { clearInherited: cleared } : {}), env: { GRID_NO_UPDATE_CHECK: '1' } })})it('refuses a batch-file engine on Windows whose first message cmd.exe would read, by name', async () => {diff --git a/cli/src/core/agents/heldLaunches.spec.ts b/cli/src/core/agents/heldLaunches.spec.tsindex e835f6a13..cdf77a788 100644--- a/cli/src/core/agents/heldLaunches.spec.ts+++ b/cli/src/core/agents/heldLaunches.spec.ts@@ -28,6 +28,20 @@ function setup(rows: RegisteredSession[], answer: (only: ReadonlySet<string>) =>}describe('agents held until a service is ready', () => {+ it('says once why an agent stays held, and does not repeat a pass that changed nothing', async () => {+ let reason = 'the pty host has gone'+ const { held, log } = setup([row('a', HELD)], (only) => summary({ held: [...only], failed: [...only].map(agentId => ({ agentId, reason })) }))+ await held.boot(async () => {})+ await held.restoreHeld(); await held.restoreHeld(); await held.restoreHeld()+ reason = 'no such folder'+ await held.restoreHeld()+ expect(log.mock.calls.map(([line]) => line)).toEqual([+ '[restore] a · could not launch from held · the pty host has gone',+ '[restore] held · every service · launched 0 of 1 · 1 still waiting',+ '[restore] a · could not launch from held · no such folder',+ ])+ })+it.each(['removed', 'closed'] as const)('does not restore a queued row that was %s before its preparation', async state => {const h = setup([row('a', HELD)])await h.held.boot(async () => {})diff --git a/cli/src/core/agents/heldLaunches.ts b/cli/src/core/agents/heldLaunches.tsindex be9456b6b..4362c45a1 100644--- a/cli/src/core/agents/heldLaunches.ts+++ b/cli/src/core/agents/heldLaunches.ts@@ -53,6 +53,8 @@ export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps)// times in a day, each pass running about four login shells (`zsh -lic`, the launch environment) from the core,// whose synchronous spawns held the event loop the terminals' keystrokes wait on.let quietPasses = 0+ let lastPass = ''+ const lastReason = new Map<string, string>()const active = new Map<string, Promise<RestoreSummary>>()let nextAgent = 0const empty = (): RestoreSummary => ({ restored: [], skipped: [], failed: [], held: [], unsurveyed: [] })@@ -117,8 +119,18 @@ export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps)}retryContention(summary)if (rejected) throw failure- log(`[restore] held · ${service ?? 'every service'} · launched ${summary.restored.length} of ${held.length}`- + (summary.held.length ? ` · ${summary.held.length} still waiting` : ''))+ // Each reason an agent stays held, once until it changes: it was dropped, so eight agents waited with nothing to say why.+ for (const { agentId, reason } of summary.failed) {+ if (lastReason.get(agentId) === reason) continue+ lastReason.set(agentId, reason)+ log(`[restore] ${sid(agentId)} · could not launch from held · ${reason}`)+ }+ // A pass runs every 500 ms while the flights are full: on Windows, 2026-11-04, that was two lines a second for good.+ const pass = `${service ?? 'every service'} · launched ${summary.restored.length} of ${held.length}`+ if (pass !== lastPass || summary.restored.length) {+ lastPass = pass+ log(`[restore] held · ${pass}` + (summary.held.length ? ` · ${summary.held.length} still waiting` : ''))+ }return summary}diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex 8ef8c4053..9bd13c5cc 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -349,6 +349,44 @@ describe('the session input controller\'s dependencies', () => {expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual([])})+ // Codex on Windows takes a paste as keys, and an Enter too soon became a newline in it, stuck in the composer (lib/pasteOnScreen.ts).+ it.each([+ ['once the paste shows and has stopped changing', [{ draft: false, screen: 'empty' }, { draft: true, screen: 'pasted' }, { draft: true, screen: 'pasted' }], false],+ ['anyway at its limit, and says so', [{ draft: false, screen: 'empty' }], true],+ ])('on Windows, presses Codex\'s Enter %s', async (_name, panes, warned) => {+ const platform = process.platform+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true })+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ agents.set('c1', { ...agents.get('a1')!, agentId: 'c1', engine: 'codex' })+ let read = 0, entered = false+ const write = messageWriter({+ readScreen: vi.fn(async (_session: unknown, capture: string | null) => ({ messageHold: null, pane: { draft: capture === 'pasted' } })) as unknown as InputDeps['readScreen'],+ resolve: (id) => agents.get(id),+ terminal: {+ validateTerminal: vi.fn(async () => true),+ captureTerminal: vi.fn(async () => panes[Math.min(read++, panes.length - 1)]!.screen),+ submitTerminalAction: vi.fn(async (_id: string, _text: string, options?: { beforeEnter?: () => Promise<string | null> }) => {+ expect(await options!.beforeEnter!()).toBeNull()+ entered = true+ return ok+ }),+ } as unknown as InputDeps['terminal'],+ })+ vi.useFakeTimers()+ try {+ const written = write('c1', 'a long message')+ await vi.advanceTimersByTimeAsync(10_000)+ await written+ } finally {+ vi.useRealTimers()+ Object.defineProperty(process, 'platform', { value: platform, configurable: true })+ agents.delete('c1')+ }+ expect(entered).toBe(true)+ expect(warn.mock.calls.some(([line]) => String(line).includes('did not show in its composer'))).toBe(warned)+ warn.mockRestore()+ })+it('reads the pane again right before the Enter, and gives the reason not to press it, a popup of the message\'s own aside', async () => {const screens = [READY_PANE, CLAUDE_PERMISSION, READY_PANE, null, READY_PANE, READY_PANE, `────────────\n❯ /mo\n────────────\n /model Set the AI model`]const answers: Array<string | null> = []@@ -664,6 +702,20 @@ describe('createInput', () => {])expect(log.mock.calls.flat().filter((line) => String(line).includes('slash-command adapted'))).toHaveLength(1)})++ it('logs a held delivery once, not once for every retry of the same delivery id', () => {+ const inputs = createInput(deps().deps)+ vi.spyOn(inputs.input, 'submit').mockImplementation(() => {})+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ // The backend retries a held delivery every second under the same id.+ inputs.submitAgent('s1', 'hello', 'd1')+ inputs.submitAgent('s1', 'hello', 'd1')+ inputs.submitAgent('s1', 'hello', 'd2')+ // A person's own message has no delivery id and is logged every time, as before.+ inputs.submitAgent('s1', 'typed')++ expect(log.mock.calls.flat().filter((line) => String(line).includes(' recv · '))).toHaveLength(3)+ })})describe('message', () => {diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 3292931be..3534ba37d 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -21,6 +21,7 @@ import type { RegisteredSession } from '../lib/registry.js'import type { MoveGate } from '../lib/hostMove/gate.js'import { SessionInputController, type MessageReceipt, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'import { passingHold } from '../lib/messageHolds.js'+import { pasteComesAsKeys, pasteOnScreen } from '../lib/pasteOnScreen.js'import type { ScreenReader } from '../lib/screenReader.js'import type { SubmissionReader } from '../lib/submissionReader.js'import type { ScreenReading } from '../engines/facets/screen.js'@@ -110,6 +111,13 @@ export function messageWriter({ readScreen, resolve, terminal: { captureTerminalelse promptTyped?.(session, capture, screen)return submitTerminalAction(id, text, {beforeEnter: async () => {+ if (pasteComesAsKeys(session.engine)) {+ const landed = await pasteOnScreen(async () => {+ const now = await captureTerminal(id)+ return { draft: (await readScreen(launchBound(session, resolve(id)), now))?.pane.draft === true, screen: now }+ }, capture)+ if (!landed) console.warn(`[inject] ${sid(id)} the paste did not show in its composer in time; pressing Enter anyway`)+ }// A read that came back empty, or a composer caught between frames, is asked again for a moment// (a re-attach can blank one capture): only what is on screen holds the Enter back, never a// read that failed once. Still not read after that, it is held, as nothing says it is safe.@@ -304,6 +312,20 @@ export function createInput(deps: InputDeps) {releaseInput()}}+ // A held delivery is retried by the backend every second; it is the same message, so the receive is+ // logged once per delivery id instead of once per attempt. Bounded: an id that has scrolled out is+ // logged again rather than remembered for the life of the daemon.+ const loggedDeliveries = new Set<string>()+ const firstReceipt = (deliveryId: string | undefined): boolean => {+ if (!deliveryId) return true+ if (loggedDeliveries.has(deliveryId)) return false+ loggedDeliveries.add(deliveryId)+ if (loggedDeliveries.size > 256) {+ const oldest = loggedDeliveries.values().next().value+ if (oldest !== undefined) loggedDeliveries.delete(oldest)+ }+ return true+ }const submitAgent = (id: string, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void => {const record = resolve(id)const sessionId = record?.sessionId ?? id@@ -313,10 +335,11 @@ export function createInput(deps: InputDeps) {// per-engine adaptation happens here — an unknown slash command would otherwise land as a visible// error in the user's terminal instead of running their turn.const adapted = adaptSlashCommand(content, engine)- if (adapted !== content) {+ const log = firstReceipt(deliveryId)+ if (log && adapted !== content) {console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)}- console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)+ if (log) console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)const target = record?.agentId ?? sessionIdif (receipt) input.submit(target, adapted, deliveryId, inputContext, receipt)else if (inputContext) input.submit(target, adapted, deliveryId, inputContext)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 8350ab7d1..04b471e18 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -47,7 +47,7 @@ import { VERSION } from '../version.js'import { isLocalOnly, withoutUpdate } from '../lib/cardUpdate.js'import { elapsedSecondsOf } from '../lib/footerTimer.js'import { sqlitePreflightMessage } from '../lib/sqliteAvailability.js'-import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'+import { loginShellCaptureLine, warmLoginShellEnvironment } from '../lib/loginShellEnv.js'import { enableOffThreadExec } from '../lib/offThreadExec.js'import type { AppSwarms } from '../cable/cableSession.js'import type { UnreadNotification } from '../lib/notificationRead.js'@@ -675,10 +675,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {{const t0 = Date.now()void loginShellEnvPromise.then((captured) => {- const count = Object.keys(captured).length- console.log(count- ? `[env] read ${count} variables from the login shell in ${Date.now() - t0}ms (engine one-shots only)`- : '[env] could not read a login shell environment — engine one-shots use the daemon environment only')+ const line = loginShellCaptureLine(Object.keys(captured).length, Date.now() - t0)+ if (line) console.log(line)})}@@ -2506,6 +2504,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// pane read is.const restoreOn = restoreTerminals({backendFor: (runtime) => terminals.backendFor(runtime),+ newPanesOn: (backend) => isDrainBackend(backend) ? createBackend : null,listTmuxPanes: () => listTmuxPanes(),cwd: homedir(),label: (engine) => buildHarnessSessionLabel(engine),diff --git a/cli/src/dsh/shell.ts b/cli/src/dsh/shell.tsindex 088b3903b..c00708734 100644--- a/cli/src/dsh/shell.ts+++ b/cli/src/dsh/shell.ts@@ -11,6 +11,7 @@ import { managedNodePath } from '../lib/nodeRuntime.js'import { shellSingleQuote } from '../lib/shellQuote.js'import { findGitBash, INSTALL_GIT_FOR_WINDOWS } from '../lib/windows/gitBash.js'import { endGitBashTree, gitBashTreeDeps } from '../lib/windows/gitBashTree.js'+import { ownProcessGroup } from '../lib/windows/noWindow.js'export interface DshCommandOptions {cwd: string@@ -167,8 +168,9 @@ export function spawnDshCommand(cwd: opts.cwd,env: { ...process.env, ...env, ...(opts.env ?? {}) },stdio: ['ignore', 'pipe', 'pipe'],- // Its own process group, so stopping it stops what it started (`sh -c node …`).- detached: true,+ // Its own process group, so stopping it stops what it started (`sh -c node …`). Windows ends the tree instead, and+ // Git Bash detached there would flash a window for each program it starts (docs/windows-rules.md).+ ...ownProcessGroup(),})}diff --git a/cli/src/dsh/viewerLedger.spec.ts b/cli/src/dsh/viewerLedger.spec.tsindex 18b8c479e..0593055d2 100644--- a/cli/src/dsh/viewerLedger.spec.ts+++ b/cli/src/dsh/viewerLedger.spec.ts@@ -3,7 +3,49 @@ import { spawn, type ChildProcess } from 'node:child_process'import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { ViewerLedger, processStartedAt } from './viewerLedger.js'+import type { ProcessRow } from '../lib/processTable.js'+import { ViewerLedger, processStartedAt, windowsViewerLeftovers } from './viewerLedger.js'++// Windows has no `ps`, so nothing was ever reaped, and a viewer's parent is gone once it runs (Git Bash's fork): twelve generations+// of one viewer were running on DESKTOP-0TFH0OJ on 2026-11-04.+describe('a viewer left over on Windows', () => {+ const fileTime = (ms: number) => `w:${(BigInt(ms) + 11_644_473_600_000n) * 10_000n}`+ const row = (pid: number, parentPid: number, args: string, startedMs: number): ProcessRow =>+ ({ pid, parentPid, executable: 'node.exe', startMarker: fileTime(startedMs), args })+ const entry = { pid: 50, startedAt: 1_000_000, agentId: 'a', dshId: 'acme/thing', viewerDir: 'C:\\Users\\Me\\.harness\\dsh\\acme\\thing' }+ const VIEWER = '"C:\\Program Files\\nodejs\\node.exe" C:/Users/me/.harness/dsh/acme/thing/toolchain/viewer.mjs'++ it('is the program from its folder whose parent has gone, started since the ledger says', () => {+ expect(windowsViewerLeftovers(entry, [row(9, 1, 'host', 1), row(60, 999, VIEWER, 1_000_500)])).toEqual([60])+ })++ it('is also its launcher, when that still runs and started when the ledger says', () => {+ expect(windowsViewerLeftovers(entry, [row(50, 999, 'bash.exe', 1_000_100)])).toEqual([50])+ expect(windowsViewerLeftovers(entry, [row(50, 999, 'bash.exe', 5_000_000)])).toEqual([])+ })++ it.each([+ ['an agent ran from that folder: its parent is alive', [row(9, 1, 'claude', 1), row(60, 9, VIEWER, 1_000_500)]],+ ['it started long before this viewer: an old pid or an older run', [row(60, 999, VIEWER, 900_000)]],+ ['it runs from another folder', [row(60, 999, '"node.exe" C:/Users/me/.harness/dsh/acme/thing2/viewer.mjs', 1_000_500)]],+ ])('leaves it alone when %s', (_name, rows) => {+ expect(windowsViewerLeftovers(entry, rows)).toEqual([])+ })++ it('ends them, and keeps the ledger when the process table could not be read', () => {+ const file = `${mkdtempSync(join(tmpdir(), 'viewer-ledger-'))}/viewers.json`+ const killed: number[] = []+ const table = { rows: null as ProcessRow[] | null }+ const ledger = new ViewerLedger({ file, platform: 'win32', windowsRows: () => table.rows, kill: pid => { killed.push(pid) } })+ ledger.add(entry)+ expect(ledger.reapOrphans()).toEqual([])+ expect(ledger.read()).toEqual([entry])+ table.rows = [row(60, 999, VIEWER, 1_000_500)]+ expect(ledger.reapOrphans()).toEqual([entry])+ expect(killed).toEqual([60])+ expect(ledger.read()).toEqual([])+ })+})describe('ViewerLedger', () => {let dir: stringdiff --git a/cli/src/dsh/viewerLedger.ts b/cli/src/dsh/viewerLedger.tsindex 26800b957..69031830b 100644--- a/cli/src/dsh/viewerLedger.ts+++ b/cli/src/dsh/viewerLedger.ts@@ -16,8 +16,47 @@ import { execFileSync } from 'node:child_process'import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { dirname, join } from 'node:path'import { env } from '../config/env.js'+import type { ProcessRow } from '../lib/processTable.js'+import { ptyHostBinary } from '../lib/ptyHost/launch.js'+import { WINDOWS_PS_TIMEOUT_MS, windowsProcessTable } from '../lib/windows/processTable.js'+import { windowsStartTime } from '../lib/windows/treeKill.js'import { killPidGroup } from './shell.js'+const WINDOWS_EPOCH_MS = 11_644_473_600_000n+/** [ms] as a Windows start time (100 ns ticks since 1601), as `windowsStartTime` reads one. */+const asWindowsTime = (ms: number): bigint => (BigInt(Math.trunc(ms)) + WINDOWS_EPOCH_MS) * 10_000n++/** Windows' process table now, or null when it could not be read. */+function readWindowsRows(): ProcessRow[] | null {+ try {+ const binary = ptyHostBinary()+ if (!binary) return null+ const output = execFileSync(binary, ['ps', '--json'], { encoding: 'utf8', timeout: WINDOWS_PS_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024, windowsHide: true })+ return windowsProcessTable(JSON.parse(output))+ } catch { return null }+}++/**+ * The pids of what remains of a ledgered viewer on Windows: its launcher, and a program running from its folder whose parent+ * has gone. The launcher alone is not enough: what Git Bash runs is a process of its own whose Windows parent has exited+ * (lib/windows/gitBashTree.ts), so nothing walks down to it once the launcher ends with the daemon. A parent still running means+ * something else started it, an agent in a pane for one, and it is left alone, as is what started before this viewer.+ */+export function windowsViewerLeftovers(entry: ViewerLedgerEntry, rows: readonly ProcessRow[]): number[] {+ const since = asWindowsTime(entry.startedAt - START_TOLERANCE_MS)+ const started = (row: ProcessRow) => windowsStartTime(row.startMarker)+ const fresh = (row: ProcessRow) => { const at = started(row); return at !== null && at >= since }+ const folder = `${entry.viewerDir.replaceAll('\\', '/').replace(/\/+$/, '').toLowerCase()}/`+ const live = new Set(rows.map(row => row.pid))+ const launcher = rows.filter(row => {+ const at = started(row)+ return row.pid === entry.pid && at !== null && at >= since && at <= asWindowsTime(entry.startedAt + START_TOLERANCE_MS)+ })+ const programs = rows.filter(row => row.pid !== entry.pid && !live.has(row.parentPid) && fresh(row)+ && row.args.replaceAll('\\', '/').toLowerCase().includes(folder))+ return [...launcher, ...programs].map(row => row.pid)+}+export interface ViewerLedgerEntry {pid: number/** ms epoch when the daemon spawned it; compared against the live process's start time. */@@ -51,6 +90,9 @@ export interface ViewerLedgerDeps {startedAt?: (pid: number) => number | nullkill?: (pid: number) => voidlog?: (line: string) => void+ platform?: NodeJS.Platform+ /** Windows' process table; null when it could not be read. */+ windowsRows?: () => ProcessRow[] | null}export class ViewerLedger {@@ -106,6 +148,20 @@ export class ViewerLedger {const startedAt = this.deps.startedAt ?? processStartedAtconst kill = this.deps.kill ?? ((pid: number) => { killPidGroup(pid) })const reaped: ViewerLedgerEntry[] = []+ if ((this.deps.platform ?? process.platform) === 'win32') {+ // Windows has no `ps` for the check below. A table that could not be read keeps the ledger for the next start.+ const rows = (this.deps.windowsRows ?? readWindowsRows)()+ if (!rows) return []+ for (const entry of entries) {+ const pids = windowsViewerLeftovers(entry, rows)+ for (const pid of pids) kill(pid)+ if (!pids.length) continue+ reaped.push(entry)+ this.deps.log?.(`[dsh] reaped orphaned ${entry.dshId} viewer: ${pids.length} process(es)`)+ }+ this.write([])+ return reaped+ }for (const entry of entries) {const live = startedAt(entry.pid)if (live === null) continue // gone, or unknowable — a pid we cannot vouch for is left alonediff --git a/cli/src/engines/codex/hooksReview.spec.ts b/cli/src/engines/codex/hooksReview.spec.tsnew file mode 100644index 000000000..3bc15df94--- /dev/null+++ b/cli/src/engines/codex/hooksReview.spec.ts@@ -0,0 +1,33 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import { WAITING } from '../../superTabs/terminal.js'+import { hooksReviewSkipKeys, screen } from './screen.js'+import type { MessageHold } from '../facets/screen.js'++/** As codex-cli 0.163.0 drew it on DESKTOP-0TFH0OJ (2026-11-04): another program's two hooks in `hooks.json`, Harness's trusted. */+const REVIEW = readFileSync(new URL('../../superTabs/fixtures/screens/codex-0163-hooks-review.txt', import.meta.url), 'utf8')++// Nobody sits at a Swarm agent's pane, so another program's new hook stopped its start for good. Esc goes on with those hooks+// off and records nothing: only a person may trust a hook, so "Trust all" is never pressed.+describe("skipping Codex's review of another program's hooks", () => {+ it('is Esc, as the footer says, and never a row', () => {+ expect(hooksReviewSkipKeys(REVIEW)).toEqual(['Escape'])+ })++ it.each([+ ['Trust all highlighted', REVIEW.replace('› 1. Review hooks', ' 1. Review hooks').replace(' 2. Trust all and continue', '› 2. Trust all and continue')],+ ['rows in another order', REVIEW.replace(' 2. Trust all and continue\n 3. Continue without trusting (hooks won\'t run)', ' 2. Continue without trusting (hooks won\'t run)\n 3. Trust all and continue')],+ ['an extra row', REVIEW.replace(' 3. Continue', ' 4. Allow everything\n 3. Continue')],+ ['no row that continues without trusting', REVIEW.replace(" 3. Continue without trusting (hooks won't run)\n", '')],+ ['another footer', REVIEW.replace('enter confirm · esc skip', 'enter confirm · esc quit')],+ ['no footer', REVIEW.replace('\n\n enter confirm · esc skip', '')],+ ['another heading', REVIEW.replace('Hooks need review', 'Plugins need review')],+ ['the screen left in scrollback above the composer', `${REVIEW}\n\n› Write tests\n gpt-6-astra high · ~/project\n`],+ ])('sends nothing on %s', (_name, capture) => {+ expect(hooksReviewSkipKeys(capture)).toBeNull()+ })++ it('reads the screen as one that waits for a person', () => {+ expect(WAITING.has(screen.inspect(REVIEW).messageHold as MessageHold)).toBe(true)+ })+})diff --git a/cli/src/engines/codex/screen.ts b/cli/src/engines/codex/screen.tsindex 3db09ce33..bbf039272 100644--- a/cli/src/engines/codex/screen.ts+++ b/cli/src/engines/codex/screen.ts@@ -68,6 +68,23 @@ export function openRestrictedKeys(capture: string): string[] | null {}const RESTRICTED_SENTENCE = 'Config, hooks, and exec policies from untrusted folders stay disabled.'+/**+ * The key that goes past Codex's review of hooks it has not seen, or null unless the capture is exactly that screen. Only for a+ * Swarm agent's own pane, which nobody sits at (superTabs/startScreen.ts): another program's new hook stopped every such start on+ * a computer that has one (Orca's, on DESKTOP-0TFH0OJ, 2026-11-04). Harness's own hooks are already recorded as reviewed+ * (kit/hookReview.ts). It is Esc, which the footer says skips, never a row: "Trust all" is a person's to press, and skipping+ * records nothing, so the same question waits for them in the next pane they open.+ */+export function hooksReviewSkipKeys(capture: string): string[] | null {+ const lines = stripAnsi(capture).replace(/ /g, ' ').split('\n').map(line => line.trim()).filter(Boolean)+ if (lines.filter(line => line === 'Hooks need review').length !== 1) return null+ const rows = lines.filter(line => /^[›>]?\s*\d+\./.test(line)).map(line => line.replace(/^[›>]\s*/, ''))+ const menu = rows.length === 3 && rows[0] === '1. Review hooks' && rows[1] === '2. Trust all and continue'+ && rows[2] === "3. Continue without trusting (hooks won't run)"+ const firstRowHighlighted = lines.some(line => /^[›>]\s*1\. Review hooks$/.test(line))+ return menu && firstRowHighlighted && /^enter\s+confirm\s+·\s+esc\s+skip$/.test(lines[lines.length - 1]) ? ['Escape'] : null+}+function takeover(capture: string, currentUi: string): PaneTakeover | null {const lines = stripAnsi(capture).replace(/\u00a0/g, ' ').split('\n')const bottom = lines.filter(line => line.trim()).slice(-3)diff --git a/cli/src/engines/kit/nativeHookFiles.spec.ts b/cli/src/engines/kit/nativeHookFiles.spec.tsindex fe5220820..7400d6930 100644--- a/cli/src/engines/kit/nativeHookFiles.spec.ts+++ b/cli/src/engines/kit/nativeHookFiles.spec.ts@@ -2,7 +2,17 @@ import { constants, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSimport { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, expect, it, vi } from 'vitest'-import { inspectHookFile, runHookPreparation } from './nativeHookFiles.js'+import { hookFileVersion, inspectHookFile, runHookPreparation } from './nativeHookFiles.js'++// Windows moved a just-published file's change time when its handle closed (measured on DESKTOP-0TFH0OJ, 2026-11-05), after the+// publication had read it: Kilo's, Pi's and Amp's plugins were written, then reported as failed, at every start.+it('leaves the change time out of a file\'s version on Windows alone', () => {+ const stat = { dev: 1n, ino: 2n, uid: 0n, mode: 0o644n, size: 5n, mtimeNs: 7n }+ const closed = (ctimeNs: bigint) => ({ ...stat, ctimeNs }) as never+ expect(hookFileVersion(closed(8n), 'win32')).toBe(hookFileVersion(closed(9n), 'win32'))+ expect(hookFileVersion(closed(8n), 'darwin')).not.toBe(hookFileVersion(closed(9n), 'darwin'))+ expect(hookFileVersion({ ...stat, mtimeNs: 70n, ctimeNs: 8n } as never, 'win32')).not.toBe(hookFileVersion(closed(8n), 'win32'))+})const fault = vi.hoisted(() => ({ sync: false, write: false, windows: false, writableOpens: 0, onSync: undefined as ((fd: number) => void) | undefined, openAs: undefined as string | undefined, onStat: undefined as ((file: unknown, options: unknown) => void) | undefined }))vi.mock('./windowsFiles.js', async original => {diff --git a/cli/src/engines/kit/nativeHookFiles.ts b/cli/src/engines/kit/nativeHookFiles.tsindex 83e8f1d74..414393699 100644--- a/cli/src/engines/kit/nativeHookFiles.ts+++ b/cli/src/engines/kit/nativeHookFiles.ts@@ -10,7 +10,13 @@ import { isRoot, renameReplacing, unchangedFlushFlags } from './windowsFiles.js'import { HookPreparationHeld } from './hookHeld.js'// Every importer of the class from here keeps working; windowsFiles.ts imports it from the leaf, with no cycle.export { HookPreparationHeld }-const version = (info: BigIntStats) => `${info.dev}:${info.ino}:${info.uid}:${info.mode}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`+/** A file's version. Without its change time on Windows, which moves when a file's last handle closes, after the rename that+ * published it (measured 2026-11-05): a publication that read it first then took its own close for someone else's edit. */+export function hookFileVersion(info: BigIntStats, platform: NodeJS.Platform = process.platform): string {+ const written = `${info.dev}:${info.ino}:${info.uid}:${info.mode}:${info.size}:${info.mtimeNs}`+ return platform === 'win32' ? written : `${written}:${info.ctimeNs}`+}+const version = (info: BigIntStats) => hookFileVersion(info)const fileIdentity = (info: BigIntStats) => `${info.dev}:${info.ino}:${info.uid}:${info.mode}`export interface HookFilePublication { verify(): void }export interface HookPreparationProof {diff --git a/cli/src/engines/kit/nativeHookYaml.spec.ts b/cli/src/engines/kit/nativeHookYaml.spec.tsindex 3842f2bfa..8f382e34a 100644--- a/cli/src/engines/kit/nativeHookYaml.spec.ts+++ b/cli/src/engines/kit/nativeHookYaml.spec.ts@@ -1,7 +1,7 @@import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { HERMES_HOOK_SETTINGS } from '../hermes/contract.js'import { installNativeYamlHooks } from './nativeHookYaml.js'@@ -35,6 +35,29 @@ function profileFirst(): void {gate.after = files => { if (files[0] === join(profile, 'config.yaml')) done() }}+describe('a large settings file', () => {+ const rule = () => ({ ...HERMES_HOOK_SETTINGS, home })+ const command = (at: string) => `node /fixture/notify.mjs --port 4242 --data-dir /fixture/data --hermes-home ${at} --engine hermes`+ const lines = (count: number) => Array.from({ length: count }, (_, at) => `key_${at}: value # a note`).join('\n') + '\n'+ beforeEach(() => {+ vi.spyOn(console, 'log').mockImplementation(() => {}); vi.spyOn(console, 'error').mockImplementation(() => {})+ writeFileSync(join(profile, 'config.yaml'), 'model: y\n')+ })++ it('takes the hooks when it is as long as Hermes\'s own, which held every Hermes agent', async () => {+ writeFileSync(join(home, 'config.yaml'), lines(6_000))+ expect(await installNativeYamlHooks(rule(), command)).toBe(true)+ expect(readFileSync(join(home, 'config.yaml'), 'utf8')).toContain(`--hermes-home ${home}`)+ })++ it('still refuses one past the limit, and leaves it as it is', async () => {+ const huge = lines(40_000)+ writeFileSync(join(home, 'config.yaml'), huge)+ expect(await installNativeYamlHooks(rule(), command)).toBe(false)+ expect(readFileSync(join(home, 'config.yaml'), 'utf8')).toBe(huge)+ })+})+it('says what each home did in the homes\' order, whichever home finishes first', async () => {const lines: string[] = []vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { lines.push(args.join(' ')) })diff --git a/cli/src/engines/kit/nativeHookYaml.ts b/cli/src/engines/kit/nativeHookYaml.tsindex 52688a577..485aca2d9 100644--- a/cli/src/engines/kit/nativeHookYaml.ts+++ b/cli/src/engines/kit/nativeHookYaml.ts@@ -7,6 +7,10 @@ import { isManagedHookCommand } from './notifyHooks.js'import { nativeHookHomes, type NativeHookHomes } from './nativeHookHomes.js'import { failure, type HookFileRemoval } from './hookRemoval.js'+/** The most YAML tokens a settings file may have. Hermes's own config of 134 KB, 2,438 lines, was over the 4,096 this was, so its+ * hooks never installed and every Hermes agent stayed held (DESKTOP-0TFH0OJ, 2026-11-05). The 1 MiB file limit bounds the parse too. */+const MAX_YAML_TOKENS = 256 * 1024+export interface NativeYamlHooks {home: stringhomes: NativeHookHomes@@ -274,8 +278,9 @@ async function installIn(rule: NativeYamlHooks, cmd: string, home: string, optioconst budget = new NativeEvidenceBudget()let tokens = 0for (const _token of new Lexer().lex(config)) {- budget.step()- if (++tokens > 4096) throw new HookPreparationHeld('the YAML configuration exceeds its structure limit')+ // Bounded by the deadline and this count, not the budget's operations: those are fewer than an ordinary file's tokens.+ budget.remaining()+ if (++tokens > MAX_YAML_TOKENS) throw new HookPreparationHeld('the YAML configuration exceeds its structure limit')}// Parse before examining markers: marker-like text inside a quoted scalar// is somebody else's configuration. Duplicate managed mappings from olderdiff --git a/cli/src/engines/nativeHookPreparation.spec.ts b/cli/src/engines/nativeHookPreparation.spec.tsindex a5dcdbcfe..620cfd1e1 100644--- a/cli/src/engines/nativeHookPreparation.spec.ts+++ b/cli/src/engines/nativeHookPreparation.spec.ts@@ -239,7 +239,7 @@ it('holds a large YAML structure before parsing or modifying it', async () => {const { root } = await fixture()const { installHermesHooks } = await import('./nativeHooks.js')const home = join(root, 'HERMES_HOME'), file = join(home, 'config.yaml')- const config = Array.from({ length: 5000 }, (_, index) => `key${index}: value`).join('\n')+ const config = Array.from({ length: 60_000 }, (_, index) => `key${index}: value`).join('\n')writeFileSync(file, config)expect(await installHermesHooks(4242, home)).toBe(false)expect(readFileSync(file, 'utf8')).toBe(config)diff --git a/cli/src/lib/appModels.ts b/cli/src/lib/appModels.tsindex 1ce25044d..efc741301 100644--- a/cli/src/lib/appModels.ts+++ b/cli/src/lib/appModels.ts@@ -211,7 +211,7 @@ export function appEngineOps(env: NodeJS.ProcessEnv, request: typeof fetch = fetconst log = openSync(join(logDir, logName), 'a', 0o600)try {// Its own process group, so it outlives this daemon and Stop ends it with whatever it started.- const child = spawn(binary, args, { env: { ...env, ...extra }, detached: true, stdio: ['ignore', log, log] })+ const child = spawn(binary, args, { env: { ...env, ...extra }, detached: true, windowsHide: true, stdio: ['ignore', log, log] })child.unref()if (!child.pid) throw new AppStartError('The model could not start. Try again.')return child.piddiff --git a/cli/src/lib/connectors/command.ts b/cli/src/lib/connectors/command.tsindex cd9957da8..f0fe1344d 100644--- a/cli/src/lib/connectors/command.ts+++ b/cli/src/lib/connectors/command.ts@@ -9,6 +9,7 @@ import { call, CallFailure, OFFICIAL_HOSTS, type Output } from './call.js'import * as gateway from './gateway.js'import { forgetPage, PageServer, rememberPage, runningPage } from './page.js'import { refresh, refreshDue } from './renew.js'+import { ownProcessGroup } from '../windows/noWindow.js'import { ConnectorError, locked, RENAMED, Store, validateCode } from './store.js'export const connectionsUsage = `Connected services (Linear, Notion, GitHub, Google…), shared by every local agent:@@ -31,7 +32,7 @@ export function openInBrowser(url: string, env: NodeJS.ProcessEnv = process.env)const harnessBrowser = ['/usr/bin/hn-browser'].find(existsSync)const command = harnessBrowser ?? (process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open')try {- const child = spawn(command, [url], { stdio: 'ignore', detached: true, shell: process.platform === 'win32', env })+ const child = spawn(command, [url], { stdio: 'ignore', ...ownProcessGroup(), shell: process.platform === 'win32', env })child.on('error', () => { /* No browser here (headless, ssh): the printed address is the way. */ })child.unref()return true@@ -45,7 +46,7 @@ async function openPage(vault: Store, io: Output): Promise<number> {let url = await runningPage(vault)if (!url) {const child = spawn(process.execPath, [...process.execArgv, process.argv[1], 'connections', 'serve', '--background'],- { stdio: 'ignore', detached: true, env: process.env })+ { stdio: 'ignore', detached: true, windowsHide: true, env: process.env })child.unref()for (let tries = 0; tries < 40 && !url; tries++) { await sleep(100); url = await runningPage(vault) }if (!url) { io.err('Could not open Connections.'); return 1 }diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex fa6f26208..455766697 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -127,7 +127,8 @@ export async function createAndRegisterPane<Ref extends TerminalRuntimeRef = Tercommand: deps.argv,...(deps.current ? { current: deps.current } : {}),...(deps.onDispatch ? { onDispatch: deps.onDispatch } : {}),- ...(deps.env ? { env: deps.env } : {}),+ // The caller's own variables win over the pane's PATH rule (lib/windows/engineStart.ts `windowsPaneLaunch`).+ ...(deps.paneLaunch?.env || deps.env ? { env: { ...(deps.paneLaunch?.env ?? {}), ...(deps.env ?? {}) } } : {}),})if (spawned.state !== 'succeeded') {console.warn(`[agent] create ${deps.engine} failed · tmux could not open a pane · ${spawned.reason ?? ''}`)diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.tsindex 2c527a386..5780105c3 100644--- a/cli/src/lib/gitProject.ts+++ b/cli/src/lib/gitProject.ts@@ -6,6 +6,7 @@ import { promisify } from 'node:util'import { placeholderBranch, plausibleBranchName, worktreeFolderName } from './agentNames.js'import { redactSecretsInText } from './logBundle.js'import { withinRoots } from './pathContainment.js'+import { ownProcessGroup } from './windows/noWindow.js'const exec = promisify(execFile)@@ -484,7 +485,7 @@ function worktreeAdd(source: string, args: string[], timeout: number, extraEnv:const failed = (reason: string, running = false): WorktreeAddFailure => ({ ok: false, reason, stderr, timedOut, diskFull: diskFull({ stderr }), running })const late = () => `timed out after ${Math.round(timeout / 1000)} s`const child = spawn('git', gitArgs(source, args), {- env: { ...gitEnv(process.env), ...extraEnv }, stdio: ['ignore', 'ignore', 'pipe'], detached: process.platform !== 'win32', windowsHide: true,+ env: { ...gitEnv(process.env), ...extraEnv }, stdio: ['ignore', 'ignore', 'pipe'], ...ownProcessGroup(),})child.stderr.on('data', (chunk: Buffer) => { if (stderr.length < 64 * 1024) stderr += chunk.toString() })const timer = setTimeout(() => {diff --git a/cli/src/lib/gridBinary.ts b/cli/src/lib/gridBinary.tsindex 46807488d..60bf3dc6a 100644--- a/cli/src/lib/gridBinary.ts+++ b/cli/src/lib/gridBinary.ts@@ -6,10 +6,10 @@* itself: that is the models service's (services/models.ts), which runs in a process of its own* (docs/design/2026-10-06-core-boundary-next.md, step 7). It reads files and never spawns.*/-import { accessSync, constants, readFileSync } from 'node:fs'-import { join, sep } from 'node:path'+import { accessSync, constants, existsSync, readFileSync, statSync } from 'node:fs'+import { join, sep, win32 } from 'node:path'import { env } from '../config/env.js'-import { binaryOnPath } from './binaryOnPath.js'+import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'/** The command, as it is named on PATH — the last resort of [gridBinaryPath], and the word the* sign-out's own "nothing to run" sentence uses (`gridLogout.ts`). */@@ -90,17 +90,38 @@ export function gridBinaryPath(processEnv: NodeJS.ProcessEnv = process.env, plat* `grid.exe`: Node cannot spawn a `.cmd` without a shell, and a shell would have to re-quote every* argument, so the installer's own line — `"<install>\Scripts\python.exe" -m cli %*` — is read and that* signed python is run directly. A `.cmd` that is not that shape is returned as it is, and fails as it did.+ *+ * The same for the `grid.exe` itself, which is a launcher that does nothing but start that python: it is unsigned, so Smart App+ * Control refuses it wherever the installer did not see that (593 times in an hour on DESKTOP-0TFH0OJ, 2026-11-05, each a notice+ * to the person that Node.js had been blocked). On a Mac nothing stands in its way; here it is stepped past, as `grid.cmd` is.*/export function gridCommand(binary: string, args: readonly string[], platform: NodeJS.Platform = process.platform): { file: string; args: string[] } {- if (platform === 'win32' && /\.(?:cmd|bat)$/i.test(binary)) {+ if (platform === 'win32') {+ const program = binary.includes('\\') || binary.includes('/') ? binary : resolveBinaryOnPath(binary) ?? binary+ let python: string | null | undefinedtry {- const python = /"([^"]+\.exe)" -m cli %\*/.exec(readFileSync(binary, 'utf8'))?.[1]- if (python) return { file: python, args: ['-m', 'cli', ...args] }+ python = /\.(?:cmd|bat)$/i.test(program)+ ? /"([^"]+\.exe)" -m cli %\*/.exec(readFileSync(program, 'utf8'))?.[1]+ : launcherPython(program)} catch { /* unreadable: spawn reports it */ }+ if (python) return { file: python, args: ['-m', 'cli', ...args] }}return { file: binary, args: [...args] }}+/** A launcher is small; anything larger is a program of its own, not read to find out. */+const MAX_LAUNCHER_BYTES = 1024 * 1024++/** The python a pip or uv launcher `.exe` starts, named on a `#!` line near its end, when it is there to run. */+function launcherPython(program: string): string | null {+ if (!/\.exe$/i.test(program) || statSync(program).size > MAX_LAUNCHER_BYTES) return null+ const bytes = readFileSync(program)+ const at = bytes.lastIndexOf('#!')+ if (at < 0) return null+ const line = bytes.subarray(at + 2, at + 2 + 4096).toString('utf8').split(/[\r\n]/, 1)[0]!.replaceAll('"', '').trim()+ return win32.basename(line).toLowerCase() === 'python.exe' && existsSync(line) ? line : null+}+/** Is there a `grid` to run at all? Asked by reading rather than by spawning, so a missing binary is* a sentence rather than a spawn error every caller has to recognise — and so a present-but-not-* executable one (EACCES, never ENOENT) is caught too. */diff --git a/cli/src/lib/gridExec.spec.ts b/cli/src/lib/gridExec.spec.tsindex 7e7a7d96a..58ac53bd5 100644--- a/cli/src/lib/gridExec.spec.ts+++ b/cli/src/lib/gridExec.spec.ts@@ -227,6 +227,32 @@ describe('grid on Windows', () => {})})+ // Smart App Control blocked the unsigned launcher 593 times in an hour on DESKTOP-0TFH0OJ (2026-11-05), each a notice to the person+ // that Node.js had been blocked, and each a `spawn UNKNOWN`. What it starts is signed: that is run instead.+ it('runs the python a launcher grid.exe names, past the launcher Windows blocks', async () => {+ const bin = installed()+ const python = join(root, 'python.exe')+ writeFileSync(python, 'MZ')+ writeFileSync(join(bin, 'grid.exe'), Buffer.concat([Buffer.from([0x4d, 0x5a, 0, 1, 2]), Buffer.from(`#!${python}\r\nPK\u0003\u0004zip`, 'latin1')]))+ const { gridCommand } = await load()++ expect(gridCommand(join(bin, 'grid.exe'), ['ls'], 'win32')).toEqual({ file: python, args: ['-m', 'cli', 'ls'] })+ expect(gridCommand(join(bin, 'grid.exe'), ['ls'], 'darwin')).toEqual({ file: join(bin, 'grid.exe'), args: ['ls'] })+ })++ it.each([+ ['names a python that has gone', (root: string) => `MZ#!${join(root, 'gone', 'python.exe')}\r\nPK`],+ ['names something else', (root: string) => `MZ#!${join(root, 'other.exe')}\r\nPK`],+ ['names nothing', () => 'MZ a program of its own'],+ ])('runs grid.exe itself when it %s', async (_name, content) => {+ const bin = installed()+ writeFileSync(join(root, 'other.exe'), 'MZ')+ writeFileSync(join(bin, 'grid.exe'), content(root))+ const { gridCommand } = await load()++ expect(gridCommand(join(bin, 'grid.exe'), ['ls'], 'win32')).toEqual({ file: join(bin, 'grid.exe'), args: ['ls'] })+ })+it('leaves everything else as it is: an .exe, a .cmd it cannot read, and any other OS', async () => {const bin = installed('grid.exe', 'grid.cmd')const { gridCommand } = await load()diff --git a/cli/src/lib/gridExec.ts b/cli/src/lib/gridExec.tsindex aa1ea3a0b..94bcb58c5 100644--- a/cli/src/lib/gridExec.ts+++ b/cli/src/lib/gridExec.ts@@ -104,7 +104,23 @@ export async function gridExec(args: readonly string[], opts: GridExecOptions =const ended = await gridCallStarted()return await new Promise<GridResult>((resolve) => {const command = gridCommand(binary, args)- const child = spawn(command.file, command.args, { stdio: ['pipe', 'pipe', 'pipe'], env: gridChildEnv(processEnv) })+ let child: ReturnType<typeof spawn>+ try {+ child = spawn(command.file, command.args, { stdio: ['pipe', 'pipe', 'pipe'], env: gridChildEnv(processEnv) })+ } catch (error) {+ // A synchronous spawn failure (Windows' application control answers UNKNOWN, for one) must not+ // reject this promise: every caller reads the result, and the counter an install waits on would+ // otherwise never be released.+ ended()+ resolve({+ code: 'GRID_FAILED',+ exitCode: 1,+ stdout: '',+ stderr: '',+ message: `Could not run \`${binary}\`: ${error instanceof Error ? error.message : String(error)}`,+ })+ return+ }let stdout = ''let stderr = ''let settled = falsediff --git a/cli/src/lib/gridFleetRpc.ts b/cli/src/lib/gridFleetRpc.tsindex caa4cc689..2e1a6ae98 100644--- a/cli/src/lib/gridFleetRpc.ts+++ b/cli/src/lib/gridFleetRpc.ts@@ -64,17 +64,25 @@ export class GridFleetRpc {const output = { stdout: new GridOutputCapture(), stderr: new GridOutputCapture() }let stopped: string | null = null, done = falselet timeout: ReturnType<typeof setTimeout>, kill: ReturnType<typeof setTimeout> | undefined- const command = gridCommand(gridBinaryPath(this.processEnv), request.args)- const child = spawn(command.file, command.args, {- env: { ...gridChildEnv(this.processEnv), ...(request.thinking === undefined ? {} : {- LLAMA_ARG_CHAT_TEMPLATE_KWARGS: JSON.stringify({ enable_thinking: request.thinking }),- }) }, stdio: ['ignore', 'pipe', 'pipe'],- })const finish = (code: number, error: string | null) => {if (done) returndone = true; clearTimeout(timeout); clearTimeout(kill); ended()resolve({ ok: code === 0 && !error, code, stdout: output.stdout.text, stderr: output.stderr.text, error })}+ const command = gridCommand(gridBinaryPath(this.processEnv), request.args)+ let child: ReturnType<typeof spawn>+ try {+ child = spawn(command.file, command.args, {+ env: { ...gridChildEnv(this.processEnv), ...(request.thinking === undefined ? {} : {+ LLAMA_ARG_CHAT_TEMPLATE_KWARGS: JSON.stringify({ enable_thinking: request.thinking }),+ }) }, stdio: ['ignore', 'pipe', 'pipe'],+ })+ } catch (error) {+ // A synchronous start failure (Windows' application control answers UNKNOWN) is reported as+ // a result, and releases the counter an install waits on. It used to reject instead.+ finish(127, `Grid could not start on this machine: ${error instanceof Error ? error.message : String(error)}. Check its Grid installation.`)+ return+ }const stop = (reason: string) => {if (stopped || done) returnstopped = reason; child.kill('SIGTERM')@@ -88,8 +96,9 @@ export class GridFleetRpc {stop(`Grid output exceeded ${maxOutput / 1024} KiB; use a narrower query.`); return}}- child.stdout.setEncoding('utf8').on('data', (data: string) => capture('stdout', data))- child.stderr.setEncoding('utf8').on('data', (data: string) => capture('stderr', data))+ // stdio is a pipe pair by construction above, so neither is null.+ child.stdout!.setEncoding('utf8').on('data', (data: string) => capture('stdout', data))+ child.stderr!.setEncoding('utf8').on('data', (data: string) => capture('stderr', data))child.once('error', () => finish(127, 'Grid could not start on this machine. Check its Grid installation.'))child.once('close', code => finish(stopped ? 124 : code ?? 1, stopped || (code === 0 ? null : 'Grid command failed.')))timeout = setTimeout(() => stop('Grid command timed out. Verify the target state before retrying a deployment.'), request.timeoutMs)diff --git a/cli/src/lib/gridHandoff.ts b/cli/src/lib/gridHandoff.tsindex 14a38514a..18abffa7d 100644--- a/cli/src/lib/gridHandoff.ts+++ b/cli/src/lib/gridHandoff.ts@@ -135,12 +135,27 @@ export async function handOffToGrid(const ended = await gridCallStarted()return await new Promise<GridHandoffResult>((resolve) => {const command = gridCommand(binary, args)- const child = spawn(command.file, command.args, {- stdio: ['pipe', opts.json ? 'pipe' : 'inherit', opts.json ? 'pipe' : 'inherit'],- // The human path inherits stderr, which is a terminal — exactly where grid would offer- // `grid update` for a binary the harness pins. See GRID_NO_UPDATE_CHECK_VAR in gridExec.ts.- env: gridChildEnv(),- })+ let child: ReturnType<typeof spawn>+ try {+ child = spawn(command.file, command.args, {+ stdio: ['pipe', opts.json ? 'pipe' : 'inherit', opts.json ? 'pipe' : 'inherit'],+ // The human path inherits stderr, which is a terminal — exactly where grid would offer+ // `grid update` for a binary the harness pins. See GRID_NO_UPDATE_CHECK_VAR in gridExec.ts.+ env: gridChildEnv(),+ })+ } catch (error) {+ // Windows' application control refuses an unsigned program synchronously (UNKNOWN). The+ // hand-off reports every failure through its result, and an install waits on this counter.+ ended()+ resolve({+ code: 'GRID_LOGIN_FAILED',+ exitCode: 1,+ message: `Could not run \`${binary}\`: ${error instanceof Error ? error.message : String(error)}`,+ stdout: '',+ stderr: '',+ })+ return+ }let stdout = ''let stderr = ''child.stdout?.on('data', (chunk: Buffer) => { stdout = capped(stdout, chunk) })diff --git a/cli/src/lib/gridLogout.ts b/cli/src/lib/gridLogout.tsindex f06c10f33..5fddd1f0e 100644--- a/cli/src/lib/gridLogout.ts+++ b/cli/src/lib/gridLogout.ts@@ -60,7 +60,19 @@ export async function passThroughToGridLogout(args: string[]): Promise<GridLogou// Inherited stderr is a terminal, where grid would offer `grid update` for a binary the harness// pins — off, as for every child of this daemon (GRID_NO_UPDATE_CHECK_VAR in gridExec.ts).const command = gridCommand(binary, [GRID_LOGOUT_VERB, ...args])- const child = spawn(command.file, command.args, { stdio: 'inherit', env: gridChildEnv() })+ let child: ReturnType<typeof spawn>+ try {+ child = spawn(command.file, command.args, { stdio: 'inherit', env: gridChildEnv() })+ } catch (error) {+ // A synchronous start failure (Windows' application control answers UNKNOWN) is a sign-out that+ // did not run, reported like any other, not a rejected promise the caller has to catch.+ resolve({+ ran: false,+ exitCode: 1,+ message: `Could not run \`${binary}\`: ${error instanceof Error ? error.message : String(error)}`,+ })+ return+ }let settled = falseconst settle = (outcome: GridLogoutOutcome): void => { if (!settled) { settled = true; resolve(outcome) } }diff --git a/cli/src/lib/gridSpawnRefusal.spec.ts b/cli/src/lib/gridSpawnRefusal.spec.tsnew file mode 100644index 000000000..f6ead0576--- /dev/null+++ b/cli/src/lib/gridSpawnRefusal.spec.ts@@ -0,0 +1,77 @@+/**+ * A grid child that cannot start at all.+ *+ * Windows' Smart App Control refuses an unsigned program synchronously: `spawn` THROWS `UNKNOWN`+ * instead of emitting an `error` event. Every grid call promises a result (`never throws`), and three+ * of them hold the counter an install waits on (`gridCalls.ts`), so a throw used to reject a promise+ * no caller catches and leave that install waiting for its whole drain.+ */+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { withGridCallsPaused } from './gridCalls.js'++const spawnMock = vi.hoisted(() => vi.fn())+vi.mock('node:child_process', () => ({ spawn: spawnMock }))++import { gridExec } from './gridExec.js'+import { handOffToGrid } from './gridHandoff.js'+import { GridFleetRpc } from './gridFleetRpc.js'+import { passThroughToGridLogout } from './gridLogout.js'++let root = ''+const saved = { HARNESS_GRID_BIN: process.env.HARNESS_GRID_BIN, ADAPTER_RUNTIME_DIR: process.env.ADAPTER_RUNTIME_DIR }++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'grid-spawn-refusal-'))+ const binary = join(root, 'grid')+ writeFileSync(binary, '#!/bin/sh\nexit 0\n', { mode: 0o755 })+ chmodSync(binary, 0o755)+ process.env.HARNESS_GRID_BIN = binary+ process.env.ADAPTER_RUNTIME_DIR = join(root, 'runtime')+ spawnMock.mockReset()+ spawnMock.mockImplementation(() => {+ throw Object.assign(new Error('spawn UNKNOWN'), { code: 'UNKNOWN' })+ })+})++afterEach(() => {+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key]+ else process.env[key] = value+ }+ spawnMock.mockReset()+ rmSync(root, { recursive: true, force: true })+})++describe('a grid program that throws on start', () => {+ it('answers with a result from every call instead of rejecting', async () => {+ const exec = await gridExec(['version'])+ expect(exec).toMatchObject({ code: 'GRID_FAILED', exitCode: 1 })+ expect(exec.message).toContain('UNKNOWN')++ const handoff = await handOffToGrid('token')+ expect(handoff).toMatchObject({ code: 'GRID_LOGIN_FAILED', exitCode: 1 })+ expect(handoff.message).toContain('UNKNOWN')++ const fleet = await new GridFleetRpc(process.env).run('owner', 'job', { args: ['version'], timeoutMs: 1_000 })+ expect(fleet).toMatchObject({ ok: false, code: 127 })+ expect(fleet.error).toContain('UNKNOWN')++ const logout = await passThroughToGridLogout([])+ expect(logout).toMatchObject({ ran: false, exitCode: 1 })+ if (!logout.ran) expect(logout.message).toContain('UNKNOWN')+ })++ it('releases the counter an install waits on', async () => {+ await gridExec(['version'])+ await handOffToGrid('token')+ await new GridFleetRpc(process.env).run('owner', 'job', { args: ['version'], timeoutMs: 1_000 })++ // A leaked count makes this wait for its full drain; a released one answers at once.+ const quick = withGridCallsPaused(async () => 'released', 10_000).then(() => 'released')+ const slow = new Promise((resolve) => setTimeout(() => resolve('waiting'), 500))+ await expect(Promise.race([quick, slow])).resolves.toBe('released')+ })+})diff --git a/cli/src/lib/loginShellEnv.spec.ts b/cli/src/lib/loginShellEnv.spec.tsindex cfb472f80..2092d0ed4 100644--- a/cli/src/lib/loginShellEnv.spec.ts+++ b/cli/src/lib/loginShellEnv.spec.ts@@ -8,6 +8,7 @@ const account = vi.hoisted(() => ({ shell: null as string | null }))vi.mock('node:os', async (original) => ({ ...await original<typeof import('node:os')>(), userInfo: () => ({ shell: account.shell }) }))import {+ loginShellCaptureLine,loginShellEnvironment,oneShotParentEnv,resetLoginShellEnvironmentCache,@@ -76,6 +77,12 @@ describe('loginShellEnvironment', () => {} finally { rmSync(dir, { recursive: true, force: true }) }})+ it('says nothing about the empty capture on Windows, where there is no login shell', () => {+ expect(loginShellCaptureLine(0, 12, 'win32')).toBeNull()+ expect(loginShellCaptureLine(0, 12, 'darwin')).toContain('could not read a login shell')+ expect(loginShellCaptureLine(3, 12, 'win32')).toContain('read 3 variables')+ })+it('caches, so a recap never pays for the probe twice', async () => {resetLoginShellEnvironmentCache()// Two overlapping callers join the same in-flight capture rather than each spawning their owndiff --git a/cli/src/lib/loginShellEnv.ts b/cli/src/lib/loginShellEnv.tsindex 759586dd2..a209168a4 100644--- a/cli/src/lib/loginShellEnv.ts+++ b/cli/src/lib/loginShellEnv.ts@@ -109,3 +109,18 @@ export function resetLoginShellEnvironmentCache(): void {cached = nullinFlight = null}++/**+ * The one startup line about the capture, or null when there is nothing to say. Windows has no POSIX+ * login shell, so the empty capture there is the normal case, not a failure worth a line at every+ * start.+ */+export function loginShellCaptureLine(+ count: number,+ elapsedMs: number,+ platform: NodeJS.Platform = process.platform,+): string | null {+ if (count > 0) return `[env] read ${count} variables from the login shell in ${elapsedMs}ms (engine one-shots only)`+ if (platform === 'win32') return null+ return '[env] could not read a login shell environment — engine one-shots use the daemon environment only'+}diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.tsindex 82fac5279..f4fae5dc3 100644--- a/cli/src/lib/oneshot.ts+++ b/cli/src/lib/oneshot.ts@@ -18,6 +18,7 @@ import {} from './disposableOneShotPool.js'import { oneShotParentEnv } from './loginShellEnv.js'import { scrubTerminalContext } from './terminalEnvironment.js'+import { ownProcessGroup } from './windows/noWindow.js'function claudeBin(): string {return env.CLAUDE_PATH || 'claude'@@ -149,7 +150,7 @@ class ClaudeWorker extends ProcessWorker {...(effort ? ['--effort', effort] : []),]const child = spawn(claudeBin(), args, {- cwd, env: buildEnv(), detached: true, stdio: ['pipe', 'pipe', 'pipe'],+ cwd, env: buildEnv(), ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],})super(child)child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))@@ -259,7 +260,7 @@ class CodexWorker extends ProcessWorker {const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })if (codexHome) processEnv.CODEX_HOME = codexHomeconst child = spawn(process.env.CODEX_PATH || 'codex', args, {- cwd, env: processEnv, detached: true, stdio: ['pipe', 'ignore', 'pipe'],+ cwd, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'ignore', 'pipe'],})super(child)this.output = output@@ -348,7 +349,7 @@ class CursorWorker extends ProcessWorker {]const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })const child = spawn(cursorBin(), args, {- cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],+ cwd, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],})super(child)child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))@@ -477,7 +478,7 @@ class OpencodeWorker extends ProcessWorker {mkdirSync(OPENCODE_RECAP_DATA_DIR, { recursive: true, mode: 0o700 })const { args, env: processEnv } = opencodeOneShotSpawn(model, oneShotParentEnv(), OPENCODE_RECAP_DATA_DIR)const child = spawn(opencodeBin(), args, {- cwd: OPENCODE_RECAP_DATA_DIR, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],+ cwd: OPENCODE_RECAP_DATA_DIR, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],})super(child)child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))@@ -627,7 +628,7 @@ class KiloWorker extends ProcessWorker {// `turn_summary` was ever emitted and the device tile stayed on `processing` forever.const { args, env: processEnv } = kiloOneShotSpawn(model, oneShotParentEnv())const child = spawn(kiloBin(), args, {- cwd: KILO_RECAP_DATA_DIR, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],+ cwd: KILO_RECAP_DATA_DIR, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],})super(child)child.stdout?.on('data', (chunk: Buffer) => this.onStdout(chunk.toString()))@@ -723,7 +724,7 @@ class PiWorker extends ProcessWorker {const args = ['-p', '--no-session', '--no-extensions', ...(model ? ['--model', model] : [])]const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })const child = spawn(piBin(), args, {- cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],+ cwd, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],})super(child)child.stdout?.on('data', (chunk: Buffer) => { this.stdout += chunk.toString() })@@ -801,7 +802,7 @@ class CommandCodeWorker extends ProcessWorker {const args = ['-p', '--no-session', ...(model ? ['-m', model] : [])]const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })const child = spawn(commandCodeBin(), args, {- cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],+ cwd, env: processEnv, ...ownProcessGroup(), stdio: ['pipe', 'pipe', 'pipe'],})super(child)child.stdout?.on('data', (chunk: Buffer) => { this.stdout += chunk.toString() })@@ -931,7 +932,7 @@ export async function runGrokOneShot(opts: OneShotOptions): Promise<OneShotResulconst timeoutMs = opts.timeoutMs ?? 60_000return await new Promise<OneShotResult>((resolve, reject) => {const child = spawn(env.GROK_PATH || 'grok', args, {- cwd: opts.cwd, env: processEnv, detached: true, stdio: ['ignore', 'pipe', 'pipe'],+ cwd: opts.cwd, env: processEnv, ...ownProcessGroup(), stdio: ['ignore', 'pipe', 'pipe'],})let stdout = ''let stderr = ''diff --git a/cli/src/lib/pasteOnScreen.spec.ts b/cli/src/lib/pasteOnScreen.spec.tsnew file mode 100644index 000000000..b8edc9801--- /dev/null+++ b/cli/src/lib/pasteOnScreen.spec.ts@@ -0,0 +1,48 @@+import { describe, expect, it, vi } from 'vitest'+import { PASTE_LAND_LIMIT_MS, pasteComesAsKeys, pasteOnScreen } from './pasteOnScreen.js'++// Codex on Windows takes a paste as a stream of keys, and an Enter within 120 ms of the last counts as a newline in it. Its 2,249+// characters stayed in the composer as "[Pasted Content 2250 chars]", and every later message waited behind that "draft", for good.+describe('whether a paste comes as keys', () => {+ it('is Codex on Windows alone', () => {+ expect(pasteComesAsKeys('codex', 'win32')).toBe(true)+ expect(pasteComesAsKeys('codex', 'darwin')).toBe(false)+ expect(pasteComesAsKeys('claude', 'win32')).toBe(false)+ })+})++describe('waiting for a paste to land before its Enter', () => {+ const EMPTY = { draft: false, screen: '› ' }+ const PASTED = { draft: true, screen: '› [Pasted Content 2249 chars]' }+ const run = async (reads: Array<{ draft: boolean; screen: string | null }>, before: string | null = '› ') => {+ let asked = 0, waited = 0+ const landed = await pasteOnScreen(async () => reads[Math.min(asked++, reads.length - 1)], before, async (ms) => { waited += ms })+ return { landed, asked, waited }+ }++ it('waits through the reads that show nothing yet, until the composer holds it and has stopped changing', async () => {+ const { landed, asked } = await run([EMPTY, EMPTY, { draft: true, screen: '› part' }, PASTED, PASTED])+ expect(landed).toBe(true)+ expect(asked).toBe(5)+ })++ it('does not take a draft that was there before the paste for the paste', async () => {+ const before = '› what a person was typing'+ const typed = { draft: true, screen: before }+ const { asked } = await run([typed, typed, PASTED, PASTED], before)+ expect(asked).toBe(4)+ })++ it('gives up at its limit and says so, so the Enter is not held for good', async () => {+ const { landed, waited } = await run([EMPTY])+ expect(landed).toBe(false)+ expect(waited).toBeGreaterThanOrEqual(PASTE_LAND_LIMIT_MS)+ })++ it('survives a read that fails', async () => {+ const reads = [() => Promise.reject(new Error('gone')), async () => PASTED, async () => PASTED]+ let asked = 0+ const wait = vi.fn(async () => {})+ expect(await pasteOnScreen(() => reads[asked++]!(), '› ', wait)).toBe(true)+ })+})diff --git a/cli/src/lib/pasteOnScreen.ts b/cli/src/lib/pasteOnScreen.tsnew file mode 100644index 000000000..c3986b616--- /dev/null+++ b/cli/src/lib/pasteOnScreen.ts@@ -0,0 +1,35 @@+/**+ * Waiting for a paste to reach an engine that takes it as keys, before pressing its Enter (core/input.ts `messageWriter`).+ *+ * Codex on Windows has no paste event: a paste is a stream of key presses, and its burst detector turns an Enter within 120 ms of+ * the last of them into a newline in the paste (codex-rs tui `paste_burst.rs`, on "terminals without bracketed paste"). The stream+ * crosses the pseudo console in its own time, so no fixed wait is right: 2,249 characters given the settle of submitTiming.ts+ * stayed in the composer as "[Pasted Content 2250 chars]", its Enter among them (DESKTOP-0TFH0OJ, 2026-11-05), and every later+ * message waited behind that "draft", for good. What the pane shows is the one thing that knows: the burst shows nothing until it+ * ends, so it has landed once the composer holds something new that two reads in a row agree on.+ */+import type { AgentEngine } from '../engines/types.js'++export const PASTE_POLL_MS = 200+/** The most it waits. Past this the Enter is pressed anyway, as it would have been: a pane that never shows the paste holds nothing. */+export const PASTE_LAND_LIMIT_MS = 8_000++export function pasteComesAsKeys(engine: AgentEngine, platform: NodeJS.Platform = process.platform): boolean {+ return engine === 'codex' && platform === 'win32'+}++/** Whether the paste was seen to land. [before]: the pane as read before the paste: a draft already there is not the paste. */+export async function pasteOnScreen(+ read: () => Promise<{ draft: boolean; screen: string | null }>,+ before: string | null,+ sleep: (ms: number) => Promise<void> = (ms) => new Promise((done) => setTimeout(done, ms)),+): Promise<boolean> {+ let last: string | null = null+ for (let waited = 0; waited < PASTE_LAND_LIMIT_MS; waited += PASTE_POLL_MS) {+ const now = await read().catch(() => null)+ if (now?.draft && now.screen !== null && now.screen !== before && now.screen === last) return true+ last = now?.screen ?? null+ await sleep(PASTE_POLL_MS)+ }+ return false+}diff --git a/cli/src/lib/processTable.ts b/cli/src/lib/processTable.tsindex c0db9a588..d019ef2f3 100644--- a/cli/src/lib/processTable.ts+++ b/cli/src/lib/processTable.ts@@ -573,7 +573,7 @@ export const ENGINE_PROCESS_SIGNATURES: Readonly<Record<RegisteredSession['engin},pi: {basenames: [/^pi$/],- entrypoints: [/pi-coding-agent[\/\\]dist[\/\\]cli\.js$/],+ entrypoints: [/pi-coding-agent[\/\\]dist[\/\\](?:bundle[\/\\])?cli\.js$/],},// The release binary is a single executable named `omp` (measured: /proc/<pid>/comm and exe).omp: {diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.tsindex e839cc34e..ec7014b01 100644--- a/cli/src/lib/projectFolder.ts+++ b/cli/src/lib/projectFolder.ts@@ -7,6 +7,7 @@ import { plausibleBranchName, projectFolderName, projectFolderSlug } from './ageimport { GitProjectError, prepareGitProject, stopTree, validGitPath } from './gitProject.js'import { cloneAttempts, isGitHubHost, parseGitHubRepository, resolvedRepositoryIdentity } from './githubRepository.js'import { githubAliases, resolveHost } from './sshHosts.js'+import { ownProcessGroup } from './windows/noWindow.js'import { scmByKind } from '../scm/scmProjects.js'import type { ScmLaunchRecord } from '../scm/types.js'@@ -307,7 +308,7 @@ export function cloneRepository(url: string, destination: string, gitEnv?: NodeJGIT_SSH_COMMAND: base.GIT_SSH_COMMAND ?? 'ssh -oBatchMode=yes -oConnectTimeout=20' }// Its own process group, so a stalled clone's remote helper and index-pack stop with it.const child = spawn(git, ['clone', '--progress', '--filter=blob:none', '--single-branch', '--', url, destination], {- stdio: ['ignore', 'ignore', 'pipe'], env, detached: process.platform !== 'win32', windowsHide: true,+ stdio: ['ignore', 'ignore', 'pipe'], env, ...ownProcessGroup(),})let diagnostic = '', stalled = falseconst stall = setTimeout(() => {diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.tsindex 3a3c3e611..b75317e99 100644--- a/cli/src/lib/remoteRelay.ts+++ b/cli/src/lib/remoteRelay.ts@@ -34,7 +34,6 @@ import {type TerminalP2pData,type TerminalP2pPolicy,} from './terminalP2p.js'-import { warmStunUrls } from './stunSelect.js'import { RemoteViewerProxy } from './remoteViewerProxy.js'import { VIEWER_UP_TYPES } from './viewerWire.js'import { isWrapped } from './e2ee/core.js'@@ -664,21 +663,19 @@ export class RemoteRelayPool {if (frame.type === 'connected' && payload?.machineId === machineId) {selected = trueentry.p2pPolicy = p2pPolicy(payload.p2p)- // Earliest instant the url list exists. startP2p() fires one round trip later on- // e2e_welcome, so the cache is usually still cold — what actually pays off is the- // in-flight dedupe: begin() joins THIS race instead of starting a second one, and its- // cost hides behind the welcome round trip. Nothing here is load-bearing for- // correctness; drop it and the only change is a slightly later first terminal.- // Unconditional, one line per machine select. Whether the backend actually handed us a- // TURN credential is invisible everywhere else — not in LOG_FRAMES (which only covers- // backendSocket, never this relay client), not in the badge, not in p2p_result — and its- // absence is indistinguishable from "TURN is configured but ICE preferred direct".- // Names only, never the credential itself.+ // Names only, never the credential: whether the backend handed us a TURN credential+ // is invisible everywhere else (not in LOG_FRAMES, which covers backendSocket, never+ // this relay client; not in the badge; not in p2p_result).+ //+ // The policy is logged, never pre-warmed here. A STUN race opens UDP sockets bound+ // to 0.0.0.0, and on Windows the firewall asks about that program the first time —+ // for a computer the person only selected, not one they are watching. begin() races+ // when a terminal actually negotiates, inside its 10s budget: the only cost is a+ // slightly later first terminal, never correctness.if (entry.p2pPolicy && this.p2pEnabled) {const p = entry.p2pPolicyconsole.log(`[p2p] policy · machine=${sid(machineId)} stun=${p.stunUrls.length}`+ ` turn=${p.turn ? `${p.turn.urls.length} urls` : 'NONE'} openWait=${p.openWaitMs}ms`)- warmStunUrls(p.stunUrls)}try { ws.send(JSON.stringify(crypto.helloFrame())) } catch { /* the close handler below rejects */ }returndiff --git a/cli/src/lib/restoreTerminals.spec.ts b/cli/src/lib/restoreTerminals.spec.tsindex 9d62c90df..bab26e088 100644--- a/cli/src/lib/restoreTerminals.spec.ts+++ b/cli/src/lib/restoreTerminals.spec.ts@@ -36,6 +36,31 @@ function setup() {return { tmuxBackend, ptyBackend, listTmuxPanes, backendFor, terminals }}+// A row on an old pty host that is draining: it refuses new panes for good, so eight agents stayed held and no message reached+// them (DESKTOP-0TFH0OJ, 2026-11-04). Its rebuilt pane opens on the host new panes go to.+describe('a row whose pane was on a host that takes no new panes', () => {+ const made: TerminalRuntimeRef = { backend: 'ptyhost', instance: 'p2', paneId: '%1' }+ const row = { agentId: 'a1', engine: 'claude', runtimes: [pty] } as unknown as RegisteredSession++ it('rebuilds it on the host new panes go to', async () => {+ const draining = fakeBackend('ptyhost', pty), target = fakeBackend('ptyhost', made)+ const terminals = restoreTerminals({+ backendFor: () => draining as unknown as TerminalBackend, listTmuxPanes: vi.fn(), cwd: '/home/me', label: () => 'harness',+ newPanesOn: () => target as unknown as TerminalBackend,+ })+ expect(await terminals.createPane(row, { argv: ['claude'] }, { current: () => true })).toEqual({ ok: true, runtime: made })+ expect(draining.create).not.toHaveBeenCalled()+ })++ it('stays on its own host when there is no other to go to', async () => {+ const own = fakeBackend('ptyhost', made)+ const terminals = restoreTerminals({+ backendFor: () => own as unknown as TerminalBackend, listTmuxPanes: vi.fn(), cwd: '/home/me', label: () => 'harness', newPanesOn: () => null,+ })+ expect(await terminals.createPane(row, { argv: ['claude'] }, { current: () => true })).toEqual({ ok: true, runtime: made })+ })+})+const entry = (runtimes: TerminalRuntimeRef[]) => ({ agentId: 'a1', engine: 'claude', runtimes }) as unknown as RegisteredSessiondescribe('restore, on each pane\'s own backend', () => {diff --git a/cli/src/lib/restoreTerminals.ts b/cli/src/lib/restoreTerminals.tsindex c4b2105aa..2ec61a767 100644--- a/cli/src/lib/restoreTerminals.ts+++ b/cli/src/lib/restoreTerminals.ts@@ -23,6 +23,8 @@ export interface RestoreTerminalsOptions {backendFor(runtime: TerminalRuntimeRef): TerminalBackend | undefined/** tmux's harness panes (`listTmuxPanes`). */listTmuxPanes(): Promise<{ ok: true; panes: ReadonlyArray<{ tmuxPane: string }> } | { ok: false }>+ /** The backend a rebuilt pane opens on when [backend], the row's own, takes no new panes (a draining pty host); else null. */+ newPanesOn?(backend: TerminalBackend): TerminalBackend | null/** Where a rebuilt pane opens (the home folder: the launch `cd`s into the row's own). */cwd: string/** What a rebuilt pane is called (`buildHarnessSessionLabel`). */@@ -55,11 +57,14 @@ export function restoreTerminals(options: RestoreTerminalsOptions): RestoreTermiconst lookup = async (runtime: TerminalRuntimeRef, engine: AgentEngine) => lookupPaneEngineProcess(backendOf(runtime), runtime, engine)const survey = () => terminalSurvey(listPanes, lookup)const restorable = (runtime: TerminalRuntimeRef): boolean => !!restoring(runtime)- /** The backend of the row's own runtime restore rebuilds (`restoreRuntimeOf`): a new pane opens there. */+ /** The backend of the row's own runtime restore rebuilds (`restoreRuntimeOf`): a new pane opens there, unless that+ * one takes none any more (a draining host refuses them for good), when it opens where new panes go. */const placed = (entry: { runtimes: readonly TerminalRuntimeRef[] }): RestartableBackend => {const runtime = restoreRuntimeOf(entry, restorable)if (!runtime) throw new Error('no terminal backend restores this harness')- return backendOf(runtime)+ const own = backendOf(runtime)+ const instead = options.newPanesOn?.(own)+ return instead && canRestart(instead) ? instead : own}return {restorable,diff --git a/cli/src/lib/runtimeInstall.ts b/cli/src/lib/runtimeInstall.tsindex 59fc5b012..28a27ca1c 100644--- a/cli/src/lib/runtimeInstall.ts+++ b/cli/src/lib/runtimeInstall.ts@@ -3,7 +3,7 @@ import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, writimport { dirname, join, sep, win32 } from 'node:path'import { env } from '../config/env.js'-import { gridAvailable, gridChildEnv, gridVersion, managedGridPath, meetsVersionFloor } from './gridExec.js'+import { gridAvailable, gridChildEnv, gridCommand, gridVersion, managedGridPath, meetsVersionFloor } from './gridExec.js'import { installGrid } from './gridInstall.js'import { followWindowsGridPin } from './gridWindowsPin.js'import { managedNodePath } from './nodeRuntime.js'@@ -347,7 +347,12 @@ export async function ensureManagedGrid(log: (message: string) => void = () => {followsPin: true,acceptsVersion: (version) => meetsVersionFloor(version),// A minute, not fifteen seconds: a onefile grid unpacks itself the first time it runs.- runs: (grid) => runs(grid, 60_000, gridChildEnv()),+ // `gridCommand` steps past an unsigned launcher and runs the signed python it names, so this+ // probe never asks Smart App Control to start the very file it would refuse (windows-rules.md §2).+ runs: (grid) => {+ const command = gridCommand(grid, ['--version'])+ return finishesCleanly(command.file, command.args, 60_000, gridChildEnv())+ },readOnly: true,log,})diff --git a/cli/src/lib/terminalAgentDiscovery.engines.spec.ts b/cli/src/lib/terminalAgentDiscovery.engines.spec.tsindex 37dc1c291..c04456fa4 100644--- a/cli/src/lib/terminalAgentDiscovery.engines.spec.ts+++ b/cli/src/lib/terminalAgentDiscovery.engines.spec.ts@@ -143,6 +143,8 @@ describe('which engine process owns a pane', () => {['cursor', 'node', '/opt/cursor-agent/versions/1.2.3/index.js'],['opencode', 'opencode.exe', '/opt/lib/node_modules/opencode-ai/bin/opencode.exe'],['pi', 'node', '/opt/lib/node_modules/pi-coding-agent/dist/cli.js'],+ // Pi 1.5.0 moved it, and every new Pi agent then stayed "Starting" (DESKTOP-0TFH0OJ, 2026-11-05).+ ['pi', 'node', '/opt/lib/node_modules/pi-coding-agent/dist/bundle/cli.js'],['hermes', 'python3', '/opt/hermes-agent/hermes'],['commandcode', 'node', '/opt/lib/node_modules/command-code/dist/index.mjs'],['devin', 'python3', '/opt/devin/cli/_versions/1.2.3/bin/devin'],diff --git a/cli/src/lib/windows/engineStart.spec.ts b/cli/src/lib/windows/engineStart.spec.tsindex 1cdcd9785..61dcc0d2c 100644--- a/cli/src/lib/windows/engineStart.spec.ts+++ b/cli/src/lib/windows/engineStart.spec.ts@@ -83,23 +83,36 @@ describe('the shell a Windows engine\'s pane becomes', () => {it('is given, with the workspace and the names to clear, to an engine\'s pane on Windows only', () => {const native = { clearEnvironment: ['CODEX_HOME', 'ANTHROPIC_API_KEY'] }+ const environment = { PATH: 'C:\\Windows;C:\\Tools' }+ const env = { PATH: 'C:\\grid;C:\\Windows;C:\\Tools;C:\\node', GRID_NO_UPDATE_CHECK: '1' }+ const where = { environment, gridBinary: 'C:\\grid\\grid.exe', nodeRuntime: 'C:\\node\\node.exe' }expect(windowsPaneLaunch('claude', { cwd: '/work', clearEnv: ['A'] }, 'darwin')).toEqual({})- expect(windowsPaneLaunch('claude', { cwd: '/work' }, 'win32')).toEqual({ cwd: '/work', afterExit: windowsAfterExit('claude') })+ expect(windowsPaneLaunch('claude', { cwd: '/work', ...where }, 'win32'))+ .toEqual({ cwd: '/work', env, afterExit: windowsAfterExit('claude') })// A grid launch's provider keys and the native launch's cleared locations, once each.- expect(windowsPaneLaunch('codex', { cwd: null, clearEnv: ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY'], native }, 'win32'))- .toEqual({ clearInherited: ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'CODEX_HOME'], afterExit: windowsAfterExit('codex') })- expect(windowsPaneLaunch('codex', { clearEnv: [], native: { clearEnvironment: [] } }, 'win32')).toEqual({ afterExit: windowsAfterExit('codex') })+ expect(windowsPaneLaunch('codex', { cwd: null, clearEnv: ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY'], native, ...where }, 'win32'))+ .toEqual({ clearInherited: ['ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'CODEX_HOME'], env, afterExit: windowsAfterExit('codex') })+ expect(windowsPaneLaunch('codex', { clearEnv: [], native: { clearEnvironment: [] }, ...where }, 'win32'))+ .toEqual({ env, afterExit: windowsAfterExit('codex') })+ // A grid already on PATH is left to PATH; a Node already there is not added twice.+ expect(windowsPaneLaunch('claude', { environment: { PATH: 'C:\\node;C:\\Tools' }, gridBinary: 'grid', nodeRuntime: 'C:\\node\\node.exe' }, 'win32').env)+ .toEqual({ PATH: 'C:\\node;C:\\Tools', GRID_NO_UPDATE_CHECK: '1' })+ // Windows often spells it `Path`; the pane must replace that entry, not add a second `PATH`+ // (measured on DESKTOP-0TFH0OJ: the duplicate was ignored and the agent saw no Harness Node).+ expect(windowsPaneLaunch('claude', { environment: { Path: 'C:\\Tools' }, gridBinary: 'C:\\grid\\grid.exe', nodeRuntime: 'C:\\node\\node.exe' }, 'win32').env)+ .toEqual({ Path: 'C:\\grid;C:\\Tools;C:\\node', GRID_NO_UPDATE_CHECK: '1' })// The command a person would type names it. On Windows Command Code's is `command-code`: `cmd` is the command// processor there (F7, B4.13).- expect(windowsPaneLaunch('commandcode', {}, 'win32').afterExit?.env).toEqual({ HARNESS_ENGINE_COMMAND: 'command-code' })+ expect(windowsPaneLaunch('commandcode', { ...where }, 'win32').afterExit?.env).toEqual({ HARNESS_ENGINE_COMMAND: 'command-code' })vi.stubEnv('CODEX_PATH', 'C:\\tools\\codex.exe')try {- expect(windowsPaneLaunch('codex', {}, 'win32').afterExit?.env).toEqual({ HARNESS_ENGINE_COMMAND: 'codex.exe' })+ expect(windowsPaneLaunch('codex', { ...where }, 'win32').afterExit?.env).toEqual({ HARNESS_ENGINE_COMMAND: 'codex.exe' })} finally { vi.unstubAllEnvs() }// A terminal's shell, or a held pane, ending is the pane's end; a held pane is told by its flag, never its argv.- expect(windowsPaneLaunch('terminal', { cwd: '/work' }, 'win32')).toEqual({ cwd: '/work' })- expect(windowsPaneLaunch('codex', { cwd: '/work', held: true }, 'win32')).toEqual({ cwd: '/work' })- expect(windowsPaneLaunch('codex', { cwd: '/work' })).toEqual(process.platform === 'win32' ? { cwd: '/work', afterExit: windowsAfterExit('codex') } : {})+ expect(windowsPaneLaunch('terminal', { cwd: '/work', ...where }, 'win32')).toEqual({ cwd: '/work' })+ expect(windowsPaneLaunch('codex', { cwd: '/work', held: true, ...where }, 'win32')).toEqual({ cwd: '/work' })+ expect(windowsPaneLaunch('codex', { cwd: '/work' }, 'win32')).toMatchObject({ cwd: '/work', afterExit: windowsAfterExit('codex') })+ expect(windowsPaneLaunch('codex', { cwd: '/work' })).toEqual(process.platform === 'win32' ? expect.objectContaining({ cwd: '/work', afterExit: windowsAfterExit('codex') }) : {})})it('tells a held pane by the argv it made, not by what an argv says', () => {diff --git a/cli/src/lib/windows/engineStart.ts b/cli/src/lib/windows/engineStart.tsindex 8678594ba..2b68ee58f 100644--- a/cli/src/lib/windows/engineStart.ts+++ b/cli/src/lib/windows/engineStart.ts@@ -22,12 +22,15 @@** Every value the shells are given travels in their environment, never in their command text.*/+import { win32 } from 'node:path'import type { NativeLaunch } from '../../engines/nativeLaunch.js'import { startupOwnedFlag } from '../../engines/kit/launchStartup.js'import { launchContract } from '../../engines/launches.js'import { isTerminalEngine, type AgentEngine } from '../../engines/types.js'import { baseNode } from '../../harnessd/baseNode.js'import { engineBin } from '../engineBin.js'+import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath } from '../gridBinary.js'+import { managedNodePath } from '../nodeRuntime.js'import type { TerminalAfterExit } from '../terminalTypes.js'import { WindowsLaunchRefused } from './launch.js'import { defaultWindowsShell } from './shell.js'@@ -118,6 +121,12 @@ export interface WindowsPaneLaunch {* the person's ANTHROPIC_API_KEY. Per launch, as the script's unset is: an agent moved home gets them back.*/clearInherited?: string[]+ /**+ * What the Unix launch script adds to an engine's pane and Windows had no counterpart of: grid's folder at the+ * front of PATH and Harness's Node at the end, so an agent's own tool calls find both, and grid's update check off+ * (GRID_NO_UPDATE_CHECK_VAR) so an agent never replaces the grid this daemon pinned.+ */+ env?: Record<string, string>}/** The launch facts `windowsPaneLaunch` reads: its options (lib/engineLaunch.ts `LaunchCommandOptions`). */@@ -127,6 +136,11 @@ export interface WindowsPaneLaunchOptions {native?: Pick<NativeLaunch, 'clearEnvironment'>/** The argv is a held pane's (`isWindowsHeldPane`), which hands off to nothing. */held?: boolean+ /** The environment the pane's PATH is built from. `process.env` unless a test hands in one. */+ environment?: NodeJS.ProcessEnv+ /** The grid and Node the pane's PATH names. Resolved here unless a test hands them in. */+ gridBinary?: string+ nodeRuntime?: string}/**@@ -139,9 +153,42 @@ export function windowsPaneLaunch(engine: AgentEngine, launch: WindowsPaneLaunchplatform: NodeJS.Platform = process.platform): WindowsPaneLaunch {if (platform !== 'win32') return {}const clearInherited = [...new Set([...(launch.clearEnv ?? []), ...(launch.native?.clearEnvironment ?? [])])]+ const enginePane = !isTerminalEngine(engine) && !launch.heldreturn {...(launch.cwd ? { cwd: launch.cwd } : {}),...(clearInherited.length ? { clearInherited } : {}),- ...(isTerminalEngine(engine) || launch.held ? {} : { afterExit: windowsAfterExit(engineBin(engine, platform).split(/[\\/]/).pop() || engine) }),+ ...(enginePane ? { env: windowsPaneEnv(launch) } : {}),+ ...(enginePane ? { afterExit: windowsAfterExit(engineBin(engine, platform).split(/[\\/]/).pop() || engine) } : {}),+ }+}++/** The first and last PATH entries an engine's Windows pane needs, and grid's update check off. */+function windowsPaneEnv(launch: WindowsPaneLaunchOptions): Record<string, string> {+ // A test that fakes the platform has no Windows environment to read; it passes one, or gets only+ // the update switch. On Windows itself the daemon's own environment is the pane's base.+ const real = process.platform === 'win32'+ const environment = launch.environment ?? (real ? process.env : {})+ const grid = launch.gridBinary ?? (real ? gridBinaryPath(environment) : '')+ const node = launch.nodeRuntime ?? (real ? managedNodePath() : '')+ // Windows names it `Path` as often as `PATH`, and a second spelling would be a duplicate the OS+ // may resolve to the inherited one: measured on DESKTOP-0TFH0OJ, 2026-11-05, the new `PATH` was+ // ignored and the agent's shell did not see Harness's Node.+ const pathName = Object.keys(environment).find((key) => key.toLowerCase() === 'path') ?? 'PATH'+ const parts = (environment[pathName] ?? '').split(';').filter((part) => part.length > 0)+ // grid's own folder first, so a managed grid a shell's PATH cannot see is the one the agent runs;+ // Harness's Node last, because a `node` the person installed still comes first, as on Unix.+ if (/[\\/]/.test(grid)) prependOnce(parts, win32.dirname(grid))+ if (node) appendOnce(parts, win32.dirname(node))+ return {+ ...(parts.length ? { [pathName]: parts.join(';') } : {}),+ [GRID_NO_UPDATE_CHECK_VAR]: '1',}}++function prependOnce(parts: string[], dir: string): void {+ if (!parts.some((part) => part.toLowerCase() === dir.toLowerCase())) parts.unshift(dir)+}++function appendOnce(parts: string[], dir: string): void {+ if (!parts.some((part) => part.toLowerCase() === dir.toLowerCase())) parts.push(dir)+}diff --git a/cli/src/lib/windows/noWindow.spec.ts b/cli/src/lib/windows/noWindow.spec.tsnew file mode 100644index 000000000..22ad9cbf2--- /dev/null+++ b/cli/src/lib/windows/noWindow.spec.ts@@ -0,0 +1,59 @@+import { readdirSync, readFileSync } from 'node:fs'+import { join, relative, sep } from 'node:path'+import { fileURLToPath } from 'node:url'+import ts from 'typescript'+import { describe, expect, it } from 'vitest'+import { ownProcessGroup } from './noWindow.js'++const SOURCE = fileURLToPath(new URL('../..', import.meta.url))++/** The only places a process may still start detached on Windows, and why that opens no window (docs/windows-rules.md, rule 1). */+const ALLOWED: Record<string, string> = {+ 'lib/ptyHost/launch.ts': 'the pty host must outlive the daemon, and what it starts runs in its own pseudo console',+ 'engines/kit/windowsInstall.ts': 'a runner that must outlive the daemon, and starts the installer itself with windowsHide',+ 'engines/kit/nativeInstall.ts': 'macOS and Linux only: Windows takes createWindowsInstallations (core/main.ts)',+ 'services/osDevice.ts': 'nmcli and the like, on Harness OS: never on Windows',+ 'lib/appModels.ts': 'a model server must outlive the daemon, and starts no console program',+ 'lib/connectors/command.ts': 'the Connectors page must outlive this command, and starts no console program',+ 'core/main.ts': 'a core an older release started with no master: Windows always has one (harness-launch.exe)',+ 'cli.ts': 'a build run from a checkout: an installed copy starts through harness-launch.exe',+}++function sources(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap(entry => {+ const path = join(dir, entry.name)+ if (entry.isDirectory()) return entry.name === 'testing' || entry.name === 'e2e' || entry.name === '__fixtures__' ? [] : sources(path)+ return /\.tsx?$/.test(entry.name) && !/\.(spec|test|d)\.tsx?$/.test(entry.name) ? [path] : []+ })+}++/** Each `detached:` in a file's code that is not plainly false. Read from its syntax, so a comment or a string names nothing. */+function detachedOptions(file: string): number {+ const tree = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, false)+ let found = 0+ const visit = (node: ts.Node): void => {+ const named = (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) && ts.isIdentifier(node.name) && node.name.text === 'detached'+ if (named && !(ts.isPropertyAssignment(node) && node.initializer.kind === ts.SyntaxKind.FalseKeyword)) found+++ ts.forEachChild(node, visit)+ }+ visit(tree)+ return found+}++describe('no window flashes on Windows', () => {+ it('starts in its own group on macOS and Linux, and hidden, never detached, on Windows', () => {+ expect(ownProcessGroup('darwin')).toEqual({ detached: true })+ expect(ownProcessGroup('linux')).toEqual({ detached: true })+ expect(ownProcessGroup('win32')).toEqual({ windowsHide: true })+ })++ it('has no `detached` outside ownProcessGroup but the places listed with their reason', () => {+ const helper = join('lib', 'windows', 'noWindow.ts')+ const found = sources(SOURCE).map(file => relative(SOURCE, file)).filter(file => file !== helper && detachedOptions(join(SOURCE, file)) > 0)+ .map(file => file.split(sep).join('/'))+ // A new one? Use ownProcessGroup(). See docs/windows-rules.md for why windowsHide beside detached does not work.+ expect(found.filter(file => !(file in ALLOWED))).toEqual([])+ // And a reason nothing needs any more goes.+ expect(Object.keys(ALLOWED).filter(file => !found.includes(file))).toEqual([])+ })+})diff --git a/cli/src/lib/windows/noWindow.ts b/cli/src/lib/windows/noWindow.tsnew file mode 100644index 000000000..2e5db96d4--- /dev/null+++ b/cli/src/lib/windows/noWindow.ts@@ -0,0 +1,12 @@+/**+ * How to start a program in its own process group without a window ever flashing on Windows (docs/windows-rules.md, rule 1).+ *+ * `detached: true` on Windows is DETACHED_PROCESS: the child has no console, so every console program it starts gets a new one,+ * and its window flashes up. `windowsHide` cannot help, since Windows ignores CREATE_NO_WINDOW beside DETACHED_PROCESS. Measured on+ * Windows 11, 2026-11-05: detached flashed with and without `windowsHide`; `windowsHide` alone never did. Windows has no process+ * groups to gain from `detached` either. Node does end such a child when it exits (not what the child starts in turn): a program+ * that must outlive Node starts through bin\harness-launch.exe (./launcher.ts) or a hidden runner (engines/kit/windowsInstall.ts).+ */+export function ownProcessGroup(platform: NodeJS.Platform = process.platform): { detached?: boolean; windowsHide?: boolean } {+ return platform === 'win32' ? { windowsHide: true } : { detached: true }+}diff --git a/cli/src/superTabs/buddyHome.ts b/cli/src/superTabs/buddyHome.tsindex 45b9483e1..75d34a6f8 100644--- a/cli/src/superTabs/buddyHome.ts+++ b/cli/src/superTabs/buddyHome.ts@@ -8,7 +8,7 @@* longer reads leaves the folder before the Buddy's next turn (pruneBuddyHome).*/import { execFile } from 'node:child_process'-import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { promisify } from 'node:util'import { launchEnvironment } from '../engines/kit/launchExecutable.js'@@ -214,6 +214,9 @@ function writeCopies(home: string, states: readonly CopyState[]): void {const path = join(home, BUDDY_COPIES_FILE), next = `${path}.next`rmSync(next, { force: true })writeFileSync(next, `Your copy of each project's code, refreshed ${new Date().toISOString()}:\n${states.map(line).join('\n')}\n`, { mode: 0o444 })+ // Windows will not rename over a read-only file (EPERM), and the last pass left this one read-only, so every later pass failed.+ // A plain file alone: chmod follows a link, and the Buddy can write in this folder, so one here could name a private file.+ if (process.platform === 'win32' && lstatSync(path, { throwIfNoEntry: false })?.isFile()) chmodSync(path, 0o644)renameSync(next, path)}diff --git a/cli/src/superTabs/fixtures/screens/codex-0163-hooks-review.txt b/cli/src/superTabs/fixtures/screens/codex-0163-hooks-review.txtnew file mode 100644index 000000000..5acfb731a--- /dev/null+++ b/cli/src/superTabs/fixtures/screens/codex-0163-hooks-review.txt@@ -0,0 +1,12 @@+++ Hooks need review+ 2 hooks are new or changed.+ Hooks can run outside the sandbox after you trust them.+++› 1. Review hooks+ 2. Trust all and continue+ 3. Continue without trusting (hooks won't run)++ enter confirm · esc skipdiff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex 4bbdf7a31..aec96d2a6 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -2935,6 +2935,26 @@ describe('a launched start whose engine stops on a screen', () => {expect(failures()[0]?.error).toBe('Its engine stopped on a folder trust question ("Trust this folder?") that nobody here can answer.')})+ // On 2026-11-04 another program's two hooks stopped every Codex start on DESKTOP-0TFH0OJ at this screen. Esc goes on with+ // those hooks off: nothing is trusted on the person's behalf, and it applies to any Swarm Codex start, Team-written or not.+ it.each([+ ['a Team-written start', { engine: 'codex', projectSettings: 'off' }],+ ['any other Swarm start', { engine: 'codex' }],+ ])("skips Codex's review of another program's hooks on %s, with Esc alone", async (_name, request) => {+ const REVIEW = screens('codex-0163-hooks-review')+ const { f, inputIfScreen, failures } = launched(REVIEW, 'menu_open', request)+ await twice(f)+ expect(inputIfScreen).toHaveBeenCalledWith('launched', ['Escape'], REVIEW)+ expect(failures()).toEqual([])+ })++ it('fails, never answers, a screen with those words on another engine', async () => {+ const { f, inputIfScreen, failures } = launched(screens('codex-0163-hooks-review'), 'menu_open', { engine: 'claude' })+ await twice(f)+ expect(inputIfScreen).not.toHaveBeenCalled()+ expect(failures()[0]?.error).toBe('Its engine stopped on a menu that nobody here can answer.')+ })+// Security review 2 of #3063: the whole screen in a reason carried what a terminal shows only its own session (a sign-in// link's state, wrapped onto the next line; a device code; an account's email), and a malformed link threw before the// failure was sent. Its second read: option labels are terminal content too ("Use code 123456", a file path, a name), sodiff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 3b8a2eb31..3ca2b3e01 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -7,6 +7,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'nodimport type { CoreApi } from '../core/api.js'import { openDaemon } from '../agentClient/daemon.js'import { codingRefusal } from '../lib/codingModel.js'+import { ownProcessGroup } from '../lib/windows/noWindow.js'import { backend, FIELD_REFUSED_MS, fieldRefused, identifier, object, SuperTabHostError } from './wire.js'import type { SwarmSources } from './host.js'import { HostFeed } from './hostFeed.js'@@ -1336,7 +1337,7 @@ export function createQuietGit(timeoutMs = 15_000): GitRun {const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', SSH_ASKPASS_REQUIRE: 'never',GCM_INTERACTIVE: 'never', GIT_OPTIONAL_LOCKS: '0' }for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE']) delete env[key]- const child = spawn('git', ['-C', cwd, ...args], { env, detached: true, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })+ const child = spawn('git', ['-C', cwd, ...args], { env, ...ownProcessGroup(), stdio: ['ignore', 'pipe', 'pipe'] })let stdout = '', stderr = '', settled = falseconst settle = (answer: { ok: boolean; timedOut?: boolean }) => { if (!settled) { settled = true; clearTimeout(timer); resolve({ ...answer, stdout, stderr }) } }child.stdout.setEncoding('utf8').on('data', (text: string) => { stdout = (stdout + text).slice(0, 65_536) })diff --git a/cli/src/superTabs/startScreen.ts b/cli/src/superTabs/startScreen.tsindex 6798ba2ff..a8d836ee9 100644--- a/cli/src/superTabs/startScreen.ts+++ b/cli/src/superTabs/startScreen.ts@@ -7,12 +7,14 @@* - A Team-written Codex start's own home names its checkout untrusted (start.ts `untrustCheckout`), so Codex asks to open* it restricted, which keeps the branch's settings off: that exact screen alone is answered (engines/codex/screen.ts* `openRestrictedKeys`), and only while the pane still shows it (inCore/terminal.ts `inputIfScreen`).+ * - Codex's review of hooks it has not seen, on a computer with another program's new hook, is skipped the same way+ * (`hooksReviewSkipKeys`): those hooks stay off and nothing is trusted. Trusting one is a person's.* - Any other screen that waits for a person (terminal.ts `WAITING`) fails the start at once, saying what kind of screen it* was, in fixed words ([hiddenPromptReason]): who started it, its coordinator and its machine's owner read that (backend* startFailure.ts); members read only that the machine could not prepare or launch it.*/import type { CoreApi } from '../core/api.js'-import { openRestrictedKeys } from '../engines/codex/screen.js'+import { hooksReviewSkipKeys, openRestrictedKeys } from '../engines/codex/screen.js'import { WAITING } from './terminal.js'import type { MessageHold } from '../engines/facets/screen.js'@@ -44,11 +46,15 @@ export async function settleHiddenScreen(terminal: Terminal | undefined, harnessif (!terminal) return { outcome: null }const read = await terminal.screen(harnessId, 0).catch(() => null)if (!read?.ok || !read.hold || !WAITING.has(read.hold as MessageHold)) return { outcome: null }- const keys = request.engine === 'codex' && request.projectSettings === 'off' ? openRestrictedKeys(read.text) : null+ const restricted = request.engine === 'codex' && request.projectSettings === 'off' ? openRestrictedKeys(read.text) : null+ const skipReview = request.engine === 'codex' && !restricted ? hooksReviewSkipKeys(read.text) : null+ const keys = restricted ?? skipReviewif (keys) {// A pane that changed meanwhile is read again on the next pass, never answered blind.const typed = await terminal.inputIfScreen(harnessId, keys, read.text).catch(() => null)- if (typed?.ok) log(`Opened the Team-written checkout restricted for session ${harnessId.slice(0, 8)}, as its engine asked`)+ if (typed?.ok) log(restricted+ ? `Opened the Team-written checkout restricted for session ${harnessId.slice(0, 8)}, as its engine asked`+ : `Went past the review of another program's hooks for session ${harnessId.slice(0, 8)}: they stay off, and nothing was trusted`)return { outcome: typed?.ok ? 'answered' : null }}// Security review 1 of #3063: one read of a screen still drawing failed a start that would have gone on, and two failures indiff --git a/desktop/lib/models/model_manager_controller.dart b/desktop/lib/models/model_manager_controller.dartindex 9407fa243..627de9a22 100644--- a/desktop/lib/models/model_manager_controller.dart+++ b/desktop/lib/models/model_manager_controller.dart@@ -63,6 +63,9 @@ class ModelManagerController extends ChangeNotifier {DateTime? _lastInventoryAttempt;bool _panelVisible = false;int _actionRevision = 0;+ /// The daemon refused this machine's models for good (a computer shared with+ /// this account): polling again every four seconds only grows the log.+ bool _guestRefused = false;String? _dismissedReadyId;GridModels? models;List<LocalModel> localModels = const [];@@ -178,6 +181,7 @@ class ModelManagerController extends ChangeNotifier {// A minimised or background app reads nothing, busy or not: the daemon owns the operation// either way, and the one refresh on return ([_foregroundChanged]) catches up.if (!app.inForeground) return;+ if (_guestRefused) return;if (backgroundInventory && !_panelVisible && !busy) {if (machine?.connectionStatus != ConnectionStatus.connected ||machine?.isOffline == true) {@@ -247,6 +251,7 @@ class ModelManagerController extends ChangeNotifier {pendingOperation = null;pendingId = null;_dismissedReadyId = null;+ _guestRefused = false;models = null;localModels = const [];memoryBytes = null;@@ -542,6 +547,9 @@ class ModelManagerController extends ChangeNotifier {bool setup = false,bool local = true,}) async {+ // Refused for good on a computer shared with this account: nothing but a forced read (Try again)+ // asks again, so a four-second poll cannot grow the log with the same refusal.+ if (_guestRefused && !force) return;final owner = machine;if (owner == null ||owner.connectionStatus != ConnectionStatus.connected ||@@ -639,6 +647,18 @@ class ModelManagerController extends ChangeNotifier {))) {pendingOperation = null;}+ } on WsRequestFailure catch (failure) {+ if (_current(owner) && revision == _actionRevision) {+ inventoryAvailable = false;+ // A computer shared with this account never offers its models, and asking again will+ // not change that: say so once and stop the four-second poll.+ if (failure.code == 'GUEST_NOT_ALLOWED') {+ _guestRefused = true;+ error = 'Models are not available on a computer shared with you.';+ } else {+ error = 'Models are unavailable. Try again.';+ }+ }} catch (_) {if (_current(owner) && revision == _actionRevision) {inventoryAvailable = false;diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 1bc50d28e..d44a3844b 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -9176,7 +9176,9 @@ class _SwarmScreenState extends State<SwarmScreen> {);final total = _tabWidths.fold(0.0, (sum, width) => sum + width);// Arrows come out of the tabs' own budget, so the bar never reflows.- final arrows = chrome?.scrollsTabsByArrows == true && total > tabBudget;+ final arrows =+ scrollsTabsByMouse(chrome, windows: _windowsCaption) &&+ total > tabBudget;final tabsWidth = math.max(0.0,math.min(total, tabBudget) -@@ -9506,7 +9508,7 @@ class _SwarmScreenState extends State<SwarmScreen> {bool arrows, {required Color color,required Widget child,- }) => widget.chrome?.scrollsTabsByArrows != true+ }) => !scrollsTabsByMouse(widget.chrome, windows: _windowsCaption)? child: WorkspaceTabScroller(controller: _tabScroll,diff --git a/desktop/lib/super_tabs/attachment_image.dart b/desktop/lib/super_tabs/attachment_image.dartindex b3d85cf31..9ac36f260 100644--- a/desktop/lib/super_tabs/attachment_image.dart+++ b/desktop/lib/super_tabs/attachment_image.dart@@ -36,6 +36,15 @@ class _SuperTabInlineImageState extends State<SuperTabInlineImage> {Uri? _url;bool _asking = false, _retried = false, _failed = false;+ /// How long after each failed ask for a link the next one is made.+ static const _askAgainAfter = [+ Duration(seconds: 2),+ Duration(seconds: 5),+ Duration(seconds: 15),+ ];+ int _waited = 0;+ Timer? _askAgain;+@overridevoid initState() {super.initState();@@ -53,6 +62,8 @@ class _SuperTabInlineImageState extends State<SuperTabInlineImage> {}_ref = widget.file;_retried = _failed = false;+ _askAgain?.cancel();+ _waited = 0;_start();}@@ -68,7 +79,13 @@ class _SuperTabInlineImageState extends State<SuperTabInlineImage> {if (!mounted || _asking) return;final ref = _ref;setState(() => _asking = true);- final url = await superTabOpenableLink(context, ref, stale: stale);+ var worthAnother = false;+ final url = await superTabOpenableLink(+ context,+ ref,+ stale: stale,+ onUnavailable: (problem) => worthAnother = !problem.gone,+ );if (!mounted) return;// Another file, Swarm or account now: this answer is not for what is// shown. The ask is over all the same, and the one shown now is asked for.@@ -77,6 +94,15 @@ class _SuperTabInlineImageState extends State<SuperTabInlineImage> {if (_url == null && !_failed) _ask(stale: false);return;}+ // Still connecting, say, as the app starts: a failure of the ask says+ // nothing of the file, so the picture waits for another before it says it+ // can't be shown. It said so until the chat was opened again.+ if (url == null && worthAnother && _waited < _askAgainAfter.length) {+ final wait = _askAgainAfter[_waited++];+ setState(() => _asking = false);+ _askAgain = Timer(wait, () => _ask(stale: stale));+ return;+ }setState(() {_asking = false;_url = url;@@ -84,6 +110,12 @@ class _SuperTabInlineImageState extends State<SuperTabInlineImage> {});}+ @override+ void dispose() {+ _askAgain?.cancel();+ super.dispose();+ }+/// The picture did not load. A short-lived link may have ended under it:/// asked for once more. An older server's permanent link is not.void _broke() {diff --git a/desktop/lib/super_tabs/file_links.dart b/desktop/lib/super_tabs/file_links.dartindex af13eae98..8912922fd 100644--- a/desktop/lib/super_tabs/file_links.dart+++ b/desktop/lib/super_tabs/file_links.dart@@ -151,6 +151,7 @@ Future<Uri?> superTabOpenableLink(SuperTabFileRef ref, {bool stale = false,void Function(String message)? onProblem,+ void Function(SuperTabFileUnavailable problem)? onUnavailable,}) async {final source = SuperTabFiles.peek(context);bool still() => context.mounted && SuperTabFiles.peek(context) == source;@@ -158,7 +159,10 @@ Future<Uri?> superTabOpenableLink(final link = await ref.link(stale: stale);return still() ? link : null;} on SuperTabFileUnavailable catch (problem) {- if (still()) onProblem?.call(problem.message);+ if (still()) {+ onProblem?.call(problem.message);+ onUnavailable?.call(problem);+ }return null;}}diff --git a/desktop/lib/super_tabs/reminders.dart b/desktop/lib/super_tabs/reminders.dartindex f6ef635b0..ae0cb7afb 100644--- a/desktop/lib/super_tabs/reminders.dart+++ b/desktop/lib/super_tabs/reminders.dart@@ -75,6 +75,7 @@ class SuperTabReminders extends ChangeNotifier {DateTime? _next;Future<void>? _loading;bool _dirty = false, _disposed = false;+ int _fails = 0;/// The reminders already told of, by id and due time: one set again on the/// same message is news again. One due before this started is not news.@@ -116,24 +117,24 @@ class SuperTabReminders extends ChangeNotifier {Future<void> _read() async {final Map<String, dynamic> answer;- // A failed read is not tried again on each Swarm read; Retry or the next- // digest reads it.+ // A failed read is not tried again on each Swarm read: its own timer+ // tries, more slowly each time ([_retryAfter]). Retry or a new digest may+ // read it sooner._next = null;try {answer = await controller.request('GET', '$_path/reminders');} on SuperTabFailure catch (failure) {if (_disposed) return;if (failure.statusCode == 404) return;- error = 'Could not load reminders. Try again.';- notifyListeners();+ _readFailed();return;} catch (_) {if (_disposed) return;- error = 'Could not load reminders. Try again.';- notifyListeners();+ _readFailed();return;}if (_disposed) return;+ _fails = 0;final fresh = [for (final row in answer['due'] as List? ?? const [])SuperTabReminder.fromJson(superTabMap(row)),@@ -149,6 +150,29 @@ class SuperTabReminders extends ChangeNotifier {notifyListeners();}+ /// How long after each failed read in a row the next one runs.+ static const _retryAfter = [+ Duration(seconds: 5),+ Duration(seconds: 15),+ Duration(seconds: 30),+ Duration(seconds: 60),+ ];++ /// Reads again by itself: one slow answer must not leave an error up until+ /// someone presses Retry. One miss is ordinary on a slow connection, so the+ /// list says it could not load from the second.+ void _readFailed() {+ final wait = _retryAfter[_fails.clamp(0, _retryAfter.length - 1)];+ _fails++;+ _wake?.cancel();+ _wake = Timer(wait, () {+ if (!_disposed && !controller.accessRevoked) unawaited(load());+ });+ if (_fails < 2) return;+ error = 'Could not load reminders. Try again.';+ notifyListeners();+ }+/// Reads the list again when the next reminder is due.void _schedule(DateTime? next) {_wake?.cancel();diff --git a/desktop/lib/widgets/export_logs_dialog.dart b/desktop/lib/widgets/export_logs_dialog.dartindex 5bcdcd540..053ef9322 100644--- a/desktop/lib/widgets/export_logs_dialog.dart+++ b/desktop/lib/widgets/export_logs_dialog.dart@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';import '../core/harness_cli_runner.dart';import '../core/reveal_folder.dart';+import '../core/runtime_platform.dart';import '../logging/log_export.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_dialog.dart';@@ -127,7 +128,11 @@ class _ExportLogsDialogState extends State<_ExportLogsDialog> {if (!busy && result.path != null)TextButton(onPressed: () => unawaited(revealFile(result.path!)),- child: const Text('Show in Finder'),+ child: Text(+ RuntimePlatform.isWindows+ ? 'Show in Explorer'+ : 'Show in Finder',+ ),),if (!busy)FilledButton(diff --git a/desktop/lib/widgets/workspace_tab_scroller.dart b/desktop/lib/widgets/workspace_tab_scroller.dartindex 72987c025..3f397b115 100644--- a/desktop/lib/widgets/workspace_tab_scroller.dart+++ b/desktop/lib/widgets/workspace_tab_scroller.dart@@ -1,6 +1,7 @@import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';+import '../state/workspace_chrome.dart';import '../shared/theme/app_icons.dart';import '../shared/theme/workspace_bar_style.dart';import 'workspace_bar_control.dart';@@ -8,6 +9,13 @@ import 'workspace_bar_control.dart';/// Cells each arrow takes beside an overflowing tab list.const int kWorkspaceTabArrowCells = 3;+/// Whether tabs that do not fit get arrows and the mouse wheel: the web's chrome+/// asks for them, and Windows always has them. Without them, a Windows person+/// with a ninth tab had no way to reach the first, nor any sign it was there+/// (DESKTOP-0TFH0OJ, 2026-11-05: their Personal Swarm looked gone).+bool scrollsTabsByMouse(WorkspaceChrome? chrome, {required bool windows}) =>+ windows || chrome?.scrollsTabsByArrows == true;+/// Arrows either side of a tab list that no longer fits, for hosts with no/// trackpad-sideways habit to lean on ([WorkspaceChrome.scrollsTabsByArrows])./// Each arrow pages the list by most of its width and goes faint at its end;diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dartindex 1a7f9c794..cf372de22 100644--- a/desktop/lib/ws/ws_conn.dart+++ b/desktop/lib/ws/ws_conn.dart@@ -958,7 +958,12 @@ class WsConn {/// know. At WARN each was an immediate, fsync'd write to the app log on the/// UI isolate — once a minute for `shares` alone, for every account that/// never turned Agent Messages on — while saying nothing anyone acts on.- static const _expectedRefusals = {'MESSAGES_OFF', 'UNKNOWN_ACTION'};+ static const _expectedRefusals = {+ 'MESSAGES_OFF',+ 'UNKNOWN_ACTION',+ // A computer shared with this account answers some actions this way by design, not a fault.+ 'GUEST_NOT_ALLOWED',+ };static bool _expectedRefusal(Object error) =>error is WsRequestFailure && _expectedRefusals.contains(error.code);diff --git a/desktop/test/model_manager_controller_test.dart b/desktop/test/model_manager_controller_test.dartindex a6a73b27b..af4bc0341 100644--- a/desktop/test/model_manager_controller_test.dart+++ b/desktop/test/model_manager_controller_test.dart@@ -29,6 +29,26 @@ void main() {app.dispose();});+ test(+ 'a computer shared with this account refuses its models once and is not asked again',+ () async {+ app.localRefusal = 'GUEST_NOT_ALLOWED';+ await controller.refresh();+ expect(+ controller.error,+ 'Models are not available on a computer shared with you.',+ );+ final reads = app.localReads;+ await controller.refresh();+ expect(app.localReads, reads);+ // Try again is a forced read, and a daemon that answers it is shown as usual.+ app.localRefusal = null;+ await controller.refresh(force: true);+ expect(app.localReads, reads + 1);+ expect(controller.error, isNull);+ },+ );+test('Download is explicit and never falls back to Start on an older daemon',() async {diff --git a/desktop/test/super_tab_inline_image_retry_test.dart b/desktop/test/super_tab_inline_image_retry_test.dartnew file mode 100644index 000000000..06fb75a62--- /dev/null+++ b/desktop/test/super_tab_inline_image_retry_test.dart@@ -0,0 +1,140 @@+// A picture whose link had ended, opened as the app starts: the ask for a+// fresh one failed once, and the message said "can't be shown here" until the+// chat was left and opened again (Desktop 1.3.68 on DESKTOP-0TFH0OJ, 2026-11-05).+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/attachment_image.dart';+import 'package:harness/super_tabs/attachment_upload.dart';+import 'package:harness/super_tabs/attachment_viewer.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/file_links.dart';+import 'package:harness/super_tabs/model.dart';++final _png = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',+);++void main() {+ final now = DateTime.utc(2026, 11, 5, 12);+ const broken = 'shot.png can’t be shown here.';+ String signed({String sig = '1'}) =>+ 'https://$kSuperTabFilesHost/bucket/super-tabs/tab/a1/shot.png'+ '?X-Goog-Signature=$sig';++ late ImageProvider Function(Uri) original;+ setUp(() {+ original = attachmentImage;+ attachmentImage = (_) => MemoryImage(_png);+ superTabFileClock = () => now;+ });+ tearDown(() {+ attachmentImage = original;+ superTabFileClock = DateTime.now;+ });++ SuperTabAttachment fresh() => SuperTabAttachment.fromJson({+ 'id': 'a1',+ 'name': 'shot.png',+ 'mime': 'image/png',+ 'size': 3000,+ 'url': 'https://cdn.harness.autonomous.ai/a1/shot.png',+ 'link': signed(sig: 'fresh'),+ 'expiresAt': now.millisecondsSinceEpoch + 900000,+ });++ /// The picture, its link ended a minute ago; [ask] answers for a fresh one.+ Future<void> show(+ WidgetTester tester,+ Future<SuperTabAttachment> Function() ask,+ ) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabInlineImage(+ file: SuperTabFileRef(+ SuperTabAttachment.fromJson({+ 'id': 'a1',+ 'name': 'shot.png',+ 'mime': 'image/png',+ 'size': 3000,+ 'url': 'https://cdn.harness.autonomous.ai/a1/shot.png',+ 'link': signed(),+ 'expiresAt': now.millisecondsSinceEpoch - 60000,+ }),+ conversationId: 'lead',+ messageId: 'm1',+ fresh: (_, _, _) => ask(),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ await tester.pump();+ }++ testWidgets('a fresh link that failed once is asked for again, and shows', (+ tester,+ ) async {+ var asked = 0;+ await show(tester, () async {+ asked++;+ if (asked == 1) throw StateError('still connecting');+ return fresh();+ });+ expect(asked, 1);+ expect(find.text(broken), findsNothing);++ await tester.pump(const Duration(seconds: 3));+ await tester.pump();+ expect(asked, 2);+ expect(find.text(broken), findsNothing);+ expect(find.byType(Image), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets('it stops asking, and says so, when the link never comes', (+ tester,+ ) async {+ var asked = 0;+ await show(tester, () async {+ asked++;+ throw StateError('offline');+ });+ await tester.pump(const Duration(minutes: 1));+ await tester.pump(const Duration(minutes: 1));+ await tester.pump(const Duration(minutes: 1));+ await tester.pump();+ expect(asked, 4);+ expect(find.text(broken), findsOneWidget);++ await tester.pump(const Duration(minutes: 5));+ expect(asked, 4);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets('a file that is gone says so at once and is not asked again', (+ tester,+ ) async {+ var asked = 0;+ await show(tester, () async {+ asked++;+ throw const SuperTabFailure('NOT_FOUND', 'Not found', statusCode: 404);+ });+ expect(asked, 1);+ expect(find.text(broken), findsOneWidget);+ await tester.pump(const Duration(minutes: 1));+ expect(asked, 1);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets('leaving before the next ask leaves no timer behind', (+ tester,+ ) async {+ await show(tester, () async => throw StateError('offline'));+ await tester.pumpWidget(const SizedBox());+ // A pending timer would fail this test when it ends.+ });+}diff --git a/desktop/test/super_tab_reminders_test.dart b/desktop/test/super_tab_reminders_test.dartindex d5610a3a5..1fd73538f 100644--- a/desktop/test/super_tab_reminders_test.dart+++ b/desktop/test/super_tab_reminders_test.dart@@ -91,6 +91,27 @@ void main() {Finder reminderRow(String messageId) =>find.byKey(ValueKey('super-activity-row-reminder:reminder-$messageId'));+ // One slow answer at startup left "Could not load reminders" on Decisions+ // until the person pressed Retry (DESKTOP-0TFH0OJ, 2026-11-05).+ testWidgets('a read that fails is tried again by itself, and says so only '+ 'once it has failed twice', (tester) async {+ final server = _chat()+ ..state['remindersDigest'] = 'r1'+ ..failReadsOf = '/reminders';+ await show(tester, server);+ final reminders = SuperTabReminders.of(c);+ expect(reminders.error, isNull);++ await tester.pump(const Duration(seconds: 6));+ await tester.pump();+ expect(reminders.error, 'Could not load reminders. Try again.');++ server.failReadsOf = null;+ await tester.pump(const Duration(seconds: 16));+ await tester.pump();+ expect(reminders.error, isNull);+ });+group('Remind me', () {testWidgets('In 20 minutes asks for the time 20 minutes on', (tester,diff --git a/desktop/test/support/model_manager.dart b/desktop/test/support/model_manager.dartindex dcdfdf532..fc6c4ed59 100644--- a/desktop/test/support/model_manager.dart+++ b/desktop/test/support/model_manager.dart@@ -151,6 +151,8 @@ class ModelManagerTestApp extends AppNotifier {}bool localReadFails = false, actionReplyLost = false;+ /// A refusal the daemon gives the local inventory for good (a computer shared with this account).+ String? localRefusal;Completer<Map<String, dynamic>>? actionReply;/// Harness sign-ins started ([login]), and whether the next one lands — the browser completing it@@ -197,6 +199,12 @@ class ModelManagerTestApp extends AppNotifier {return held.future;}if (localReadFails) throw StateError('offline');+ if (localRefusal != null) {+ throw WsRequestFailure(+ responseType: 'grid_fleet_models_list',+ code: localRefusal!,+ );+ }return inventoryFor(machineId);}diff --git a/desktop/test/workspace_tabs_by_mouse_test.dart b/desktop/test/workspace_tabs_by_mouse_test.dartnew file mode 100644index 000000000..8098cafe0--- /dev/null+++ b/desktop/test/workspace_tabs_by_mouse_test.dart@@ -0,0 +1,12 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/widgets/workspace_tab_scroller.dart';++void main() {+ test('Windows reaches tabs that do not fit by arrows and the wheel', () {+ expect(scrollsTabsByMouse(null, windows: true), isTrue);+ });++ test('a host with its own tab strip keeps it', () {+ expect(scrollsTabsByMouse(null, windows: false), isFalse);+ });+}diff --git a/docs/superpowers/plans/2026-11-05-windows-backlog.md b/docs/superpowers/plans/2026-11-05-windows-backlog.mdnew file mode 100644index 000000000..860563d7a--- /dev/null+++ b/docs/superpowers/plans/2026-11-05-windows-backlog.md@@ -0,0 +1,163 @@+# Windows Backlog Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task by task, in this session. The owner has said not to use subagents. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Everything still open on Windows, measured against what the Mac does on `main` today, is fixed, or is named with the reason it stays open.++**Architecture:** Two kinds of task. A **walk** runs a Mac flow on the real PC and turns each failure into a root-cause fix with a test that failed first. A **gap** is a difference already read in the code, fixed the same way. Windows-only branches stay behind the platform checks that exist; Mac and Linux behavior does not change unless a task says so.++**Tech Stack:** TypeScript CLI (vitest), Flutter Desktop, Rust `pty/` and `tui/`, PowerShell on the PC.++**Spec:** `docs/superpowers/specs/2026-11-04-windows-parity-design.md`, and the audit below, which replaces its "Where Windows stands today".++## Audit against `main` at d99e24ca6 (2026-11-05)++Mac-only checks read and found **correct, no work**: menu-bar notices (Windows keeps the sidebar row and has toasts), keychain usage read, Spotlight marker, folder read by descriptor (Windows reads by path), responsibility probe, Mac fonts. Services run in the core's process on Windows, by design.++| # | Open item | Evidence | Task |+|---|---|---|---|+| 1 | CLI 0.5.40 with production's terminal host 0.4.31 never run; `hn` in a real console never run | manifests; last session's PC ran 9.9.9 | 1 |+| 2 | Not walked on Windows: Git project and worktree, commit and push through the GitHub App, Import, Share, plain terminal, rename, `harness remote`, `team model`, device flows | PR #3032 | 2 |+| 3 | Agents stuck at their engine's own hidden screen | #3063 handles Codex's trust screen; "Hooks need review" is not in it | 3 |+| 4 | Cursor, Devin, Grok, Antigravity have no hooks on Windows; Hermes's are unconfirmed | `win32Runner` absent; `hooksNotOnWindows` | 4 |+| 5 | Seven PowerShell installers never run end to end; `programs` paths read, not measured | `ENGINE_WINDOWS_INSTALL` | 4 |+| 6 | Windows panes lack the grid `PATH` and `GRID_NO_UPDATE_CHECK`, and Harness's Node at the end of `PATH` | `gridPanePrelude` runs in the POSIX script only; `engineStart.ts` "Not done" | 5 |+| 7 | Pane blank for 15-50 s during an engine's first start | Copilot and Kilo on the PC | 6 |+| 8 | Stopping panes dropped tabs from 5 to 3; New Harness defaulted to another machine | seen on the PC, not investigated | 6 |+| 9 | Desktop release fails on one connection reset | `scripts/verify-desktop-release.py`, 1.3.65 | 7 |+| 10 | `feat/windows-app-menu` and `-dropdowns` unmerged (7 commits), overlapping #2947 | `git rev-list`; the owner's dirty checkout holds related files | 8 |+| 11 | New Swarm hidden from Search commands | memory, 10-29; `keymap_commands.dart:773` suggests fixed | 8 |+| 12 | Arm not rerun since the serial spec fix | PR #3032 | 9 |+| 13 | Native `hn` gate failures never compared with `main` | PR #3032 | 9 |+| 14 | `hn` shell integration is Unix only | `shell_picker.rs` | 10 |+| 15 | Add machine to a Team is heavy | owner, unanswered | 11 |+| 16 | Guests on Windows are design only | guests spec | 12 |+| 17 | Teammate routing to `<host> · Team` needs a second person | memory | named as open |++## Global Constraints++- Root cause, no stopgaps; every bug fix has a test that failed first.+- Windows checks run on the signed build on DESKTOP-0TFH0OJ, in the Personal Swarm only. Send nothing into shared Swarms.+- Ask before every commit and push. Edit code with the Edit tool. Run long suites once, saved to a file.+- Never print secrets. The PC's `.codex\config.toml` holds a plain key: read its keys by name, never the file.+- Do not run a vendor's installer from a script of ours: only through the product. Never approve another program's hooks on the person's behalf.+- Do not touch the owner's dirty main checkout. Copy follows `docs/naming-system.md`.+- Mac and Linux keep their tests green; a change to shared code says so in its PR.++## Review Focus++1. A profile folder with a space in its name: every hook line and installer path must still work.+2. A computer with another program's hooks already in the engine's file (Orca's blocks moved Harness's to index 1).+3. A daemon restart mid-install or mid-start: nothing left running as nobody's, nothing installed twice at once.+4. A person who is watching the pane answers the screen first: an automatic answer must not type into whatever comes next.+5. An older daemon with a newer Desktop, and CLI 0.5.40 with host 0.4.31: refuse in words, never hang.++---++### Task 1: The production combination++**Files:** whatever the walk finds; likely `cli/src/tui/index.ts`, `cli/src/lib/windows/`.++- [ ] **Step 1:** On the PC, run CLI 0.5.40 with host 0.4.31 (download it from the production manifest, check its sha256). Create a pane, stop it, reopen it, run `hn`.+ Expected: panes work; `hn` says `TUI_NOT_IN_PAYLOAD`, no crash.+- [ ] **Step 2:** Point `current-pty` at the staged 0.5.40, check signatures, run `hn` in a real console: list, attach, type, detach, a pane's exit.+ Expected: Authenticode valid under Smart App Control; each step works.+- [ ] **Step 3:** Fix each failure at its cause, test first. Commit.++### Task 2: Walk the Mac flows on Windows++**Files:** whatever the walk finds.++Each row is a Mac flow run as a person would, on the signed build:++- [ ] **Step 1: Git project.** Open a real repository in New Harness, with and without a worktree. Expected: branch shown, worktree created under `harnesses\worktrees`, deleted with the harness.+- [ ] **Step 2: Swarm with the GitHub App.** In a throwaway repository the owner names, a Personal Swarm task commits, pushes and opens a pull request, which appears in Pull requests. Expected: authored as the App or the owner as on a Mac; `gh` missing gives its banner.+- [ ] **Step 3: The rest.** Import an agent; Share a harness and open the link; plain terminal; rename a harness and see its Swarm agent renamed (#2912); `harness remote`; `team model`; Threads, Mentions and Decisions in the sidebar (#3057); themes when #3059 lands.+- [ ] **Step 4: Devices.** Add device with no device attached says so in words; with hardware only if the owner plugs it in, else named as unverified.+- [ ] **Step 5:** Fix each failure at its cause, test first. Commit per fix.++### Task 3: A hidden engine screen does not end a Swarm start++Blocked on #3063 merging; build on its `startScreen.ts` and `openRestrictedKeys` pattern, not beside them.++**Files:**+- Modify: `cli/src/engines/codex/screen.ts`, `cli/src/superTabs/startScreen.ts`+- Test: `cli/src/engines/codex/hooksReview.spec.ts`; fixture `cli/src/superTabs/fixtures/screens/codex-0163-hooks-review.txt`, captured from the PC++**Interfaces:**+- Produces: `hooksReviewSkipKeys(capture: string): string[] | null`++- [ ] **Step 1: Failing test.** The exact screen gives the keys for "Continue without trusting"; a capture with any line changed, a selection on another row, or text typed in it gives `null`; "Trust all" is never returned.+- [ ] **Step 2:** Run it, watch it fail.+- [ ] **Step 3:** Implement. Only for a Swarm start's own pane, before it has a session, never a pane a person opened. Read the screen again before sending.+- [ ] **Step 4:** Any other screen still blocking at the start's deadline fails it at once with the screen's first line, through #3063's path, so the Lead tells the person what it asks.+- [ ] **Step 5:** On the PC, with Orca's hooks present, a Lead starts a Codex engineer. Expected: it joins in seconds; `harness show` proves Harness's hooks fired; Orca's did not run; `config.toml` gained no trust for Orca.+- [ ] **Step 6:** Commit.++### Task 4: Every engine installs and reports on Windows++**Files:**+- Modify: `cli/src/lib/engineInstall.ts` (`programs`), `cli/src/engines/{cursor,devin,grok,agy}/contract.ts` (`win32Runner`), `cli/src/engines/kit/windowsHooks.spec.ts`++- [ ] **Step 1:** Through the app, one at a time, install Cursor, Amp, Grok, Devin, Muse, Antigravity, Oh My Pi. For each record: installer log, where the program landed, whether the pane opened. Fix `programs` from what is measured.+- [ ] **Step 2:** For each hooked engine, read how it runs a hook on Windows from its own source or docs; measure one on the PC. Record it beside its `win32Runner`, as the existing rows do. An engine whose runner cannot be proven keeps `hooksNotOnWindows`, named in the PR.+- [ ] **Step 3: Failing tests.** In `windowsHooks.spec.ts`, each new engine's line is quoted for its runner, with a space in the profile path; replace the "no runner" assertion on lines 26-30 of the block with the new values.+- [ ] **Step 4:** Implement, run, then on the PC confirm a session binds and turns close for each engine that can sign in; Hermes past its first-run question. One that needs a paid login is named as unverified.+- [ ] **Step 5:** Commit.++### Task 5: Windows panes get what the launch script gives a Mac pane++**Files:**+- Modify: `cli/src/lib/windows/engineStart.ts`, `cli/src/lib/engineLaunch.ts`+- Test: `cli/src/lib/windows/engineStart.spec.ts`++**Interfaces:**+- Produces: `windowsPaneEnvironment(gridBinary: string | null, nodeDir: string, path: string): Record<string, string>`++- [ ] **Step 1: Failing tests.** With a grid binary: its folder first on `PATH`, `GRID_NO_UPDATE_CHECK=1`. Harness's Node folder last on `PATH`. One `PATH` key whatever its case. No grid binary: only the Node folder.+- [ ] **Step 2:** Run, watch fail. Implement. Use `path.win32`.+- [ ] **Step 3:** On the PC, a grid-model harness runs `grid --version` from its pane, and its `grid update` is not offered. Commit.++### Task 6: First start and stop on Windows read as they do on a Mac++**Files:** `cli/src/core/agents/heldLaunches.ts`, `desktop/lib/state/` as the cause shows.++- [ ] **Step 1:** Measure on the PC and read on the Mac what shows between pressing New Harness and the engine's first paint, for an engine already installed and for one installing.+- [ ] **Step 2:** Failing test, then show the held line ("Installing Copilot…", "Starting Copilot…") until the engine draws. Same words as the Mac's.+- [ ] **Step 3:** Reproduce 5 tabs dropping to 3 after stopping panes. Find the cause in the desktop's tab sync; compare with the Mac before calling it a bug. Fix with a failing test if it is one.+- [ ] **Step 4:** New Harness's default machine: read the rule on the Mac and match it; a Windows app with this computer available opens on it only if the Mac does. Commit.++### Task 7: One connection reset does not fail a Desktop release++**Files:** Modify `scripts/verify-desktop-release.py`; test beside its existing tests.++- [ ] **Step 1: Failing test.** A download reset twice then served passes; served with a wrong sha256 fails at once with no retry; reset on every try fails naming the file.+- [ ] **Step 2:** Implement three tries with backoff, for connection errors and 5xx only. Run. Commit.++### Task 8: The Windows menu branch and Search commands++- [ ] **Step 1:** Compare `origin/feat/windows-app-menu-dropdowns` with `main`, commit by commit. List what #2947 already carries and what is left.+- [ ] **Step 2:** Move only what is left to this branch, keeping its author. Triage against `desktop/test/windows_app_menu_test.dart` on `main`. Ask the owner before dropping anything of theirs.+- [ ] **Step 3:** Confirm New Swarm in Search commands on the PC. If absent, failing test in the keymap tests, then fix. Commit.++### Task 9: Runs nobody has compared++- [ ] **Step 1:** Read the Windows workflow's latest run on `main` for the Arm job. If it has not run since the serial fix, start it once, by hand.+- [ ] **Step 2:** Build `hn` from `main` before #3032 and from `main` now; run `scripts/validate-tui-native.py` once on each, sequentially, output saved to files. Only fixtures failing now and passing before are this work's: fix those. Update the memory note on the rest.++### Task 10: `hn` shell integration in PowerShell (lowest priority, owner's words)++**Files:** `tui/src/shell_picker.rs`, `tui/src/shell_context.rs`, new `tui/src/shell_powershell.rs`++- [ ] **Step 1:** Spike: a PowerShell profile fragment that carries the cwd and command marks to `hn` over the owner-only pipe in `tui/src/sock.rs`, in place of FIFOs. Write what it can and cannot do in the plan's ledger before more code.+- [ ] **Step 2:** Failing tests for the fragment's text and for the marks parsed; implement; run on the PC. Commit, or name it as dropped with the reason.++### Task 11: Adding a machine to a Team (design first)++- [ ] **Step 1:** Draw the current steps and a one-click flow with one status per machine, as a local HTML file in `~/Downloads`. The owner chooses before any code.+- [ ] **Step 2:** Plan the chosen flow as its own document.++### Task 12: Guests on Windows (security review first)++- [ ] **Step 1:** Spike on a signed build per `docs/superpowers/specs/2026-11-04-windows-guests-design.md`, on a disposable local account, removed afterwards.+- [ ] **Step 2:** The owner names a security reviewer. No product code before that review.diff --git a/docs/windows-rules.md b/docs/windows-rules.mdnew file mode 100644index 000000000..1846989e8--- /dev/null+++ b/docs/windows-rules.md@@ -0,0 +1,109 @@+# Windows rules++Everything here cost real time on a real Windows computer. Read it before you change code that starts a+process, runs a script, or shows text on Windows, and before you test anything there. A person on Windows+must see what a person on a Mac sees: the app, and nothing else.++## 1. Harness never opens a window the person did not ask for++On a Mac a background program has no window. On Windows a console program started by a process that has no+console gets a new console, and that window flashes up and closes. The person sees it every time, and they+cannot tell what it was.++Measured on Windows 11 with Windows Terminal as the default terminal (2026-11-05). A Node parent with a hidden+console, as the daemon has, starts `cmd`, and `cmd` starts `ping` and `powershell`:++| Node `spawn` options | A window flashes? |+|---|---|+| `detached: true` | **Yes** |+| `detached: true, windowsHide: true` | **Yes** |+| none | No |+| `windowsHide: true` | No |++Why: libuv turns `detached` into `DETACHED_PROCESS`, so the child has no console at all, and each console+program it starts then gets a new one. `CREATE_NO_WINDOW` is ignored beside `DETACHED_PROCESS`, so+`windowsHide` cannot rescue it. It looks hidden in a quick test when the child itself starts nothing.++The rules:++- **CLI (Node): never `detached: true` on Windows for a program that starts other programs.** Use+ `ownProcessGroup()` from `cli/src/lib/windows/noWindow.ts`: its own process group on macOS and Linux, a hidden+ console on Windows. `cli/src/lib/windows/noWindow.spec.ts` fails on a new `detached: true` anywhere in `cli/src`+ unless that file lists it with the reason.+- **A process that must outlive Node** (Node ends a child that is not detached when Node exits) starts through+ `bin\harness-launch.exe` (`cli/src/lib/windows/launcher.ts`), which uses `CREATE_NO_WINDOW`, or through a small+ detached runner that starts the real work hidden (`cli/src/engines/kit/windowsInstall.ts`).+- **Desktop (Dart): use `startHidden` and `runHidden`** (`desktop/lib/core/hidden_process.dart`). Plain+ `Process.start` and `Process.run` in normal mode are hidden too. `ProcessStartMode.detached` is only for a GUI+ program (`explorer.exe`, the launcher). `inheritStdio` and `runInShell` are not for a console program.+- **Rust:** `CREATE_NO_WINDOW`, never with `DETACHED_PROCESS` (`pty/src/launcher.rs`).+- **A scheduled task** runs a GUI-subsystem program (`harness-launch.exe`), never `powershell.exe` or `cmd.exe` in+ the person's session. `powershell -WindowStyle Hidden` still flashes before it hides.+- **Test helpers follow the same rule.** A script that runs on someone's computer through a scheduled task must run+ hidden (WScript `Run line, 0, True`). A window from a test looks exactly like a window from the product.++Prove it by recording, not by watching: list the visible windows of class `ConsoleWindowClass`,+`CASCADIA_HOSTING_WINDOW_CLASS` and `PseudoConsoleWindow` every 40 ms through the flow you changed, with each owner's+command line. A person's eye misses most of them, and a run over SSH sees none, because SSH lands in session 0.++Sources: [Node `child_process`](https://nodejs.org/api/child_process.html) (`windowsHide` defaults to `false`+everywhere), [Process Creation Flags](https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags),+[Creation of a Console](https://learn.microsoft.com/en-us/windows/console/creation-of-a-console), Dart SDK+[`process_win.cc`](https://github.com/dart-lang/sdk/blob/main/runtime/bin/process_win.cc).++## 2. Starting processes++- A **detached PowerShell has no console, exits 0, and runs nothing.** A zero exit from it proves nothing: check the+ result the script should have made.+- Node ends a child that is not detached when Node exits (a kill-on-close job). Only that direct child: what the child+ starts in turn is outside the job.+- SSH sessions and scheduled tasks end their children too. A survival test run through either one tells you nothing about+ a person's computer. Test from the app.+- `-EncodedCommand` makes PowerShell write CLIXML to stderr. Use `-Command` when anyone reads the error.+ Inside `-Command`, `-ErrorAction Stop` needs `try`/`catch` for the script to end.++- **A paste can arrive as keys.** The Mac gets one paste event, so Enter after it is safe. Codex on Windows gets a stream of key+ presses, and an Enter within 120 ms of the last becomes a newline in the paste (codex-rs `paste_burst.rs`): the message stays in+ the composer and every later one waits behind that "draft". Wait for the paste to show on screen (`lib/pasteOnScreen.ts`), not a+ fixed time.++- **An unsigned program is blocked, and the person is told.** Smart App Control refuses it (`spawn UNKNOWN`, thrown by `spawn`, not+ an `error` event), and each attempt can raise a notice naming Node.js. Never poll an unsigned program: run what it starts, if that+ is signed (`gridCommand` in `lib/gridBinary.ts`), or stop asking. Check `Microsoft-Windows-CodeIntegrity/Operational` after a change.++## 3. Files++- **A file's change time moves when its last handle closes**, after a rename that published it. Measured 2026-11-05: `ctimeNs`+ differed before and after `close`. Do not compare it across a close: three plugins were written and then reported as failed+ (`hookFileVersion` in `cli/src/engines/kit/nativeHookFiles.ts`).+- **A rename over a read-only file fails with `EPERM`.** A file we write read-only stops every later refresh unless it is made+ writable first (`writeCopies` in `cli/src/superTabs/buddyHome.ts`).+- **There is no `ps`.** Read the process table through `lib/windows/processTable.ts`. A check that treats a failed `ps` as "gone"+ quietly does nothing on Windows: viewers piled up for that reason (`dsh/viewerLedger.ts`).+- **What Git Bash runs has a parent that has gone.** Walking Windows' parent links does not reach it (`lib/windows/gitBashTree.ts`).++## 4. Screens a person sees++- **A mouse has no sideways scroll.** Anything that overflows sideways needs arrows and the wheel, or what falls off the end looks+ deleted (`scrollsTabsByMouse` in `desktop/lib/widgets/workspace_tab_scroller.dart`).+- **A window that nobody asked for is rule 1.** A prompt nobody can answer in a hidden pane is its sibling: answer the exact screen+ safely or fail the start with a reason (`cli/src/superTabs/startScreen.ts`).++## 5. Testing on Windows++- Test in the person's session (session 1) and in the signed build. Windows behaves differently in session 0 and for an+ unsigned file.+- `SendKeys` Ctrl+Shift chords do not reach the app. That is the test's fault. Send real key events (`keybd_event`).+- Claude Code on Windows takes a pasted image on Alt+V, not Ctrl+V.+- Check the machine chip says This Computer before you start anything: a new Harness can default to another machine.+- Files and secrets: read a config file by key name. Never print `config.toml` or similar: it can hold a plain API key.++## 6. Words++Windows people read "Windows" or "this computer", never "Mac", "Finder", "Terminal.app" or `~/`. Text shared by all+platforms says "this computer". See the [Naming System](naming-system.md).++## When you find a new one++Add it here in the same change as the fix: what happened, what was measured, the rule. Add a test that fails if it comes+back, where a test can catch it. A note alone did not stop the last one.