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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions electron/ipc/pty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,30 @@ describe('spawnAgent session reattach', () => {
).not.toThrow();
expect(mockPtySpawn).toHaveBeenCalledTimes(1);
});

it('replaces an existing same-id PTY when attachExisting is explicitly false', () => {
const win = createMockWindow();
const agentId = 'agent-replace';
const args = buildSpawnArgs({
agentId,
command: 'claude',
args: [],
dockerMode: false,
onOutput: { __CHANNEL_ID__: 'channel-1' },
});

spawnAgent(win, args);
const oldProc = mockPtySpawn.mock.results[0].value as ReturnType<typeof mockPtySpawn>;

spawnAgent(win, {
...args,
attachExisting: false,
onOutput: { __CHANNEL_ID__: 'channel-2' },
});

expect(oldProc.kill).toHaveBeenCalled();
expect(mockPtySpawn).toHaveBeenCalledTimes(2);
});
});

describe('validateCommand', () => {
Expand Down
7 changes: 3 additions & 4 deletions electron/mcp/coordinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,9 @@ export class Coordinator {
}
});

// Re-subscribe our output callback when the renderer respawns a managed agent.
// TerminalView kills the existing PTY (clearing all subscribers) then spawns a
// new one with the same agentId. Without this, our outputCb is lost and we
// can never detect idle for that sub-task.
// Re-subscribe our output callback when the renderer reattaches to, or explicitly
// replaces, a managed agent. Without this, our outputCb is lost and we can never
// detect idle for that sub-task.
onPtyEvent('spawn', (agentId) => {
const outputCb = this.subscribers.get(agentId);
if (!outputCb) return; // not a coordinated agent, or initial spawn (not yet subscribed)
Expand Down
2 changes: 1 addition & 1 deletion src/components/TaskAITerminal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -607,7 +607,7 @@ function AgentTerminalPane(props: {
)
}
attachExisting={a().attachExisting}
preserveOnWindowUnload
preserveSessionOnCleanup
onExit={(code) => markAgentExited(a().id, code)}
onData={(data) => markAgentOutput(a().id, data, props.task.id)}
onFileLink={props.onFileLink}
Expand Down
10 changes: 5 additions & 5 deletions src/components/TerminalView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ interface TerminalViewProps {
dockerImage?: string;
spawnDelayMs?: number;
attachExisting?: boolean;
preserveOnWindowUnload?: boolean;
preserveSessionOnCleanup?: boolean;
dockerMountWorktreeParent?: boolean;
onExit?: (exitInfo: {
exit_code: number | null;
Expand Down Expand Up @@ -127,8 +127,8 @@ export function TerminalView(props: TerminalViewProps) {
const taskId = props.taskId;
const agentId = props.agentId;
const initialFontSize = props.fontSize ?? 13;
const attachExisting = props.attachExisting;
const preserveOnWindowUnload = props.preserveOnWindowUnload === true;
const attachExisting = props.attachExisting ?? true;
const preserveSessionOnCleanup = props.preserveSessionOnCleanup === true;

term = new Terminal({
cursorBlink: true,
Expand Down Expand Up @@ -702,7 +702,7 @@ export function TerminalView(props: TerminalViewProps) {
}

onCleanup(() => {
const preserveSession = windowUnloading && preserveOnWindowUnload;
const preserveSession = preserveSessionOnCleanup;
if (!windowUnloading || preserveSession) {
flushPendingInput();
flushPendingResize();
Expand All @@ -715,7 +715,7 @@ export function TerminalView(props: TerminalViewProps) {
webglAddon?.dispose();
webglAddon = undefined;
unregisterTerminal(agentId);
if (preserveSession && ptyPaused) {
if (ptyPaused) {
fireAndForget(IPC.ResumeAgent, { agentId });
ptyPaused = false;
}
Expand Down
136 changes: 136 additions & 0 deletions src/store/agents.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

const { mockSetStore, mockMarkAgentSpawned } = vi.hoisted(() => ({
mockSetStore: vi.fn(),
mockMarkAgentSpawned: vi.fn(),
}));

let mockAgents: Record<string, AgentLike> = {};

interface AgentLike {
id: string;
taskId: string;
def: AgentDefLike;
resumed: boolean;
status: 'running' | 'exited';
exitCode: number | null;
signal: string | null;
lastOutput: string[];
generation: number;
spawnDelayMs?: number;
attachExisting?: boolean;
}

interface AgentDefLike {
id: string;
name: string;
command: string;
args: string[];
resume_args: string[];
skip_permissions_args: string[];
description: string;
}

function applySetStore(...args: unknown[]): void {
if (args.length === 1 && typeof args[0] === 'function') {
(args[0] as (s: { agents: Record<string, AgentLike> }) => void)({ agents: mockAgents });
}
}

vi.mock('./core', () => ({
store: new Proxy({} as Record<string, unknown>, {
get(_target, prop) {
if (prop === 'agents') return mockAgents;
return undefined;
},
}),
setStore: mockSetStore,
}));

vi.mock('./taskStatus', () => ({
markAgentSpawned: mockMarkAgentSpawned,
refreshTaskStatus: vi.fn(),
clearAgentActivity: vi.fn(),
}));

vi.mock('./persistence', () => ({ saveState: vi.fn() }));
vi.mock('../lib/ipc', () => ({ invoke: vi.fn() }));

import { restartAgent, switchAgent } from './agents';

const codexDef: AgentDefLike = {
id: 'codex',
name: 'Codex',
command: 'codex',
args: [],
resume_args: ['resume', '--last'],
skip_permissions_args: [],
description: '',
};

function exitedAgent(overrides: Partial<AgentLike> = {}): AgentLike {
return {
id: 'agent-1',
taskId: 'task-1',
def: codexDef,
resumed: false,
status: 'exited',
exitCode: 1,
signal: '1',
lastOutput: ['interrupted'],
generation: 2,
spawnDelayMs: 500,
attachExisting: true,
...overrides,
};
}

beforeEach(() => {
vi.clearAllMocks();
mockSetStore.mockImplementation((...args: unknown[]) => applySetStore(...args));
mockAgents = { 'agent-1': exitedAgent() };
});

describe('restartAgent', () => {
it('marks the next terminal mount as an explicit process replacement', () => {
restartAgent('agent-1', true);

expect(mockAgents['agent-1']).toMatchObject({
status: 'running',
exitCode: null,
signal: null,
lastOutput: [],
resumed: true,
generation: 3,
attachExisting: false,
});
expect(mockAgents['agent-1'].spawnDelayMs).toBeUndefined();
expect(mockMarkAgentSpawned).toHaveBeenCalledWith('agent-1');
});
});

describe('switchAgent', () => {
it('marks the next terminal mount as an explicit process replacement', () => {
const claudeDef: AgentDefLike = {
...codexDef,
id: 'claude',
name: 'Claude',
command: 'claude',
};

switchAgent('agent-1', claudeDef);

expect(mockAgents['agent-1']).toMatchObject({
def: claudeDef,
status: 'running',
exitCode: null,
signal: null,
lastOutput: [],
resumed: false,
generation: 3,
attachExisting: false,
});
expect(mockAgents['agent-1'].spawnDelayMs).toBeUndefined();
expect(mockMarkAgentSpawned).toHaveBeenCalledWith('agent-1');
});
});
4 changes: 2 additions & 2 deletions src/store/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export function restartAgent(agentId: string, useResumeArgs: boolean): void {
s.agents[agentId].lastOutput = [];
s.agents[agentId].resumed = useResumeArgs;
s.agents[agentId].spawnDelayMs = undefined;
s.agents[agentId].attachExisting = undefined;
s.agents[agentId].attachExisting = false;
s.agents[agentId].generation += 1;
}
}),
Expand All @@ -132,7 +132,7 @@ export function switchAgent(agentId: string, newDef: AgentDef): void {
s.agents[agentId].lastOutput = [];
s.agents[agentId].resumed = false;
s.agents[agentId].spawnDelayMs = undefined;
s.agents[agentId].attachExisting = undefined;
s.agents[agentId].attachExisting = false;
s.agents[agentId].generation += 1;
}
}),
Expand Down
Loading