Skip to content

Commit 45aaea7

Browse files
committed
fix: preserve chat lifecycle and CrewCoder runtime state
1 parent 5450451 commit 45aaea7

23 files changed

Lines changed: 744 additions & 39 deletions

‎AGENTS.md‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,23 @@ Update corresponding Docs in [CrewCode Docs](/docs/), and [AGENTS.md](/AGENTS.md
2424

2525
## Agent Notes
2626

27+
Explicit Stop must reach runtime teardown without waiting for provider abort
28+
acknowledgement. Windows termination targets only the owned runtime PID tree;
29+
never kill by provider/image name. Preserve the native resume id and do not replay
30+
the cancelled prompt. Keep desktop and Brain Stop behavior aligned.
31+
32+
Bridge invalidation from model/effort/profile/approval or hydrated settings must
33+
defer while startup or a turn is active. Apply the restart on the next idle send
34+
with the existing resume key; never send changed settings into the old runtime.
35+
Explicit Stop/removal remains immediate. Unexpected CrewCoder ACP exits must
36+
retain the observed code/signal and bounded stderr tail without replaying work.
37+
See `docs/crewcoder-provider.md`.
38+
39+
Keep CrewCoder lifecycle diagnostics independent of chat error suppression:
40+
record internal stop callers and observed exit code/signal/stderr in the OS-temp
41+
`crewcode-crewcoder-lifecycle.jsonl`. A packaged executable path does not establish
42+
its build revision, and a requested internal stop is not proof of a user action.
43+
2744
Codex Full Access must keep `on-request` so MCP computer-use consent can reach
2845
the bridge's approval rules. CrewCoder's nested Codex adapter must also answer
2946
MCP elicitations explicitly; native Full access does not erase a service's own
@@ -59,12 +76,22 @@ grants, including in Full Access. See `docs/chat-artifacts.md`.
5976
Delegation first-send placement is an explicit CrewCode choice before provider
6077
dispatch. Honor the persisted owner isolation choice, pin shared checkout paths
6178
separately from isolated worktree metadata, and never checkout the parent to
62-
satisfy delegation. Cancel pending sends on Stop/session or checkout changes;
79+
satisfy delegation. Cancel pending sends on explicit Stop/session removal or checkout changes;
6380
recheck parent liveness and cohort after worktree creation, preserving interrupted
6481
results without launching workers. Stop during bridge startup must cancel prompt
6582
forwarding and stale-bridge retries, targeting only the exact late bridge id.
6683
See `docs/delegated-threads.md`.
6784

85+
Pane unmounts and switching visible chats are navigation, not Stop. A submitted
86+
prompt must finish starting in its captured session even when hidden. Preserve
87+
explicit Stop and same-session provider/checkout cancellation; explicit session
88+
removal/reset must retire an exact late startup before any prompt is dispatched.
89+
The explicit Stop button must bypass launch-setting restart deferral using
90+
`dropBridge(..., { stopRunning: true })`, scoped to its exact session/provider.
91+
Clear the selected pane's pending-send UI immediately on Stop, even before a
92+
bridge id exists. Late settlement of the cancelled RPC must not change a newer
93+
send's indicator or another chat's state. See `usePendingChatSend`.
94+
6895
Windows provider discovery must use the shared Windows executable candidates
6996
for desktop, Brain, and usage probes, including native .exe and npm .cmd/.bat
7097
launchers and per-user locations when the GUI PATH is stale. Never use Unix
@@ -185,6 +212,12 @@ reconciliation, startup, or session switching. Preserve global delivery for
185212
newly appended live errors and active-scope delivery for live agent-exit
186213
warnings. See `docs/notifications.md`.
187214

215+
CrewCoder thought chunks with `crewcoder/progress` metadata are authoritative
216+
item snapshots: replace by turn/item/kind, including empty corrections, and do not
217+
also append portable text. Consume matching commentary dialogue echoes once in
218+
Thinking; snapshot updates must not split active reply bubbles. Keep plain ACP delta compatibility and the existing
219+
Thinking log presentation. See `docs/crewcoder-provider.md`.
220+
188221
CrewCoder negotiates `_crewcoder/request_question` for nested provider questions
189222
and permission details. Keep questions separate from permission-option filtering
190223
and Full Access auto-approval; preserve free text, choices, and cancellation.

‎docs/crewcoder-provider.md‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,15 @@ CrewCoder is a first-class CrewCode chat and Crew provider implemented by
66
`--mode`, and translates newline-delimited JSON-RPC 2.0 onto the shared
77
`AgentBridge` event stream. CrewCoder remains the ACP agent.
88

9+
CrewCode consumes optional `_meta["crewcoder/progress"]` thought snapshots by
10+
turn, item id, and kind. Updates replace that item's Thinking log text, including
11+
completed corrections and empty results, instead of appending the portable fallback
12+
again. Commentary snapshots also identify the matching portable dialogue echo;
13+
CrewCode consumes that echo once in Thinking rather than opening a reply for each
14+
token. Snapshot updates do not close an active dialogue bubble, so interleaved
15+
progress cannot fragment replies. Older ACP thought chunks still stream as text deltas. This keeps the existing
16+
CrewCode Thinking log presentation without changing CrewCoder's own thinking UI.
17+
918
CrewCoder-specific usage metadata, permission semantics, reasoning,
1019
and tool-call ordering must not change Hermes behavior.
1120

@@ -98,6 +107,46 @@ plan is a normal composer message; CrewCoder treats that as a new
98107

99108
## ACP lifecycle
100109

110+
The shared desktop/Brain Stop path requests cancellation but never waits for its
111+
acknowledgement before runtime teardown. Windows kills target the exact owned
112+
runtime PID and its descendants, including npm launcher children. Stop keeps the
113+
saved native session id so the next user message follows normal resume; it never
114+
replays the cancelled prompt automatically. Unix and SSH keep their existing
115+
process/channel termination paths.
116+
117+
Switching chats or unmounting the visible pane does not cancel a submitted prompt,
118+
including while its bridge is still starting. The send retains its original chat,
119+
provider, and checkout. Explicit Stop, same-session provider/checkout changes, and
120+
session removal/reset retain cancellation. If removal wins a startup race, the
121+
registry stops the exact late bridge and refuses prompt dispatch.
122+
The Stop button explicitly requests `dropBridge(..., { stopRunning: true })`;
123+
it must bypass the deferral used for launch-setting changes, affect only the
124+
selected session/provider, and retire a late startup before dispatch.
125+
Stop also clears the pane's local pending-send indicator immediately, without
126+
waiting for startup/resume RPC settlement. Late completion of a stopped send
127+
must not clear a newer send's indicator or make another chat look busy.
128+
129+
Launch-setting changes discovered during startup or an active turn must not
130+
terminate that chat. CrewCode defers model, effort, profile, approval, and other
131+
bridge invalidations until the next idle send, which restarts with the latest
132+
settings and the existing resume key. Sends under changed settings are refused
133+
until the current turn settles. Explicit Stop and session removal still stop
134+
their exact bridge.
135+
136+
Unexpected ACP exits report the observed exit code or termination signal and a
137+
bounded stderr tail, including an unterminated last line. Missing exit status is
138+
reported explicitly. CrewCode does not automatically replay an interrupted prompt.
139+
The preceding error carries the cause even if the generic exit row has no code.
140+
141+
Every CrewCoder stop request and exit also appends a diagnostic record to
142+
`crewcode-crewcoder-lifecycle.jsonl` in the agent host's OS temporary directory
143+
(`%TEMP%` on Windows). This remains active for expected/internal stops, whose
144+
chat errors are intentionally suppressed. Records include bridge/process ids,
145+
the stop caller stack, exit code/signal, whether Stop was requested, and a bounded
146+
stderr tail; they exclude prompt and response bodies. A requested stop establishes
147+
that CrewCode initiated teardown, not that the user clicked Stop. Inspect this
148+
file for unexplained `agent exited (unknown)` rows instead of inferring an old build.
149+
101150
The bridge performs this handshake before reporting ready:
102151

103152
1. `initialize` with protocol version 1 and text-file capabilities. The bridge
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { describe, expect, it, vi } from 'vitest'
2+
import { spawnAgentProcess, type AgentProc } from './agent-spawn'
3+
4+
vi.mock('../remote/ssh-pool', () => ({ execRemoteStream: vi.fn() }))
5+
6+
function alive(pid: number): boolean {
7+
try { process.kill(pid, 0); return true } catch { return false }
8+
}
9+
10+
describe('owned Windows runtime termination', () => {
11+
it.skipIf(process.platform !== 'win32')('terminates one runtime and its child while leaving a sibling runtime alive', async () => {
12+
const roots: Array<{ proc: AgentProc; closed: Promise<void> }> = []
13+
const children: number[] = []
14+
const fixture = "const {spawn}=require('node:child_process');const c=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});console.log(c.pid);setInterval(()=>{},1000)"
15+
try {
16+
for (let index = 0; index < 2; index++) {
17+
const { proc } = await spawnAgentProcess({ command: process.execPath, args: ['-e', fixture], cwd: process.cwd() })
18+
const closed = new Promise<void>(resolve => { proc.on('close', () => resolve()) })
19+
roots.push({ proc, closed })
20+
const child = await new Promise<number>((resolve, reject) => {
21+
let output = ''
22+
proc.on('error', reject)
23+
proc.stdout.on('data', (chunk: Buffer) => {
24+
output += chunk.toString()
25+
if (!output.includes('\n')) return
26+
const pid = Number(output.trim())
27+
if (!Number.isInteger(pid) || pid <= 0) reject(new Error('Invalid fixture child PID'))
28+
else resolve(pid)
29+
})
30+
})
31+
children.push(child)
32+
}
33+
expect(children.every(alive)).toBe(true)
34+
roots[0]!.proc.kill()
35+
await roots[0]!.closed
36+
await vi.waitFor(() => expect(alive(children[0]!)).toBe(false), { timeout: 5_000 })
37+
expect(alive(roots[1]!.proc.pid!)).toBe(true)
38+
expect(alive(children[1]!)).toBe(true)
39+
} finally {
40+
for (const root of roots) root.proc.kill()
41+
await Promise.all(roots.map(root => root.closed))
42+
}
43+
}, 15_000)
44+
})

‎src/main/agents/agent-spawn.test.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,24 @@
11
import { afterEach, describe, expect, it, vi } from 'vitest'
22
import { spawnAgentProcess } from './agent-spawn'
33

4-
const { spawn, execRemoteStream } = vi.hoisted(() => ({ spawn: vi.fn(() => ({})), execRemoteStream: vi.fn() }))
5-
vi.mock('child_process', () => ({ spawn }))
4+
const { spawn, execFile, execRemoteStream } = vi.hoisted(() => ({
5+
spawn: vi.fn(() => ({ pid: 123, exitCode: null, signalCode: null, kill: vi.fn(() => true) })),
6+
execFile: vi.fn(), execRemoteStream: vi.fn(),
7+
}))
8+
vi.mock('child_process', () => ({ spawn, execFile }))
69
vi.mock('../remote/ssh-pool', () => ({ execRemoteStream }))
7-
afterEach(() => { vi.restoreAllMocks(); spawn.mockClear() })
10+
afterEach(() => { vi.restoreAllMocks(); spawn.mockClear(); execFile.mockClear() })
811

912
describe('local agent spawning', () => {
13+
it('kills only the selected owned Windows process tree', async () => {
14+
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
15+
const { proc } = await spawnAgentProcess({ command: 'C:/bin/codex.exe', args: [], cwd: 'C:/project' })
16+
proc.kill()
17+
proc.kill()
18+
expect(execFile).toHaveBeenCalledOnce()
19+
expect(execFile).toHaveBeenCalledWith(expect.stringMatching(/taskkill.exe$/i),
20+
['/PID', '123', '/T', '/F'], { windowsHide: true }, expect.any(Function))
21+
})
1022
it('routes Windows npm launchers through cmd.exe', async () => {
1123
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
1224
await spawnAgentProcess({ command: 'C:/CLI Tools/crewcoder.cmd', args: ['acp'], cwd: 'C:/project' })

‎src/main/agents/agent-spawn.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { spawn } from 'child_process'
1+
import { execFile, spawn } from 'child_process'
2+
import { join } from 'path'
23
import type { ClientChannel } from 'ssh2'
34
import { isRemoteRoot, parseRemoteTarget } from '../remote/ssh-target'
45
import { execRemoteStream } from '../remote/ssh-pool'
@@ -18,7 +19,7 @@ export interface AgentProc {
1819
}
1920
stdout: NodeJS.ReadableStream
2021
stderr: NodeJS.ReadableStream
21-
on(event: 'close', cb: (code: number | null) => void): void
22+
on(event: 'close', cb: (code: number | null, signal?: NodeJS.Signals | null) => void): void
2223
on(event: 'error', cb: (err: Error) => void): void
2324
kill(): void
2425
killed: boolean
@@ -79,6 +80,25 @@ export async function spawnAgentProcess(opts: SpawnAgentOpts): Promise<SpawnAgen
7980
stdio: ['pipe', 'pipe', 'pipe'],
8081
windowsHide: true,
8182
})
83+
if (process.platform === 'win32') {
84+
const killParent = cp.kill.bind(cp)
85+
let killRequested = false
86+
cp.kill = (signal) => {
87+
if (!cp.pid || cp.exitCode !== null || cp.signalCode !== null) return false
88+
if (killRequested) return true
89+
killRequested = true
90+
// npm launchers and agent subprocesses outlive a parent-only kill.
91+
// Target this exact live owned PID, never a provider name or all Node processes.
92+
execFile(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'taskkill.exe'),
93+
['/PID', String(cp.pid), '/T', '/F'], { windowsHide: true }, error => {
94+
if (error && cp.exitCode === null && cp.signalCode === null) {
95+
killRequested = false
96+
killParent(signal)
97+
}
98+
})
99+
return true
100+
}
101+
}
82102
// child_process satisfies the AgentProc subset structurally; the cast keeps
83103
// the bridges on a single type regardless of transport.
84104
return { proc: cp as unknown as AgentProc, dir: opts.cwd, remote: false }

‎src/main/agents/bridge-service.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createPiBridge } from './pi-bridge'
2+
import { stopRuntime } from './stop-runtime'
23
import { createOpencodeBridge } from './opencode-bridge'
34
import { createCodexBridge } from './codex-bridge'
45
import { createClaudeBridge } from './claude-bridge'
@@ -423,8 +424,8 @@ export class AgentBridgeService {
423424
const entry = this.bridges.get(bridgeId)
424425
this.clearQueuedPromptsForBridge(bridgeId)
425426
this.releaseConversationPrompt(bridgeId)
426-
if (entry) await entry.bridge.stop().catch(() => {})
427-
this.bridges.delete(bridgeId)
427+
if (entry) await stopRuntime(entry.bridge).catch(() => {})
428+
if (this.bridges.get(bridgeId) === entry) this.bridges.delete(bridgeId)
428429
return { ok: true }
429430
}
430431

‎src/main/agents/bridge-types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ export type BridgeEvent =
9898
| { type: 'session_id'; bridgeId: string; sessionId: string; resumed: boolean }
9999
| { type: 'turn_start'; bridgeId: string; turnId: string }
100100
| { type: 'text_delta'; bridgeId: string; turnId: string; delta: string }
101+
| { type: 'thinking_snapshot'; bridgeId: string; turnId: string; itemId: string; text: string; completed: boolean }
101102
| { type: 'thinking_delta'; bridgeId: string; turnId: string; delta: string }
102103
// Non-streaming history replay from providers that send transcript chunks on resume.
103104
| { type: 'history_user'; bridgeId: string; text: string }

0 commit comments

Comments
 (0)