Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Terminal-command sign-ins and auto-retry when the sign-in terminal closes (PRD-8655, PRD-8050) (#4931)

Abraham57a8660c36ba
diff --git a/.changeset/prd-8655-8050-terminal-sign-in-recovery.md b/.changeset/prd-8655-8050-terminal-sign-in-recovery.md
new file mode 100644
index 000000000..2d7420066
--- /dev/null
+++ b/.changeset/prd-8655-8050-terminal-sign-in-recovery.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+An in-app agent that signs in through a terminal command now gets an "Open terminal to sign in" button that runs it, and closing a sign-in terminal's tab or shell retries the chat and re-sends the message the sign-in held back, as does "Already signed in? Retry".
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index 332fd43e8..73749548f 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -140,6 +140,8 @@ To apply it sooner, stop that server yourself. [`ok stop`](/docs/reference/cli#m
Retrying a conversation that failed to start re-resolves that conversation's own agent right away and leaves every other conversation on the adapter it already has. Custom agent commands keep their existing behavior.
+When an in-app agent needs you to sign in, the chat says so and offers what the agent supports: **Sign in** when the agent signs you in itself, and **Open terminal to sign in** (desktop app) when the agent runs its login as a terminal command or when its own CLI is installed. That terminal belongs to the chat that opened it for as long as this window stays open: when you close its tab or its shell exits, the chat retries on its own, and if the agent comes back ready, the message the sign-in held back is sent again. **Already signed in? Retry** does the same by hand, so a sign-in completed elsewhere is one press away. The terminal is never closed for you, so a failed login keeps its output on screen.
+
When a catalog-managed agent that OpenKnowledge launches through npx fails because npm reports that the entry in its npx cache is missing its `package.json`, OpenKnowledge deletes that one `_npx/<hash>` directory from npm's cache and relaunches the adapter once before reporting a failure. Custom agent commands and uv-managed adapters are never retried this way. Every launch that does fail, whatever its kind, is recorded with the last lines the adapter printed in [`.ok/local/acp-launch-failures.log`](../reference/what-open-knowledge-writes.mdx#while-a-project-is-open), which bug reports include.
A startup error ending with "Try again after an allowed release becomes available." means the requested adapter has no eligible release under that policy. Retry after one becomes eligible; OpenKnowledge does not disable your cooldown. Acquisition contacts your configured package registry or Python index; see [network requests](../reference/what-open-knowledge-writes.mdx#what-leaves-your-machine).
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index 18f3d5475..1527406f5 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -209,7 +209,14 @@ vi.doMock('./SessionsHost', () => ({
reserveRightRevealTabGutter?: boolean;
visible?: boolean;
onVisibleChange?: (visible: boolean) => void;
- launch?: { nonce: number; stagePaste?: string } | null;
+ launch?: {
+ nonce: number;
+ stagePaste?: string;
+ cli?: string | null;
+ command?: { executable: string; args: readonly string[] };
+ label?: string;
+ signInThreadId?: string;
+ } | null;
threadLaunch?: { nonce: number; agentId?: string; prompt?: string | null } | null;
}) => {
return (
@@ -222,6 +229,10 @@ vi.doMock('./SessionsHost', () => ({
data-visible={String(visible)}
data-launch-nonce={launch ? String(launch.nonce) : 'none'}
data-launch-stage={launch?.stagePaste ?? 'none'}
+ data-launch-cli={launch?.cli ?? 'none'}
+ data-launch-command={launch?.command ? JSON.stringify(launch.command) : 'none'}
+ data-launch-label={launch?.label ?? 'none'}
+ data-launch-sign-in={launch?.signInThreadId ?? 'none'}
data-thread-launch-nonce={threadLaunch ? String(threadLaunch.nonce) : 'none'}
data-thread-launch-agent={threadLaunch?.agentId ?? 'none'}
data-thread-launch-image-parts={String(collectImageParts(threadLaunch).length)}
@@ -651,6 +662,38 @@ describe('EditorPane session-panel wiring', () => {
expect(dock().getAttribute('data-launch-nonce')).toBe('none');
});
+ test('desktop: a command launch and a sign-in CLI launch reach the dock with their command, label and chat', async () => {
+ const desk = makeOkDesktopStub();
+ (window as { okDesktop?: unknown }).okDesktop = desk.stub;
+ const { requestTerminalCommandLaunch, requestTerminalLaunch } = await import(
+ './handoff/terminal-launch-events'
+ );
+ await renderEditorPane();
+ const dock = () => screen.getByTestId('terminal-dock');
+
+ act(() =>
+ requestTerminalCommandLaunch({
+ label: 'Log in with Auggie',
+ command: { executable: 'auggie', args: ['--acp', 'login'] },
+ signInThreadId: 'thread-9',
+ }),
+ );
+ expect(dock().getAttribute('data-visible')).toBe('true');
+ expect(dock().getAttribute('data-launch-nonce')).toBe('1');
+ expect(dock().getAttribute('data-launch-cli')).toBe('none');
+ expect(dock().getAttribute('data-launch-command')).toBe(
+ JSON.stringify({ executable: 'auggie', args: ['--acp', 'login'] }),
+ );
+ expect(dock().getAttribute('data-launch-label')).toBe('Log in with Auggie');
+ expect(dock().getAttribute('data-launch-sign-in')).toBe('thread-9');
+
+ act(() => requestTerminalLaunch('', 'claude', { signInThreadId: 'thread-9' }));
+ expect(dock().getAttribute('data-launch-nonce')).toBe('2');
+ expect(dock().getAttribute('data-launch-cli')).toBe('claude');
+ expect(dock().getAttribute('data-launch-command')).toBe('none');
+ expect(dock().getAttribute('data-launch-sign-in')).toBe('thread-9');
+ });
+
test('desktop: a distinct Open-in-terminal after a hide gets a fresh, monotonic nonce', async () => {
const desk = makeOkDesktopStub();
(window as { okDesktop?: unknown }).okDesktop = desk.stub;
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 46f8933be..b542f54b0 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -2,6 +2,7 @@ import type { HocuspocusProvider } from '@hocuspocus/provider';
import {
isEditableTextDocFile,
type TerminalCli,
+ type TerminalLaunchCommand,
type TerminalPlacement,
} from '@inkeep/open-knowledge-core';
import type { AttachmentPart } from '@inkeep/open-knowledge-core/acp/thread-protocol';
@@ -72,13 +73,27 @@ const SessionsHost = lazy(() =>
import('./SessionsHost').then((mod) => ({ default: mod.SessionsHost })),
);
-export interface TerminalLaunchIntent {
+export interface TerminalCliLaunchIntent {
readonly prompt: string | null;
readonly cli: TerminalCli;
readonly nonce: number;
readonly stagePaste?: string;
+ readonly command?: undefined;
+ readonly signInThreadId?: string;
}
+interface TerminalCommandLaunchIntent {
+ readonly prompt: null;
+ readonly cli: null;
+ readonly nonce: number;
+ readonly command: TerminalLaunchCommand;
+ readonly label: string;
+ readonly stagePaste?: undefined;
+ readonly signInThreadId?: string;
+}
+
+export type TerminalLaunchIntent = TerminalCliLaunchIntent | TerminalCommandLaunchIntent;
+
export interface ThreadLaunchIntent {
readonly agentSource: 'registry' | 'custom';
readonly agentId: string;
@@ -327,15 +342,30 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
}, []);
useEffect(() => {
- return subscribeToTerminalLaunchRequests((text, cli, { stage }) => {
+ return subscribeToTerminalLaunchRequests((request) => {
setTerminalVisible(true);
launchNonceRef.current += 1;
- setTerminalLaunch({
- prompt: stage ? null : text,
- cli,
- nonce: launchNonceRef.current,
- stagePaste: stage ? text : undefined,
- });
+ const nonce = launchNonceRef.current;
+ const signIn =
+ request.signInThreadId === undefined ? {} : { signInThreadId: request.signInThreadId };
+ setTerminalLaunch(
+ request.kind === 'command'
+ ? {
+ prompt: null,
+ cli: null,
+ command: request.command,
+ label: request.label,
+ nonce,
+ ...signIn,
+ }
+ : {
+ prompt: request.stage ? null : request.prompt,
+ cli: request.cli,
+ nonce,
+ stagePaste: request.stage ? request.prompt : undefined,
+ ...signIn,
+ },
+ );
});
}, []);
diff --git a/packages/app/src/components/NoteWindowMainActionReceiver.dom.test.ts b/packages/app/src/components/NoteWindowMainActionReceiver.dom.test.ts
index a9f9c6dda..fd07d78cd 100644
--- a/packages/app/src/components/NoteWindowMainActionReceiver.dom.test.ts
+++ b/packages/app/src/components/NoteWindowMainActionReceiver.dom.test.ts
@@ -17,10 +17,11 @@ describe('dispatchNoteWindowMainAction', () => {
const unsubscribe = [
subscribeToActiveTerminalInput((detail) => received.push(detail), target),
subscribeToAgentThreadLaunchRequests((detail) => received.push(detail), target),
- subscribeToTerminalLaunchRequests(
- (prompt, cli, options) => received.push({ prompt, cli, ...options }),
- target,
- ),
+ subscribeToTerminalLaunchRequests((request) => {
+ if (request.kind === 'cli') {
+ received.push({ prompt: request.prompt, cli: request.cli, stage: request.stage });
+ }
+ }, target),
];
dispatchNoteWindowMainAction(
diff --git a/packages/app/src/components/SessionsHost.agents.dom.test.tsx b/packages/app/src/components/SessionsHost.agents.dom.test.tsx
index 96d6a6659..92dc3333d 100644
--- a/packages/app/src/components/SessionsHost.agents.dom.test.tsx
+++ b/packages/app/src/components/SessionsHost.agents.dom.test.tsx
@@ -2256,9 +2256,11 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
test('an Ask AI instruction RUNS on a new thread (never a CLI)', async () => {
mockRegisteredAgent = { source: 'registry', id: 'acme-agent', name: 'Acme' };
const launches: unknown[] = [];
- const stopLaunch = subscribeToTerminalLaunchRequests((prompt, cli, opts) =>
- launches.push({ prompt, cli, ...opts }),
- );
+ const stopLaunch = subscribeToTerminalLaunchRequests((request) => {
+ if (request.kind === 'cli') {
+ launches.push({ prompt: request.prompt, cli: request.cli, stage: request.stage });
+ }
+ });
render(<Harness />);
await screen.findByTestId('terminal-new-chat');
@@ -2467,9 +2469,11 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {
{ submit: false, label: 'a selection send' },
])('with NO agent set up, $label is left to the terminal dock', async ({ submit }) => {
const launches: unknown[] = [];
- const stopLaunch = subscribeToTerminalLaunchRequests((prompt, cli, opts) =>
- launches.push({ prompt, cli, ...opts }),
- );
+ const stopLaunch = subscribeToTerminalLaunchRequests((request) => {
+ if (request.kind === 'cli') {
+ launches.push({ prompt: request.prompt, cli: request.cli, stage: request.stage });
+ }
+ });
const onVisibleChange = vi.fn((_v: boolean) => {});
render(<Harness bridge={makeTerminalBridge()} onVisibleChange={onVisibleChange} />);
await screen.findByTestId('terminal-new-chat');
diff --git a/packages/app/src/components/SessionsHost.terminal-rehydration.dom.test.tsx b/packages/app/src/components/SessionsHost.terminal-rehydration.dom.test.tsx
index a565cd45c..74de243c2 100644
--- a/packages/app/src/components/SessionsHost.terminal-rehydration.dom.test.tsx
+++ b/packages/app/src/components/SessionsHost.terminal-rehydration.dom.test.tsx
@@ -1,10 +1,12 @@
// @vitest-environment jsdom
-import { act, cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { useEffect, useState } from 'react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';
+import type { TerminalLaunchIntent } from './EditorPane';
+import { subscribeToSignInTerminalExits } from './handoff/sign-in-terminal-events';
import {
dispatchReorderChord,
dispatchTabChord,
@@ -51,17 +53,25 @@ vi.doMock('@tanstack/react-query', () => ({
useQuery: () => ({ data: undefined, isLoading: false, isError: false }),
}));
+type GateExit = (info: { exitCode: number; signal: number | null }) => void;
+const gateExits: Array<GateExit | undefined> = [];
+
vi.doMock('./TerminalGate', () => ({
TerminalGate: ({
adoptPtyId,
onPtyId,
+ onExit,
}: {
adoptPtyId?: string | null;
onPtyId?: (ptyId: string | null) => void;
+ onExit?: GateExit;
}) => {
useEffect(() => {
onPtyId?.(adoptPtyId ?? 'pty-fresh');
}, [adoptPtyId, onPtyId]);
+ useEffect(() => {
+ gateExits.push(onExit);
+ }, [onExit]);
return <div data-testid="terminal-gate" data-adopt={adoptPtyId ?? ''} />;
},
}));
@@ -89,11 +99,13 @@ function Harness({
restoreNonce = 0,
startVisible = false,
bumpRestoreAfterMount = false,
+ launch = null,
}: {
bridge: OkDesktopBridge;
restoreNonce?: number;
startVisible?: boolean;
bumpRestoreAfterMount?: boolean;
+ launch?: TerminalLaunchIntent | null;
}) {
const [container, setContainer] = useState<HTMLDivElement | null>(null);
const [visible, setVisible] = useState(startVisible);
@@ -115,6 +127,7 @@ function Harness({
terminalCapable
visible={visible}
terminalRestoreRevealNonce={nonce}
+ launch={launch}
onVisibleChange={setVisible}
installedClis={{}}
container={container}
@@ -134,12 +147,120 @@ async function revealAndSettle(ms: number) {
describe('SessionsHost — terminal dock rehydration must always settle', () => {
beforeEach(() => {
vi.useFakeTimers();
+ gateExits.length = 0;
});
afterEach(() => {
cleanup();
vi.useRealTimers();
});
+ test('a sign-in terminal closing tells the chat that opened it', async () => {
+ const seen = vi.fn();
+ const stop = subscribeToSignInTerminalExits(seen);
+ try {
+ render(
+ <Harness
+ bridge={makeBridge({})}
+ launch={{
+ prompt: null,
+ cli: null,
+ command: { executable: 'auggie', args: ['--acp', 'login'] },
+ label: 'Log in with Auggie',
+ nonce: 1,
+ signInThreadId: 't1',
+ }}
+ />,
+ );
+ await revealAndSettle(1_000);
+ const exit = gateExits.filter((handler) => handler !== undefined).at(-1);
+ expect(exit).toBeDefined();
+ act(() => exit?.({ exitCode: 0, signal: null }));
+ expect(seen).toHaveBeenCalledWith('t1');
+ } finally {
+ stop();
+ }
+ });
+
+ test('closing a sign-in tab through its close control tells the chat exactly once', async () => {
+ const seen = vi.fn();
+ const stop = subscribeToSignInTerminalExits(seen);
+ try {
+ render(
+ <Harness
+ bridge={makeBridge({})}
+ launch={{
+ prompt: null,
+ cli: null,
+ command: { executable: 'auggie', args: ['--acp', 'login'] },
+ label: 'Log in with Auggie',
+ nonce: 1,
+ signInThreadId: 't1',
+ }}
+ />,
+ );
+ await revealAndSettle(1_000);
+ const exit = gateExits.filter((handler) => handler !== undefined).at(-1);
+ expect(exit).toBeDefined();
+ const closeButtons = screen.getAllByRole('button', { name: /^Close / });
+ act(() => {
+ fireEvent.click(closeButtons[closeButtons.length - 1] as HTMLElement);
+ });
+ await revealAndSettle(10);
+ expect(seen).toHaveBeenCalledTimes(1);
+ expect(seen).toHaveBeenCalledWith('t1');
+ act(() => exit?.({ exitCode: 0, signal: null }));
+ expect(seen).toHaveBeenCalledTimes(1);
+ } finally {
+ stop();
+ }
+ });
+
+ test('a sign-in shell that exits before its tab closes still tells the chat once', async () => {
+ const seen = vi.fn();
+ const stop = subscribeToSignInTerminalExits(seen);
+ try {
+ render(
+ <Harness
+ bridge={makeBridge({})}
+ launch={{
+ prompt: null,
+ cli: null,
+ command: { executable: 'auggie', args: ['--acp', 'login'] },
+ label: 'Log in with Auggie',
+ nonce: 1,
+ signInThreadId: 't1',
+ }}
+ />,
+ );
+ await revealAndSettle(1_000);
+ const exit = gateExits.filter((handler) => handler !== undefined).at(-1);
+ act(() => exit?.({ exitCode: 0, signal: null }));
+ expect(seen).toHaveBeenCalledTimes(1);
+ const closeButtons = screen.getAllByRole('button', { name: /^Close / });
+ act(() => {
+ fireEvent.click(closeButtons[closeButtons.length - 1] as HTMLElement);
+ });
+ await revealAndSettle(10);
+ expect(seen).toHaveBeenCalledTimes(1);
+ } finally {
+ stop();
+ }
+ });
+
+ test('an ordinary terminal closing tells no chat', async () => {
+ const seen = vi.fn();
+ const stop = subscribeToSignInTerminalExits(seen);
+ try {
+ render(<Harness bridge={makeBridge({})} launch={{ prompt: null, cli: 'codex', nonce: 1 }} />);
+ await revealAndSettle(1_000);
+ expect(gateExits.length).toBeGreaterThan(0);
+ expect(gateExits.every((handler) => handler === undefined)).toBe(true);
+ expect(seen).not.toHaveBeenCalled();
+ } finally {
+ stop();
+ }
+ });
+
test('a getDockState() that never settles still seeds a terminal on reveal', async () => {
render(<Harness bridge={makeBridge({ getDockState: NEVER })} />);
await revealAndSettle(10_000);
diff --git a/packages/app/src/components/SessionsHost.tsx b/packages/app/src/components/SessionsHost.tsx
index a700aad50..ba418bee7 100644
--- a/packages/app/src/components/SessionsHost.tsx
+++ b/packages/app/src/components/SessionsHost.tsx
@@ -106,6 +106,7 @@ const ThreadView = lazy(() =>
import { sendQueuedCommentsInThread, subscribeSendToOpenChat } from '@/comments/open-chat-send';
import { subscribeToPreferredSessionRequests } from './handoff/preferred-session-events';
+import { notifySignInTerminalExited } from './handoff/sign-in-terminal-events';
import type { TerminalCommandId } from './handoff/terminal-command-events';
import {
type ActiveTerminalInputDetail,
@@ -1078,6 +1079,7 @@ export function SessionsHost({
if (index === -1) return;
noteUserArrangement();
const session = current[index];
+ notifySignInExitOnce(session);
const isLast = current.length === 1;
pendingActiveKeyRef.current = null;
if (id === activeSessionIdRef.current) {
@@ -1097,6 +1099,14 @@ export function SessionsHost({
}
}
const closeActiveRef = useRef(() => {});
+ const signInExitNotifiedRef = useRef(new Set<string>());
+ function notifySignInExitOnce(session: (typeof sessionsRef.current)[number] | undefined) {
+ if (session == null || session.kind !== 'terminal') return;
+ const threadId = session.launch?.signInThreadId;
+ if (threadId === undefined || signInExitNotifiedRef.current.has(session.id)) return;
+ signInExitNotifiedRef.current.add(session.id);
+ notifySignInTerminalExited(threadId);
+ }
const [switchingThreads, setSwitchingThreads] = useState<ReadonlySet<string>>(() => new Set());
useEffect(() => {
@@ -1926,6 +1936,11 @@ export function SessionsHost({
commandId={session.commandId}
adoptPtyId={session.adoptPtyId}
onPtyId={(ptyId) => setSessionPtyId(session.id, ptyId)}
+ onExit={
+ session.launch?.signInThreadId === undefined
+ ? undefined
+ : () => notifySignInExitOnce(session)
+ }
onTitleChange={(title) => setSessionTitle(session.id, title)}
onClose={() => closeSession(session.id)}
/>
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsx
index ac4099ad7..b621c3167 100644
--- a/packages/app/src/components/TerminalDock.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.dom.test.tsx
@@ -918,9 +918,11 @@ describe('TerminalDock multi-session', () => {
expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
const launchRequests: Array<{ text: string; cli: string; stage: boolean }> = [];
- const stopLaunch = subscribeToTerminalLaunchRequests((text, cli, opts) =>
- launchRequests.push({ text, cli, stage: opts.stage }),
- );
+ const stopLaunch = subscribeToTerminalLaunchRequests((request) => {
+ if (request.kind === 'cli') {
+ launchRequests.push({ text: request.prompt, cli: request.cli, stage: request.stage });
+ }
+ });
await act(async () => {
requestActiveTerminalInput('explain this');
});
diff --git a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
index ee54ff3ec..be477d815 100644
--- a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
@@ -295,9 +295,11 @@ describe('issue #351 — the terminal dock rehydrates surviving sessions after a
test('an Ask-AI selection does NOT raw-write into a reload survivor (unknown shell type)', async () => {
const { bridge, create, input } = makeSurvivingMainBridge([{ ptyId: 'pty-1' }]);
const launchRequests: Array<{ text: string; cli: string; stage: boolean }> = [];
- const stopLaunch = subscribeToTerminalLaunchRequests((text, cli, opts) =>
- launchRequests.push({ text, cli, stage: opts.stage }),
- );
+ const stopLaunch = subscribeToTerminalLaunchRequests((request) => {
+ if (request.kind === 'cli') {
+ launchRequests.push({ text: request.prompt, cli: request.cli, stage: request.stage });
+ }
+ });
render(dockUi(bridge, true));
await waitFor(() => expect(screen.getAllByTestId('terminal-session')).toHaveLength(1), {
diff --git a/packages/app/src/components/TerminalGate.tsx b/packages/app/src/components/TerminalGate.tsx
index 7a120fe72..27ff66650 100644
--- a/packages/app/src/components/TerminalGate.tsx
+++ b/packages/app/src/components/TerminalGate.tsx
@@ -17,6 +17,7 @@ const TerminalPanel = lazyWithPreload(() =>
interface TerminalGateProps {
readonly bridge: OkDesktopBridge;
readonly onClose?: () => void;
+ readonly onExit?: (info: { readonly exitCode: number; readonly signal: number | null }) => void;
readonly onTitleChange?: (title: string) => void;
readonly launch?: TerminalLaunchIntent | null;
readonly commandId?: TerminalCommandId | null;
@@ -27,6 +28,7 @@ interface TerminalGateProps {
export function TerminalGate({
bridge,
onClose,
+ onExit,
onTitleChange,
launch = null,
commandId = null,
@@ -83,6 +85,7 @@ export function TerminalGate({
bridge={bridge}
className="h-full"
onClose={onClose}
+ onExit={onExit}
onTitleChange={onTitleChange}
launch={launch}
commandId={commandId}
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index a760f8481..be7232418 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -233,6 +233,29 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
expect(launchInputWrites(terminal.input)).toEqual([]);
});
+ test('a command launch hands the structured command to create without any CLI preflight', async () => {
+ const { bridge, terminal } = makeBridge(WIRED);
+ const command: TerminalLaunchCommand = {
+ executable: '/rt/bin/npx',
+ args: ['-y', '@augmentcode/[email protected]', '--acp', 'login'],
+ env: { AUGGIE_LOGIN_FLOW: 'terminal' },
+ pathPrepend: ['/rt/bin'],
+ };
+ render(
+ <TerminalPanel
+ bridge={bridge}
+ launch={{ prompt: null, cli: null, command, label: 'Log in with Auggie', nonce: 1 }}
+ />,
+ );
+
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+ expect(bakedLaunch(terminal.create)).toEqual(command);
+ expect(terminal.create.mock.calls[0]?.[0]).toMatchObject({ launchCli: undefined });
+ expect(terminal.claudePreflight).not.toHaveBeenCalled();
+ expect(terminal.cliPreflight).not.toHaveBeenCalled();
+ expect(launchInputWrites(terminal.input)).toEqual([]);
+ });
+
test('Windows keeps the CLI structured and bracketed-pastes the prompt after readiness', async () => {
const { bridge, terminal, pushData } = makeBridge(WIRED, ON_PATH, 'win32');
const prompt = 'review {"quoted":"JSON"}; & calc';
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index 016285936..c92d8b4ae 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -28,7 +28,7 @@ import type { OkDesktopBridge, OkPtyNotice } from '@/lib/desktop-bridge-types';
import { cn } from '@/lib/utils';
import { getPageListCache } from '../editor/page-list-cache';
import { filePathToDocName, hashFromDocName, hashFromFolderPath } from '../lib/doc-hash';
-import type { TerminalLaunchIntent } from './EditorPane';
+import type { TerminalCliLaunchIntent, TerminalLaunchIntent } from './EditorPane';
import { filesFromExternalDrop, isExternalFileDrag } from './file-tree-adapter';
import {
type TerminalCommandId,
@@ -609,7 +609,7 @@ function TerminalSession({
};
const resolveLaunchCommand = async (
- intent: TerminalLaunchIntent,
+ intent: TerminalCliLaunchIntent,
): Promise<string | TerminalLaunchCommand | undefined> => {
const buildLaunch = (opts: Parameters<typeof buildCliLaunchArgString>[2]) =>
bridge.platform === 'win32'
@@ -705,9 +705,13 @@ function TerminalSession({
let launchCommand: string | TerminalLaunchCommand | undefined;
let launchCli: TerminalCli | undefined;
if (launch !== null && adoptPtyId === null) {
- launchCli = launch.cli;
- launchCommand = await resolveLaunchCommand(launch);
- if (cancelled) return;
+ if (launch.cli === null) {
+ launchCommand = launch.command;
+ } else {
+ launchCli = launch.cli;
+ launchCommand = await resolveLaunchCommand(launch);
+ if (cancelled) return;
+ }
} else if (commandId !== null && adoptPtyId === null) {
launchCommand =
bridge.platform === 'win32'
@@ -760,12 +764,13 @@ function TerminalSession({
markInteractive();
const staged = launch?.stagePaste;
+ const cliLaunch = launch !== null && launch.cli !== null ? launch : null;
const injectionBytes =
- launch != null && launchCommand !== undefined && launch.prompt != null
- ? buildStartupInjectionBytes(launch.cli, launch.prompt, bridge.platform)
+ cliLaunch !== null && launchCommand !== undefined && cliLaunch.prompt != null
+ ? buildStartupInjectionBytes(cliLaunch.cli, cliLaunch.prompt, bridge.platform)
: null;
- if (injectionBytes != null && launch != null) {
- const cfg = startupInjectionFor(launch.cli, bridge.platform);
+ if (injectionBytes != null && cliLaunch !== null) {
+ const cfg = startupInjectionFor(cliLaunch.cli, bridge.platform);
const settleMs = cfg?.settleMs ?? STAGE_PASTE_SETTLE_MS;
const marker = cfg?.readyMarker;
const bytes = injectionBytes;
diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsx
index ceb5c347d..e2159319e 100644
--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx
+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx
@@ -1,4 +1,8 @@
-import type { ThreadEvent, ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import type {
+ ThreadAuthTerminalLaunch,
+ ThreadEvent,
+ ThreadInfo,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { i18n } from '@lingui/core';
import {
act,
@@ -12,6 +16,7 @@ import {
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, describe, expect, test, vi } from 'vitest';
+import { notifySignInTerminalExited } from '@/components/handoff/sign-in-terminal-events';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
import { TooltipProvider } from '@/components/ui/tooltip';
import { MAX_TOTAL_ATTACHMENT_BYTES } from '@/lib/acp/image-attachment';
@@ -53,7 +58,19 @@ const sendQueuedNow = vi.fn((_threadId: string, _id: string) => {});
const setChatGrant = vi.fn((_threadId: string, _grant: string, _enabled: boolean) => {});
const toastError = vi.fn((_message: string) => {});
const cancel = vi.fn((_threadId: string) => {});
-const retryThread = vi.fn(async (_threadId: string) => {});
+const retryThread = vi.fn(
+ async (_threadId: string): Promise<ThreadInfo> => makeInfo({ status: 'ready' }),
+);
+const FIXTURE_TERMINAL_LAUNCH: ThreadAuthTerminalLaunch = {
+ executable: '/rt/bin/npx',
+ args: ['-y', '@augmentcode/[email protected]', '--acp', 'login'],
+ env: { AUGGIE_LOGIN_FLOW: 'terminal' },
+ pathPrepend: ['/rt/bin'],
+};
+const terminalAuthLaunch = vi.fn(
+ async (_threadId: string, _methodId: string): Promise<ThreadAuthTerminalLaunch> =>
+ FIXTURE_TERMINAL_LAUNCH,
+);
const createThread = vi.fn(
async (_params: unknown): Promise<unknown> => ({
threadId: 'thread-2',
@@ -84,6 +101,7 @@ vi.doMock('@/lib/acp/thread-client', () => ({
createThread,
resumeThread,
retryThread,
+ terminalAuthLaunch,
authenticateThread,
getThread: () => null,
subscribe: () => () => {},
@@ -508,6 +526,7 @@ afterEach(() => {
toastError.mockClear();
cancel.mockClear();
retryThread.mockClear();
+ terminalAuthLaunch.mockClear();
createThread.mockClear();
resumeThread.mockClear();
resetStagedThreadDrafts();
@@ -4794,6 +4813,257 @@ describe('ThreadView auth-required dead ends', () => {
}
});
+ test('an agent whose sign-in is a terminal command runs that command in the terminal', async () => {
+ const launches: unknown[] = [];
+ const onLaunch = (event: Event) => launches.push((event as CustomEvent).detail);
+ window.addEventListener('open-knowledge:terminal-launch', onLaunch);
+ Object.assign(window, {
+ okDesktop: {
+ config: { ptyAvailable: true },
+ terminal: { cliInstalledMap: () => Promise.resolve({}) },
+ },
+ });
+ try {
+ model = makeModel({
+ turnActive: false,
+ items: [
+ authNotice({
+ authMethods: [
+ {
+ id: 'auggie-login',
+ name: 'Log in with Auggie',
+ kind: 'terminal',
+ terminalLaunchAvailable: true,
+ },
+ ],
+ }),
+ ],
+ });
+ render(
+ <ThreadView
+ info={makeInfo({
+ archived: false,
+ status: 'auth_required',
+ agent: { id: 'auggie', name: 'Auggie', source: 'custom' },
+ })}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(offerButton().getAttribute('data-auth-offer-kind')).toBe('terminal-sign-in'),
+ );
+ expect(authSurface().textContent).toContain('Log in with Auggie');
+
+ await userEvent.click(offerButton());
+ await waitFor(() =>
+ expect(launches).toEqual([
+ {
+ kind: 'command',
+ label: 'Log in with Auggie',
+ command: FIXTURE_TERMINAL_LAUNCH,
+ signInThreadId: 'thread-1',
+ },
+ ]),
+ );
+ expect(terminalAuthLaunch).toHaveBeenCalledWith('thread-1', 'auggie-login');
+ expect(retryThread).not.toHaveBeenCalled();
+ } finally {
+ window.removeEventListener('open-knowledge:terminal-launch', onLaunch);
+ Reflect.deleteProperty(window, 'okDesktop');
+ }
+ });
+
+ test('a sign-in launch the server refuses becomes a toast, never a terminal', async () => {
+ const launches: unknown[] = [];
+ const onLaunch = (event: Event) => launches.push((event as CustomEvent).detail);
+ window.addEventListener('open-knowledge:terminal-launch', onLaunch);
+ Object.assign(window, {
+ okDesktop: {
+ config: { ptyAvailable: true },
+ terminal: { cliInstalledMap: () => Promise.resolve({}) },
+ },
+ });
+ terminalAuthLaunch.mockRejectedValueOnce(
+ new Error('this agent offers no terminal sign-in by that name'),
+ );
+ try {
+ model = makeModel({
+ turnActive: false,
+ items: [
+ authNotice({
+ authMethods: [
+ {
+ id: 'auggie-login',
+ name: 'Log in with Auggie',
+ kind: 'terminal',
+ terminalLaunchAvailable: true,
+ },
+ ],
+ }),
+ ],
+ });
+ render(
+ <ThreadView
+ info={makeInfo({
+ archived: false,
+ status: 'auth_required',
+ agent: { id: 'auggie', name: 'Auggie', source: 'custom' },
+ })}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(offerButton().getAttribute('data-auth-offer-kind')).toBe('terminal-sign-in'),
+ );
+ await userEvent.click(offerButton());
+ await waitFor(() =>
+ expect(toastError).toHaveBeenCalledWith(
+ 'Sign-in failed: this agent offers no terminal sign-in by that name',
+ ),
+ );
+ expect(launches).toEqual([]);
+ expect(retryThread).not.toHaveBeenCalled();
+ } finally {
+ window.removeEventListener('open-knowledge:terminal-launch', onLaunch);
+ Reflect.deleteProperty(window, 'okDesktop');
+ }
+ });
+
+ test('a harness CLI sign-in names the chat that opened the terminal', async () => {
+ const launches: unknown[] = [];
+ const onLaunch = (event: Event) => launches.push((event as CustomEvent).detail);
+ window.addEventListener('open-knowledge:terminal-launch', onLaunch);
+ Object.assign(window, {
+ okDesktop: {
+ config: { ptyAvailable: true },
+ terminal: { cliInstalledMap: () => Promise.resolve({ claude: true }) },
+ },
+ });
+ try {
+ model = makeModel({ turnActive: false, items: [] });
+ render(
+ <ThreadView
+ info={makeInfo({
+ archived: false,
+ status: 'auth_required',
+ agent: { id: 'claude-acp', name: 'Claude Agent', source: 'registry' },
+ })}
+ />,
+ );
+ await waitFor(() =>
+ expect(offerButton().getAttribute('data-auth-offer-kind')).toBe('terminal-sign-in'),
+ );
+ await userEvent.click(offerButton());
+ expect(launches).toEqual([
+ { kind: 'cli', prompt: '', cli: 'claude', stage: false, signInThreadId: 'thread-1' },
+ ]);
+ } finally {
+ window.removeEventListener('open-knowledge:terminal-launch', onLaunch);
+ Reflect.deleteProperty(window, 'okDesktop');
+ }
+ });
+
+ test('closing the sign-in terminal retries the chat and re-sends the message it held back', async () => {
+ retryThread.mockResolvedValueOnce(makeInfo({ status: 'ready' }));
+ const agent = { id: 'claude-acp', name: 'Claude Agent', source: 'registry' as const };
+ model = makeModel({
+ turnActive: false,
+ items: [
+ { kind: 'message', role: 'user', text: 'summarise the standup', messageId: 'u1' },
+ authNotice({ authMethods: undefined }),
+ ],
+ });
+ const view = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'auth_required', agent })} />,
+ );
+ await screen.findByTestId('agent-thread-auth-status');
+
+ act(() => {
+ notifySignInTerminalExited('thread-1');
+ });
+ await waitFor(() => expect(retryThread).toHaveBeenCalledWith('thread-1'));
+ await waitFor(() =>
+ expect(prompt).toHaveBeenCalledWith('thread-1', 'summarise the standup', undefined),
+ );
+
+ view.rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready', agent })} />);
+ expect(screen.queryByTestId('agent-thread-user-message')).toBeNull();
+ });
+
+ test('a sign-in terminal closing for another chat, or after recovery, retries nothing', async () => {
+ model = makeModel({
+ turnActive: false,
+ items: [
+ { kind: 'message', role: 'user', text: 'summarise the standup', messageId: 'u1' },
+ authNotice({ authMethods: undefined }),
+ ],
+ });
+ const view = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'auth_required' })} />,
+ );
+ await screen.findByTestId('agent-thread-auth-status');
+ act(() => {
+ notifySignInTerminalExited('thread-2');
+ });
+ expect(retryThread).not.toHaveBeenCalled();
+
+ view.rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+ act(() => {
+ notifySignInTerminalExited('thread-1');
+ });
+ expect(retryThread).not.toHaveBeenCalled();
+ expect(prompt).not.toHaveBeenCalled();
+ });
+
+ test('Already signed in? Retry re-sends the held message once the agent is ready', async () => {
+ retryThread.mockResolvedValueOnce(makeInfo({ status: 'ready' }));
+ model = makeModel({
+ turnActive: false,
+ items: [
+ { kind: 'message', role: 'user', text: 'summarise the standup', messageId: 'u1' },
+ authNotice({ authMethods: undefined }),
+ ],
+ });
+ render(<ThreadView info={makeInfo({ archived: false, status: 'auth_required' })} />);
+
+ await userEvent.click(within(authSurface()).getByTestId('agent-thread-retry'));
+ await waitFor(() =>
+ expect(prompt).toHaveBeenCalledWith('thread-1', 'summarise the standup', undefined),
+ );
+ });
+
+ test('a retry that leaves the agent signed out re-sends nothing', async () => {
+ retryThread.mockResolvedValueOnce(makeInfo({ status: 'auth_required' }));
+ model = makeModel({
+ turnActive: false,
+ items: [
+ { kind: 'message', role: 'user', text: 'summarise the standup', messageId: 'u1' },
+ authNotice({ authMethods: undefined }),
+ ],
+ });
+ render(<ThreadView info={makeInfo({ archived: false, status: 'auth_required' })} />);
+
+ await userEvent.click(within(authSurface()).getByTestId('agent-thread-retry'));
+ await waitFor(() => expect(retryThread).toHaveBeenCalledWith('thread-1'));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(prompt).not.toHaveBeenCalled();
+ });
+
+ test('a refused resume shows New chat once when the sign-in notice already offers it', () => {
+ model = makeModel({ turnActive: false, items: [authNotice({ authMethods: undefined })] });
+ render(<ThreadView info={makeInfo({ archived: true, resumable: false, status: 'exited' })} />);
+ expect(screen.queryByTestId('agent-thread-resume-failed')).toBeNull();
+ expect(screen.getAllByRole('button', { name: 'New chat with Claude' })).toHaveLength(1);
+ });
+
+ test('a refused resume without a sign-in notice keeps the banner as the way out', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ render(<ThreadView info={makeInfo({ archived: true, resumable: false, status: 'exited' })} />);
+ expect(screen.getByTestId('agent-thread-resume-failed')).toBeDefined();
+ });
+
test('a clickable sign-in method still wins over the terminal fallback', async () => {
Object.assign(window, {
okDesktop: {
diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsx
index 8aada9ecf..d84aa4292 100644
--- a/packages/app/src/components/acp/ThreadView.tsx
+++ b/packages/app/src/components/acp/ThreadView.tsx
@@ -5,6 +5,7 @@ import type {
AttachmentPart,
QueuedMessage,
SessionConfigOption,
+ ThreadAuthMethod,
ThreadFailureDetail,
ThreadInfo,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
@@ -74,7 +75,11 @@ import { ComposerContextChips } from '@/components/ComposerContextChips';
import { CopyButton } from '@/components/CopyButton';
import { isExternalFileDrag } from '@/components/file-tree-adapter';
import { focusComposerInputOnCardPointer } from '@/components/focus-composer-on-card-pointer';
-import { requestTerminalLaunch } from '@/components/handoff/terminal-launch-events';
+import { subscribeToSignInTerminalExits } from '@/components/handoff/sign-in-terminal-events';
+import {
+ requestTerminalCommandLaunch,
+ requestTerminalLaunch,
+} from '@/components/handoff/terminal-launch-events';
import { useOptionalPageList } from '@/components/PageListContext';
import { RotatingComposerPlaceholder } from '@/components/RotatingComposerPlaceholder';
import { Badge } from '@/components/ui/badge';
@@ -123,7 +128,7 @@ import {
rememberAgentMode,
} from '@/lib/acp/agent-settings-store';
import { configValueHint, resolveDefaultOptionLabel } from '@/lib/acp/config-value-hints';
-import { useHarnessTerminalCli } from '@/lib/acp/harness-terminal-cli';
+import { terminalLaunchAvailable, useHarnessTerminalCli } from '@/lib/acp/harness-terminal-cli';
import {
attachmentBudgetKb,
collectAllFiles,
@@ -209,6 +214,7 @@ import {
type ThreadAuthActionKind,
type ThreadAuthOffer,
type ThreadAuthOfferWithoutSignIn,
+ terminalAuthMethods,
threadAuthHistoryOffer,
threadAuthOffer,
threadAuthOfferWithoutSignInMethods,
@@ -292,6 +298,56 @@ function isSignInWaitingStatus(status: ThreadInfo['status']): boolean {
return status === 'auth_required' || status === 'authenticating';
}
+interface StrandedMessage {
+ readonly messageId: string;
+ readonly text: string;
+ readonly attachments: readonly AttachmentPart[];
+ readonly foldedIndex: number;
+}
+
+function latestSignInNoticeIndex(items: readonly RenderedItem[]): number {
+ for (let index = items.length - 1; index >= 0; index -= 1) {
+ const item = items[index];
+ if (
+ item?.kind === 'notice' &&
+ item.superseded !== true &&
+ item.failure?.reason === 'auth-required'
+ ) {
+ return index;
+ }
+ }
+ return -1;
+}
+
+function strandedMessageBeforeSignIn(items: readonly RenderedItem[]): StrandedMessage | null {
+ const noticeIndex = latestSignInNoticeIndex(items);
+ if (noticeIndex === -1) return null;
+ for (let index = noticeIndex - 1; index >= 0; index -= 1) {
+ const item = items[index];
+ if (item?.kind !== 'message' || item.role !== 'user') continue;
+ let foldedIndex = 0;
+ for (let before = 0; before < index; before += 1) {
+ const earlier = items[before];
+ if (earlier?.kind === 'notice' && earlier.superseded === true) continue;
+ foldedIndex += 1;
+ }
+ return {
+ messageId: item.messageId,
+ text: item.text,
+ attachments: item.attachments ?? [],
+ foldedIndex,
+ };
+ }
+ return null;
+}
+
+function latestTerminalAuthMethod(items: readonly RenderedItem[]): ThreadAuthMethod | null {
+ const noticeIndex = latestSignInNoticeIndex(items);
+ const item = noticeIndex === -1 ? undefined : items[noticeIndex];
+ const methods = item?.kind === 'notice' ? (item.failure?.authMethods ?? []) : [];
+ return terminalAuthMethods(methods)[0] ?? null;
+}
+
function isStartingStatus(status: ThreadInfo['status']): boolean {
return status === 'installing' || status === 'spawning' || isSignInWaitingStatus(status);
}
@@ -585,6 +641,7 @@ export function ThreadView({
const awaitingSignIn = isSignInWaitingStatus(status);
const canRetry = !archived && (status === 'error' || awaitingSignIn);
const terminalCli = useHarnessTerminalCli(info.agent.id);
+ const terminalAvailable = terminalLaunchAvailable();
const [retryPending, setRetryPending] = useState(false);
const [revertedPositions, setRevertedPositions] = useState<ReadonlySet<number>>(new Set());
const canQueue = !archived && turnActive;
@@ -837,15 +894,34 @@ export function ThreadView({
}, [info.threadId]);
const retryThread = (): void => {
+ const stranded =
+ awaitingSignIn && model !== null ? strandedMessageBeforeSignIn(model.items) : null;
setRetryPending(true);
void client
.retryThread(info.threadId)
+ .then((next) => {
+ if (stranded === null || next.status !== 'ready') return;
+ setRevertedPositions((prev) => new Set(prev).add(stranded.foldedIndex));
+ void sendText(stranded.text, stranded.text, stranded.attachments);
+ })
.catch((err: unknown) => {
toast.error(t`Couldn't start ${agentName}: ${errorText(err)}`);
})
.finally(() => setRetryPending(false));
};
+ const retryAfterSignInTerminal = useEffectEvent(() => {
+ if (!awaitingSignIn || retryPending) return;
+ retryThread();
+ });
+ useEffect(
+ () =>
+ subscribeToSignInTerminalExits((threadId) => {
+ if (threadId === info.threadId) retryAfterSignInTerminal();
+ }),
+ [info.threadId],
+ );
+
const authenticateThread = async (methodId: string): Promise<void> => {
await client.authenticateThread(info.threadId, methodId);
};
@@ -911,9 +987,27 @@ export function ThreadView({
case 'new-chat':
startFreshThread();
return;
- case 'terminal-sign-in':
- if (terminalCli !== null) requestTerminalLaunch('', terminalCli);
+ case 'terminal-sign-in': {
+ const method =
+ terminalAvailable && model !== null ? latestTerminalAuthMethod(model.items) : null;
+ if (method !== null) {
+ void client
+ .terminalAuthLaunch(info.threadId, method.id)
+ .then((launch) => {
+ requestTerminalCommandLaunch({
+ label: method.name,
+ command: launch,
+ signInThreadId: info.threadId,
+ });
+ })
+ .catch((err: unknown) => {
+ toast.error(t`Sign-in failed: ${errorText(err)}`);
+ });
+ } else if (terminalCli !== null) {
+ requestTerminalLaunch('', terminalCli, { signInThreadId: info.threadId });
+ }
return;
+ }
default: {
const exhaustive: never = kind;
void exhaustive;
@@ -968,16 +1062,8 @@ export function ThreadView({
agentName,
terminalCli,
});
- let authOfferNoticeIndex = -1;
- if (authOffer.actionLabel !== null) {
- for (let index = visibleItems.length - 1; index >= 0; index -= 1) {
- const item = visibleItems[index];
- if (item?.kind === 'notice' && item.failure?.reason === 'auth-required') {
- authOfferNoticeIndex = index;
- break;
- }
- }
- }
+ const authOfferNoticeIndex =
+ authOffer.actionLabel === null ? -1 : latestSignInNoticeIndex(visibleItems);
let restoreNoticeIndex = -1;
if (!archived && status !== 'exited') {
for (let index = visibleItems.length - 1; index >= 0; index -= 1) {
@@ -1037,21 +1123,17 @@ export function ThreadView({
? t`Couldn't resume this chat: ${resumeError.message}`
: '';
+ const newChatOfferInTranscript = authOffer.kind === 'new-chat' && authOfferNoticeIndex !== -1;
+
const items = visibleItems;
const mentionRecency: MentionRecency = {
currentDocName: activeDocName,
recentPaths: threadAttachmentPaths(items),
};
- let authPrompt: ThreadFailureDetail | null = null;
- if (awaitingSignIn && !archived) {
- for (let index = items.length - 1; index >= 0; index -= 1) {
- const item = items[index];
- if (item?.kind === 'notice' && item.failure?.reason === 'auth-required') {
- authPrompt = item.failure;
- break;
- }
- }
- }
+ const signInNoticeIndex = awaitingSignIn && !archived ? latestSignInNoticeIndex(items) : -1;
+ const signInNotice = signInNoticeIndex === -1 ? undefined : items[signInNoticeIndex];
+ const authPrompt: ThreadFailureDetail | null =
+ signInNotice?.kind === 'notice' ? signInNotice.failure : null;
return (
<MentionRecencyContext value={mentionRecency}>
@@ -1149,6 +1231,7 @@ export function ThreadView({
authMethods: authPrompt.authMethods ?? [],
agentName,
terminalCli,
+ terminalAvailable,
})}
agent={info.agent}
agentName={agentName}
@@ -1366,7 +1449,7 @@ export function ThreadView({
>
{announcedStartStatus}
</span>
- {resumeFailureMessage !== '' ? (
+ {resumeFailureMessage !== '' && !newChatOfferInTranscript ? (
<div
className="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"
data-testid="agent-thread-resume-failed"
diff --git a/packages/app/src/components/acp/thread-auth-offer.test.ts b/packages/app/src/components/acp/thread-auth-offer.test.ts
index 817eec7e1..8c1731016 100644
--- a/packages/app/src/components/acp/thread-auth-offer.test.ts
+++ b/packages/app/src/components/acp/thread-auth-offer.test.ts
@@ -8,6 +8,7 @@ import {
isThreadResumable,
manualAuthMethods,
type ThreadAuthOffer,
+ terminalAuthMethods,
threadAuthOffer,
threadAuthOfferWithoutSignInMethods,
} from './thread-auth-offer';
@@ -40,7 +41,12 @@ function everyOffer(): {
clickableMethodCount: clickableAuthMethods(authMethods).length,
manualMethodCount: manualAuthMethods(authMethods).length,
},
- offer: threadAuthOffer({ authMethods, agentName: 'Claude', terminalCli: null }),
+ offer: threadAuthOffer({
+ authMethods,
+ agentName: 'Claude',
+ terminalCli: null,
+ terminalAvailable: false,
+ }),
}));
}
@@ -100,7 +106,12 @@ describe('threadAuthOffer', () => {
});
test('a live thread awaiting sign-in with no method at all offers retry', () => {
- const offer = threadAuthOffer({ authMethods: [], agentName: 'Claude', terminalCli: null });
+ const offer = threadAuthOffer({
+ authMethods: [],
+ agentName: 'Claude',
+ terminalCli: null,
+ terminalAvailable: false,
+ });
expect(offer.kind).toBe('retry');
expect(offer.headline).toBe('Claude needs you to sign in.');
});
@@ -110,6 +121,7 @@ describe('threadAuthOffer', () => {
authMethods: MANUAL_ONLY,
agentName: 'Claude',
terminalCli: 'claude',
+ terminalAvailable: true,
});
expect(offer.kind).toBe('terminal-sign-in');
expect(offer.actionLabel).toBe('Open terminal to sign in');
@@ -128,6 +140,7 @@ describe('threadAuthOffer', () => {
authMethods: MANUAL_ONLY,
agentName: 'Claude',
terminalCli: null,
+ terminalAvailable: false,
});
expect(offer.kind).toBe('none');
expect(offer.headline).toBe('Claude needed you to sign in.');
@@ -139,6 +152,7 @@ describe('threadAuthOffer', () => {
authMethods: CLICKABLE,
agentName: 'Claude',
terminalCli: null,
+ terminalAvailable: false,
});
expect(offer.kind).toBe('sign-in');
expect(offer.headline).toBe('Sign in to Claude to continue.');
@@ -383,3 +397,51 @@ describe('threadAuthOfferWithoutSignInMethods', () => {
}
});
});
+
+describe('terminal auth methods that carry a command', () => {
+ const LAUNCHABLE: readonly ThreadAuthMethod[] = [
+ {
+ id: 'auggie-login',
+ name: 'Log in with Auggie',
+ kind: 'terminal',
+ terminalLaunchAvailable: true,
+ },
+ ];
+
+ test('only methods with a launch count as terminal methods', () => {
+ expect(terminalAuthMethods([...LAUNCHABLE, ...MANUAL_ONLY, ...CLICKABLE])).toEqual(LAUNCHABLE);
+ });
+
+ test('a launchable method opens the terminal even when no harness CLI is installed', () => {
+ const offer = threadAuthOffer({
+ authMethods: LAUNCHABLE,
+ agentName: 'Auggie',
+ terminalCli: null,
+ terminalAvailable: true,
+ });
+ expect(offer.kind).toBe('terminal-sign-in');
+ expect(offer.actionLabel).toBe('Open terminal to sign in');
+ expect(offer.headline).toBe('Auggie needs you to sign in.');
+ });
+
+ test('without a terminal the launchable method is only described', () => {
+ const offer = threadAuthOffer({
+ authMethods: LAUNCHABLE,
+ agentName: 'Auggie',
+ terminalCli: null,
+ terminalAvailable: false,
+ });
+ expect(offer.kind).toBe('none');
+ expect(offer.actionLabel).toBeNull();
+ });
+
+ test('a clickable method still wins over a launchable one', () => {
+ const offer = threadAuthOffer({
+ authMethods: [...LAUNCHABLE, ...CLICKABLE],
+ agentName: 'Auggie',
+ terminalCli: null,
+ terminalAvailable: true,
+ });
+ expect(offer.kind).toBe('sign-in');
+ });
+});
diff --git a/packages/app/src/components/acp/thread-auth-offer.ts b/packages/app/src/components/acp/thread-auth-offer.ts
index 4608fb0ab..3397934c0 100644
--- a/packages/app/src/components/acp/thread-auth-offer.ts
+++ b/packages/app/src/components/acp/thread-auth-offer.ts
@@ -27,6 +27,7 @@ export interface ThreadAuthOfferInput {
readonly authMethods: readonly ThreadAuthMethod[];
readonly agentName: string;
readonly terminalCli: TerminalCli | null;
+ readonly terminalAvailable: boolean;
}
export function isThreadResumable(info: Pick<ThreadInfo, 'resumable'>): boolean {
@@ -34,7 +35,11 @@ export function isThreadResumable(info: Pick<ThreadInfo, 'resumable'>): boolean
}
function isClickable(method: ThreadAuthMethod): boolean {
- return method.kind !== 'terminal' && method.kind !== 'env_var';
+ return (
+ method.kind !== 'terminal' &&
+ method.kind !== 'env_var' &&
+ method.terminalLaunchAvailable !== true
+ );
}
export function clickableAuthMethods(
@@ -49,6 +54,12 @@ export function manualAuthMethods(
return methods.filter((method) => !isClickable(method));
}
+export function terminalAuthMethods(
+ methods: readonly ThreadAuthMethod[],
+): readonly ThreadAuthMethod[] {
+ return methods.filter((method) => method.terminalLaunchAvailable === true);
+}
+
export function threadAuthHistoryOffer(agentName: string): ThreadAuthOfferWithoutSignIn {
return {
kind: 'none',
@@ -91,7 +102,7 @@ export function threadAuthOfferWithoutSignInMethods({
status,
agentName,
terminalCli,
-}: Omit<ThreadAuthOfferInput, 'authMethods'>): ThreadAuthOfferWithoutSignIn {
+}: Omit<ThreadAuthOfferInput, 'authMethods' | 'terminalAvailable'>): ThreadAuthOfferWithoutSignIn {
if (archived) {
if (!resumable) {
return threadAuthNewChatOffer(agentName);
@@ -133,7 +144,11 @@ export function threadAuthOffer({
authMethods,
agentName,
terminalCli,
-}: Pick<ThreadAuthOfferInput, 'authMethods' | 'agentName' | 'terminalCli'>): ThreadAuthOffer {
+ terminalAvailable,
+}: Pick<
+ ThreadAuthOfferInput,
+ 'authMethods' | 'agentName' | 'terminalCli' | 'terminalAvailable'
+>): ThreadAuthOffer {
if (clickableAuthMethods(authMethods).length > 0) {
return {
kind: 'sign-in',
@@ -141,6 +156,9 @@ export function threadAuthOffer({
actionLabel: t`Sign in`,
};
}
+ if (terminalAvailable && terminalAuthMethods(authMethods).length > 0) {
+ return threadAuthTerminalOffer(agentName);
+ }
if (manualAuthMethods(authMethods).length > 0) {
if (terminalCli != null) return threadAuthTerminalOffer(agentName);
return threadAuthHistoryOffer(agentName);
diff --git a/packages/app/src/components/handoff/sign-in-terminal-events.test.ts b/packages/app/src/components/handoff/sign-in-terminal-events.test.ts
new file mode 100644
index 000000000..933290363
--- /dev/null
+++ b/packages/app/src/components/handoff/sign-in-terminal-events.test.ts
@@ -0,0 +1,25 @@
+import { expect, test, vi } from 'vitest';
+import {
+ notifySignInTerminalExited,
+ subscribeToSignInTerminalExits,
+} from './sign-in-terminal-events';
+
+test('an exit reaches every subscriber with its thread id until they unsubscribe', () => {
+ const target = new EventTarget();
+ const seen = vi.fn();
+ const stop = subscribeToSignInTerminalExits(seen, target);
+ notifySignInTerminalExited('t1', target);
+ expect(seen).toHaveBeenCalledWith('t1');
+ stop();
+ notifySignInTerminalExited('t2', target);
+ expect(seen).toHaveBeenCalledTimes(1);
+});
+
+test('an event without a thread id is ignored', () => {
+ const target = new EventTarget();
+ const seen = vi.fn();
+ subscribeToSignInTerminalExits(seen, target);
+ target.dispatchEvent(new CustomEvent('open-knowledge:sign-in-terminal-exit', { detail: {} }));
+ target.dispatchEvent(new Event('open-knowledge:sign-in-terminal-exit'));
+ expect(seen).not.toHaveBeenCalled();
+});
diff --git a/packages/app/src/components/handoff/sign-in-terminal-events.ts b/packages/app/src/components/handoff/sign-in-terminal-events.ts
new file mode 100644
index 000000000..69d6f05c2
--- /dev/null
+++ b/packages/app/src/components/handoff/sign-in-terminal-events.ts
@@ -0,0 +1,36 @@
+const SIGN_IN_TERMINAL_EXIT_EVENT = 'open-knowledge:sign-in-terminal-exit';
+
+interface SignInTerminalExitDetail {
+ readonly threadId: string;
+}
+
+export function notifySignInTerminalExited(
+ threadId: string,
+ target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'
+ ? new EventTarget()
+ : window,
+): void {
+ target.dispatchEvent(
+ new CustomEvent<SignInTerminalExitDetail>(SIGN_IN_TERMINAL_EXIT_EVENT, {
+ detail: { threadId },
+ }),
+ );
+}
+
+export function subscribeToSignInTerminalExits(
+ onExit: (threadId: string) => void,
+ target: Pick<Window, 'addEventListener' | 'removeEventListener'> | EventTarget = typeof window ===
+ 'undefined'
+ ? new EventTarget()
+ : window,
+): () => void {
+ const listener = (event: Event) => {
+ const detail =
+ event instanceof CustomEvent
+ ? (event as CustomEvent<SignInTerminalExitDetail>).detail
+ : undefined;
+ if (detail && typeof detail.threadId === 'string') onExit(detail.threadId);
+ };
+ target.addEventListener(SIGN_IN_TERMINAL_EXIT_EVENT, listener as EventListener);
+ return () => target.removeEventListener(SIGN_IN_TERMINAL_EXIT_EVENT, listener as EventListener);
+}
diff --git a/packages/app/src/components/handoff/terminal-launch-events.test.ts b/packages/app/src/components/handoff/terminal-launch-events.test.ts
index f433671ad..ea80e845d 100644
--- a/packages/app/src/components/handoff/terminal-launch-events.test.ts
+++ b/packages/app/src/components/handoff/terminal-launch-events.test.ts
@@ -1,15 +1,19 @@
import type { TerminalCli } from '@inkeep/open-knowledge-core';
import { describe, expect, test } from 'vitest';
-import { requestTerminalLaunch, subscribeToTerminalLaunchRequests } from './terminal-launch-events';
+import {
+ requestTerminalCommandLaunch,
+ requestTerminalLaunch,
+ subscribeToTerminalLaunchRequests,
+ type TerminalLaunchRequest,
+} from './terminal-launch-events';
describe('terminal-launch-events', () => {
test('delivers the composed prompt + chosen CLI from request to subscriber', () => {
const target = new EventTarget();
const received: Array<{ prompt: string; cli: TerminalCli }> = [];
- const unsub = subscribeToTerminalLaunchRequests(
- (prompt, cli) => received.push({ prompt, cli }),
- target,
- );
+ const unsub = subscribeToTerminalLaunchRequests((request) => {
+ if (request.kind === 'cli') received.push({ prompt: request.prompt, cli: request.cli });
+ }, target);
requestTerminalLaunch(
"Let's work on `foo.md` using OpenKnowledge.",
@@ -33,13 +37,104 @@ describe('terminal-launch-events', () => {
])('$label', ({ options, expected }) => {
const target = new EventTarget();
const received: boolean[] = [];
- const unsub = subscribeToTerminalLaunchRequests(
- (_p, _c, opts) => received.push(opts.stage),
- target,
- );
+ const unsub = subscribeToTerminalLaunchRequests((request) => {
+ if (request.kind === 'cli') received.push(request.stage);
+ }, target);
requestTerminalLaunch('some text', 'claude', options, target);
expect(received).toEqual([expected]);
unsub();
});
+
+ test('a CLI launch names the chat that opened it for sign-in', () => {
+ const target = new EventTarget();
+ const received: TerminalLaunchRequest[] = [];
+ subscribeToTerminalLaunchRequests((request) => received.push(request), target);
+ requestTerminalLaunch('', 'claude', { signInThreadId: 't1' }, target);
+ expect(received).toEqual([
+ { kind: 'cli', prompt: '', cli: 'claude', stage: false, signInThreadId: 't1' },
+ ]);
+ });
+
+ test('a command launch carries the command, its label and the signing-in chat', () => {
+ const target = new EventTarget();
+ const received: TerminalLaunchRequest[] = [];
+ subscribeToTerminalLaunchRequests((request) => received.push(request), target);
+ requestTerminalCommandLaunch(
+ {
+ label: 'Log in with Auggie',
+ command: { executable: 'auggie', args: ['--acp', 'login'], env: {}, pathPrepend: [] },
+ signInThreadId: 't1',
+ },
+ target,
+ );
+ expect(received).toEqual([
+ {
+ kind: 'command',
+ label: 'Log in with Auggie',
+ command: { executable: 'auggie', args: ['--acp', 'login'], env: {}, pathPrepend: [] },
+ signInThreadId: 't1',
+ },
+ ]);
+ });
+
+ test('an untagged prompt-and-cli detail, the shape the desktop smoke harness dispatches, is a CLI launch', () => {
+ const target = new EventTarget();
+ const received: TerminalLaunchRequest[] = [];
+ subscribeToTerminalLaunchRequests((request) => received.push(request), target);
+ target.dispatchEvent(
+ new CustomEvent('open-knowledge:terminal-launch', {
+ detail: { prompt: '', cli: 'claude', stage: false },
+ }),
+ );
+ target.dispatchEvent(
+ new CustomEvent('open-knowledge:terminal-launch', {
+ detail: { prompt: 'fix this', cli: 'codex', stage: true },
+ }),
+ );
+ expect(received).toEqual([
+ { kind: 'cli', prompt: '', cli: 'claude', stage: false },
+ { kind: 'cli', prompt: 'fix this', cli: 'codex', stage: true },
+ ]);
+ });
+
+ test('an unknown tag never launches, even with a valid prompt and CLI', () => {
+ const target = new EventTarget();
+ const received: TerminalLaunchRequest[] = [];
+ subscribeToTerminalLaunchRequests((request) => received.push(request), target);
+ target.dispatchEvent(
+ new CustomEvent('open-knowledge:terminal-launch', {
+ detail: { kind: 'script', prompt: 'p', cli: 'claude', stage: false },
+ }),
+ );
+ expect(received).toEqual([]);
+ });
+
+ test('a malformed command or an untagged detail without a CLI is ignored', () => {
+ const target = new EventTarget();
+ const received: TerminalLaunchRequest[] = [];
+ subscribeToTerminalLaunchRequests((request) => received.push(request), target);
+ for (const detail of [
+ { kind: 'command', label: 'x', command: { executable: 7, args: [] } },
+ { kind: 'command', label: 'x', command: { executable: 'auggie', args: 'login' } },
+ { kind: 'command', label: 'x', command: null },
+ { kind: 'command', command: { executable: 'auggie', args: [] } },
+ { prompt: 'p', stage: false },
+ { prompt: 7, cli: 'claude' },
+ ]) {
+ target.dispatchEvent(new CustomEvent('open-knowledge:terminal-launch', { detail }));
+ }
+ expect(received).toEqual([]);
+ });
+
+ test('a malformed event is ignored', () => {
+ const target = new EventTarget();
+ const received: TerminalLaunchRequest[] = [];
+ subscribeToTerminalLaunchRequests((request) => received.push(request), target);
+ target.dispatchEvent(
+ new CustomEvent('open-knowledge:terminal-launch', { detail: { kind: 'command' } }),
+ );
+ target.dispatchEvent(new Event('open-knowledge:terminal-launch'));
+ expect(received).toEqual([]);
+ });
});
diff --git a/packages/app/src/components/handoff/terminal-launch-events.ts b/packages/app/src/components/handoff/terminal-launch-events.ts
index 9b249b019..f0aee15ad 100644
--- a/packages/app/src/components/handoff/terminal-launch-events.ts
+++ b/packages/app/src/components/handoff/terminal-launch-events.ts
@@ -1,60 +1,112 @@
-import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import type { TerminalCli, TerminalLaunchCommand } from '@inkeep/open-knowledge-core';
import { routeNoteWindowActionToMain } from '@/lib/note-window-main-actions';
const TERMINAL_LAUNCH_EVENT = 'open-knowledge:terminal-launch';
-interface TerminalLaunchDetail {
- readonly prompt: string;
- readonly cli: TerminalCli;
- readonly stage: boolean;
-}
+export type TerminalLaunchRequest =
+ | {
+ readonly kind: 'cli';
+ readonly prompt: string;
+ readonly cli: TerminalCli;
+ readonly stage: boolean;
+ readonly signInThreadId?: string;
+ }
+ | {
+ readonly kind: 'command';
+ readonly command: TerminalLaunchCommand;
+ readonly label: string;
+ readonly signInThreadId?: string;
+ };
export interface TerminalLaunchOptions {
readonly stage?: boolean;
+ readonly signInThreadId?: string;
+}
+
+export interface TerminalCommandLaunchRequest {
+ readonly command: TerminalLaunchCommand;
+ readonly label: string;
+ readonly signInThreadId?: string;
+}
+
+type LaunchTarget = Pick<Window, 'dispatchEvent'> | EventTarget;
+
+function defaultTarget(): LaunchTarget {
+ return typeof window === 'undefined' ? new EventTarget() : window;
+}
+
+function dispatchLaunch(target: LaunchTarget, request: TerminalLaunchRequest): void {
+ target.dispatchEvent(
+ new CustomEvent<TerminalLaunchRequest>(TERMINAL_LAUNCH_EVENT, { detail: request }),
+ );
}
export function requestTerminalLaunch(
prompt: string,
cli: TerminalCli,
options?: TerminalLaunchOptions,
- target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'
- ? new EventTarget()
- : window,
+ target: LaunchTarget = defaultTarget(),
): void {
- if (
- routeNoteWindowActionToMain(
- {
- kind: 'terminal-launch',
- prompt,
- cli,
- stage: options?.stage === true,
- },
- target,
- )
- )
- return;
- target.dispatchEvent(
- new CustomEvent<TerminalLaunchDetail>(TERMINAL_LAUNCH_EVENT, {
- detail: { prompt, cli, stage: options?.stage === true },
- }),
- );
+ const stage = options?.stage === true;
+ if (routeNoteWindowActionToMain({ kind: 'terminal-launch', prompt, cli, stage }, target)) return;
+ dispatchLaunch(target, {
+ kind: 'cli',
+ prompt,
+ cli,
+ stage,
+ ...(options?.signInThreadId === undefined ? {} : { signInThreadId: options.signInThreadId }),
+ });
+}
+
+export function requestTerminalCommandLaunch(
+ request: TerminalCommandLaunchRequest,
+ target: LaunchTarget = defaultTarget(),
+): void {
+ dispatchLaunch(target, { kind: 'command', ...request });
}
export function subscribeToTerminalLaunchRequests(
- onRequest: (prompt: string, cli: TerminalCli, options: { stage: boolean }) => void,
+ onRequest: (request: TerminalLaunchRequest) => void,
target: Pick<Window, 'addEventListener' | 'removeEventListener'> | EventTarget = typeof window ===
'undefined'
? new EventTarget()
: window,
): () => void {
const listener = (event: Event) => {
- const detail =
- event instanceof CustomEvent
- ? (event as CustomEvent<TerminalLaunchDetail>).detail
+ const detail: Record<string, unknown> | undefined =
+ event instanceof CustomEvent && typeof event.detail === 'object' && event.detail !== null
+ ? (event.detail as Record<string, unknown>)
: undefined;
- if (detail && typeof detail.prompt === 'string') {
- onRequest(detail.prompt, detail.cli, { stage: detail.stage === true });
+ if (detail === undefined) return;
+ const signIn =
+ typeof detail.signInThreadId === 'string' ? { signInThreadId: detail.signInThreadId } : {};
+ if (detail.kind === 'command') {
+ const command = detail.command;
+ if (
+ typeof command === 'object' &&
+ command !== null &&
+ typeof (command as { executable?: unknown }).executable === 'string' &&
+ Array.isArray((command as { args?: unknown }).args) &&
+ typeof detail.label === 'string'
+ ) {
+ onRequest({
+ kind: 'command',
+ command: command as TerminalLaunchCommand,
+ label: detail.label,
+ ...signIn,
+ });
+ }
+ return;
}
+ if (detail.kind !== undefined && detail.kind !== 'cli') return;
+ if (typeof detail.prompt !== 'string' || typeof detail.cli !== 'string') return;
+ onRequest({
+ kind: 'cli',
+ prompt: detail.prompt,
+ cli: detail.cli as TerminalCli,
+ stage: detail.stage === true,
+ ...signIn,
+ });
};
target.addEventListener(TERMINAL_LAUNCH_EVENT, listener as EventListener);
return () => target.removeEventListener(TERMINAL_LAUNCH_EVENT, listener as EventListener);
diff --git a/packages/app/src/lib/acp/harness-terminal-cli.ts b/packages/app/src/lib/acp/harness-terminal-cli.ts
index 195eb0680..d6cfaabc0 100644
--- a/packages/app/src/lib/acp/harness-terminal-cli.ts
+++ b/packages/app/src/lib/acp/harness-terminal-cli.ts
@@ -20,7 +20,7 @@ export function harnessTerminalCli(
return installedClis[cli] === true ? cli : null;
}
-function terminalLaunchAvailable(): boolean {
+export function terminalLaunchAvailable(): boolean {
if (typeof window === 'undefined' || isNoteWindow()) return false;
const bridge = window.okDesktop ?? null;
return bridge?.terminal != null && bridge.config.ptyAvailable === true;
diff --git a/packages/app/src/lib/acp/thread-client.test.ts b/packages/app/src/lib/acp/thread-client.test.ts
index 1458bc354..d90b05cb5 100644
--- a/packages/app/src/lib/acp/thread-client.test.ts
+++ b/packages/app/src/lib/acp/thread-client.test.ts
@@ -590,6 +590,44 @@ describe('retry and sign-in lifecycle', () => {
frame({ op: 'error', code: 'not-ready', message: 'wrong account', reqId, threadId: 't1' });
await expect(pending).rejects.toThrow(/wrong account/);
});
+
+ test('terminalAuthLaunch sends the method id and resolves with the launch the server composed', async () => {
+ const { client, sent, frame } = makeWiredClient();
+ const pending = client.terminalAuthLaunch('t1', 'cli-login');
+ await flush();
+ const request = sent.find((f) => f.op === 'terminal_auth_launch');
+ expect(request).toMatchObject({
+ op: 'terminal_auth_launch',
+ threadId: 't1',
+ methodId: 'cli-login',
+ });
+ expect(String(request?.reqId)).toMatch(/^terminal-auth-/);
+
+ const launch = {
+ executable: 'auggie',
+ args: ['--acp', 'login'],
+ env: { AUGGIE_LOGIN_FLOW: 'terminal' },
+ pathPrepend: [],
+ };
+ frame({ op: 'terminal_auth_launch_ready', reqId: request?.reqId as string, launch });
+ await expect(pending).resolves.toEqual(launch);
+ });
+
+ test('a terminal launch the server refuses rejects with its reason', async () => {
+ const { client, sent, frame } = makeWiredClient();
+ const pending = client.terminalAuthLaunch('t1', 'missing');
+ await flush();
+ const reqId = sent.find((f) => f.op === 'terminal_auth_launch')?.reqId as string;
+
+ frame({
+ op: 'error',
+ code: 'not-ready',
+ message: 'this agent offers no terminal sign-in by that name',
+ reqId,
+ threadId: 't1',
+ });
+ await expect(pending).rejects.toThrow(/no terminal sign-in by that name/);
+ });
});
describe('createThread channel wait', () => {
diff --git a/packages/app/src/lib/acp/thread-client.ts b/packages/app/src/lib/acp/thread-client.ts
index 070c32e99..e715d5157 100644
--- a/packages/app/src/lib/acp/thread-client.ts
+++ b/packages/app/src/lib/acp/thread-client.ts
@@ -1,5 +1,6 @@
import type {
AttachmentPart,
+ ThreadAuthTerminalLaunch,
ThreadChatGrant,
ThreadClientFrame,
ThreadErrorCode,
@@ -34,6 +35,12 @@ interface PendingCreate {
timer: ReturnType<typeof setTimeout>;
}
+interface PendingTerminalAuthLaunch {
+ resolve: (launch: ThreadAuthTerminalLaunch) => void;
+ reject: (err: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
interface PendingQueueEdit {
resolve: () => void;
reject: (err: Error) => void;
@@ -90,6 +97,7 @@ export class AgentThreadClient {
private pendingCreates = new Map<string, PendingCreate>();
private pendingResumes = new Map<string, PendingCreate>();
private pendingRetries = new Map<string, PendingCreate>();
+ private pendingTerminalAuthLaunches = new Map<string, PendingTerminalAuthLaunch>();
private pendingContextWindows = new Map<string, PendingCreate>();
private pendingAuths = new Map<string, PendingCreate>();
private pendingQueueEdits = new Map<string, PendingQueueEdit>();
@@ -422,6 +430,22 @@ export class AgentThreadClient {
return promise;
}
+ async terminalAuthLaunch(threadId: string, methodId: string): Promise<ThreadAuthTerminalLaunch> {
+ this.connectNow();
+ await this.waitForOpen(CHANNEL_WAIT_MS);
+ this.reqCounter += 1;
+ const reqId = `terminal-auth-${this.reqCounter}`;
+ const promise = new Promise<ThreadAuthTerminalLaunch>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pendingTerminalAuthLaunches.delete(reqId);
+ reject(new Error('the sign-in terminal request timed out'));
+ }, RETRY_TIMEOUT_MS);
+ this.pendingTerminalAuthLaunches.set(reqId, { resolve, reject, timer });
+ });
+ this.send({ op: 'terminal_auth_launch', threadId, reqId, methodId });
+ return promise;
+ }
+
async authenticateThread(threadId: string, methodId: string): Promise<ThreadInfo> {
this.connectNow();
await this.waitForOpen(CHANNEL_WAIT_MS);
@@ -520,6 +544,11 @@ export class AgentThreadClient {
pending.reject(new ThreadChannelUnavailableError());
}
this.pendingRetries.clear();
+ for (const pending of this.pendingTerminalAuthLaunches.values()) {
+ clearTimeout(pending.timer);
+ pending.reject(new ThreadChannelUnavailableError());
+ }
+ this.pendingTerminalAuthLaunches.clear();
for (const pending of this.pendingContextWindows.values()) {
clearTimeout(pending.timer);
pending.reject(new ThreadChannelUnavailableError());
@@ -635,6 +664,15 @@ export class AgentThreadClient {
this.upsertInfo(frame.info);
return;
}
+ case 'terminal_auth_launch_ready': {
+ const pending = this.pendingTerminalAuthLaunches.get(frame.reqId);
+ if (pending !== undefined) {
+ this.pendingTerminalAuthLaunches.delete(frame.reqId);
+ clearTimeout(pending.timer);
+ pending.resolve(frame.launch);
+ }
+ return;
+ }
case 'context_window_set': {
const pending = this.pendingContextWindows.get(frame.reqId);
if (pending !== undefined) {
@@ -711,6 +749,13 @@ export class AgentThreadClient {
pendingRetry.reject(new Error(frame.message));
return;
}
+ const pendingTerminalAuth = this.pendingTerminalAuthLaunches.get(frame.reqId);
+ if (pendingTerminalAuth !== undefined) {
+ this.pendingTerminalAuthLaunches.delete(frame.reqId);
+ clearTimeout(pendingTerminalAuth.timer);
+ pendingTerminalAuth.reject(new Error(frame.message));
+ return;
+ }
const pendingWindow = this.pendingContextWindows.get(frame.reqId);
if (pendingWindow !== undefined) {
this.pendingContextWindows.delete(frame.reqId);
diff --git a/packages/cli/src/commands/start.terminal-auth.test.ts b/packages/cli/src/commands/start.terminal-auth.test.ts
new file mode 100644
index 000000000..487e7fd8b
--- /dev/null
+++ b/packages/cli/src/commands/start.terminal-auth.test.ts
@@ -0,0 +1,118 @@
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { ConfigSchema } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { type BootedStartServer, bootStartServer, runStartCommand, startCommand } from './start.ts';
+
+const bootServerCalls = vi.hoisted(() => [] as Array<Record<string, unknown>>);
+
+vi.mock('@inkeep/open-knowledge-server', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@inkeep/open-knowledge-server')>();
+ return {
+ ...actual,
+ bootServer: (opts: Parameters<typeof actual.bootServer>[0]) => {
+ bootServerCalls.push(opts as unknown as Record<string, unknown>);
+ return actual.bootServer(opts);
+ },
+ };
+});
+
+describe('--terminal-auth reaches bootServer', () => {
+ let tmpDir: string;
+ let booted: BootedStartServer | null = null;
+ let originalHome: string | undefined;
+
+ beforeEach(async () => {
+ tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-start-terminal-auth-'));
+ const okDir = resolve(tmpDir, '.ok');
+ mkdirSync(okDir, { recursive: true });
+ writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');
+ writeFileSync(resolve(okDir, '.gitignore'), '', 'utf-8');
+ originalHome = process.env.HOME;
+ process.env.HOME = tmpDir;
+ bootServerCalls.length = 0;
+ });
+
+ afterEach(async () => {
+ if (booted) {
+ try {
+ await booted.destroy();
+ } catch {}
+ booted = null;
+ }
+ if (originalHome === undefined) delete process.env.HOME;
+ else process.env.HOME = originalHome;
+ await rm(tmpDir, { recursive: true, force: true });
+ });
+
+ test('bootStartServer passes terminalAuthAvailable on, and only when it is true', async () => {
+ booted = await bootStartServer({
+ config: ConfigSchema.parse({}),
+ cwd: tmpDir,
+ host: '127.0.0.1',
+ skipAutoInit: true,
+ terminalAuthAvailable: true,
+ });
+ expect(bootServerCalls).toHaveLength(1);
+ expect(bootServerCalls[0]?.terminalAuthAvailable).toBe(true);
+ await booted.destroy();
+ booted = null;
+
+ booted = await bootStartServer({
+ config: ConfigSchema.parse({}),
+ cwd: tmpDir,
+ host: '127.0.0.1',
+ skipAutoInit: true,
+ });
+ expect(bootServerCalls).toHaveLength(2);
+ expect(bootServerCalls[1]).not.toHaveProperty('terminalAuthAvailable');
+ });
+
+ test('the start command forwards --terminal-auth to bootServer, and nothing without it', async () => {
+ const cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(tmpDir);
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const exits: number[] = [];
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ exits.push(code ?? 0);
+ return undefined as never;
+ }) as never);
+ const stopServer = async (expected: number) => {
+ process.emit('SIGTERM', 'SIGTERM');
+ await vi.waitFor(() => expect(exits).toHaveLength(expected), { timeout: 20_000 });
+ };
+ try {
+ await runStartCommand(ConfigSchema.parse({}), {
+ terminalAuth: true,
+ only: 'server',
+ openBrowser: false,
+ });
+ expect(bootServerCalls).toHaveLength(1);
+ expect(bootServerCalls[0]?.terminalAuthAvailable).toBe(true);
+ await stopServer(1);
+
+ await runStartCommand(ConfigSchema.parse({}), { only: 'server', openBrowser: false });
+ expect(bootServerCalls).toHaveLength(2);
+ expect(bootServerCalls[1]).not.toHaveProperty('terminalAuthAvailable');
+ await stopServer(2);
+ } finally {
+ cwdSpy.mockRestore();
+ logSpy.mockRestore();
+ exitSpy.mockRestore();
+ }
+ }, 60_000);
+
+ test('the start command parses the hidden flag into its options', async () => {
+ const cmd = startCommand(() => ConfigSchema.parse({}));
+ cmd.exitOverride();
+ cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} });
+ let captured: Record<string, unknown> = {};
+ cmd.action((opts: Record<string, unknown>) => {
+ captured = opts;
+ });
+ await cmd.parseAsync(['--terminal-auth', '--no-open-browser'], { from: 'user' });
+ expect(captured.terminalAuth).toBe(true);
+ expect(cmd.helpInformation()).not.toContain('--terminal-auth');
+ });
+});
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 976971afb..5ed796664 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -308,6 +308,7 @@ interface BootStartServerOptions {
reactShellDistDir?: string;
singleFile?: string;
projectDir?: string;
+ terminalAuthAvailable?: boolean;
}
export interface BootedStartServer {
@@ -507,6 +508,7 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
? { serveContentAssets: opts.serveContentAssets }
: {}),
...(opts.reactShellDistDir ? { reactShellDistDir: opts.reactShellDistDir } : {}),
+ ...(opts.terminalAuthAvailable === true ? { terminalAuthAvailable: true } : {}),
});
} catch (err) {
await reapOwnedEphemeralDir();
@@ -549,6 +551,7 @@ interface StartCommandOptions {
singleFile?: string;
projectDir?: string;
externalUrl?: string;
+ terminalAuth?: boolean;
}
export function resolveStartConfig(
@@ -702,6 +705,7 @@ export async function runStartCommand(configArg: Config, opts: StartCommandOptio
serverRuntime: runtime,
...(opts.singleFile ? { singleFile: opts.singleFile } : {}),
...(opts.projectDir ? { projectDir: opts.projectDir } : {}),
+ ...(opts.terminalAuth === true ? { terminalAuthAvailable: true } : {}),
});
} catch (err) {
if (err instanceof OkDirMissingError) {
@@ -991,6 +995,12 @@ export function startCommand(getConfig: () => Config): Command {
'Throwaway project root for --single-file (where ephemeral .ok/ state lives)',
).hideHelp(),
)
+ .addOption(
+ new Option(
+ '--terminal-auth',
+ "Tell in-app agents that this server's client can run terminal sign-ins (the desktop app passes it when it has a terminal)",
+ ).hideHelp(),
+ )
.option(
'--external-url <url>',
'Canonical external origin clients dial (sets server.externalUrl for this run) — its host joins the Host/Origin allowlists (CORS + external-Host admission). External exposure additionally requires consent (OK_ALLOW_EXTERNAL=1 or server.allowExternal).',
diff --git a/packages/core/src/acp/thread-protocol.ts b/packages/core/src/acp/thread-protocol.ts
index c30507b83..3a7268c13 100644
--- a/packages/core/src/acp/thread-protocol.ts
+++ b/packages/core/src/acp/thread-protocol.ts
@@ -49,11 +49,19 @@ export type PiBridgeThreadState =
| 'bridge-failed'
| 'trust-failed';
+export interface ThreadAuthTerminalLaunch {
+ executable: string;
+ args: string[];
+ env: Record<string, string>;
+ pathPrepend: string[];
+}
+
export interface ThreadAuthMethod {
id: string;
name: string;
description?: string;
kind?: string;
+ terminalLaunchAvailable?: true;
}
export interface ThreadFailureDetail {
@@ -344,6 +352,12 @@ export type ThreadClientFrame =
threadId: string;
reqId: string;
}
+ | {
+ op: 'terminal_auth_launch';
+ threadId: string;
+ reqId: string;
+ methodId: string;
+ }
| {
op: 'authenticate';
threadId: string;
@@ -360,6 +374,7 @@ export type ThreadServerFrame =
| { op: 'created'; reqId: string; info: ThreadInfo }
| { op: 'resumed'; reqId: string; info: ThreadInfo }
| { op: 'retried'; reqId: string; info: ThreadInfo }
+ | { op: 'terminal_auth_launch_ready'; reqId: string; launch: ThreadAuthTerminalLaunch }
| { op: 'context_window_set'; reqId: string; info: ThreadInfo }
| { op: 'authenticated'; reqId: string; info: ThreadInfo }
| { op: 'subscribed'; threadId: string; fromSeq: number; info: ThreadInfo }
@@ -419,6 +434,7 @@ const CLIENT_OPS = new Set([
'rename',
'resume',
'retry',
+ 'terminal_auth_launch',
'authenticate',
'delete',
'list',
@@ -583,6 +599,9 @@ export function parseThreadClientFrame(raw: string): ThreadClientFrame | null {
case 'retry':
if (!str('threadId') || !str('reqId')) return null;
return frame as unknown as ThreadClientFrame;
+ case 'terminal_auth_launch':
+ if (!str('threadId') || !str('reqId') || !str('methodId')) return null;
+ return frame as unknown as ThreadClientFrame;
case 'authenticate':
if (!str('threadId') || !str('reqId') || !str('methodId')) return null;
return frame as unknown as ThreadClientFrame;
diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.ts
index 3419682a7..dbee2cf40 100644
--- a/packages/core/src/handoff/index.ts
+++ b/packages/core/src/handoff/index.ts
@@ -33,6 +33,7 @@ export {
buildStartupInjectionBytes,
buildWindowsCliLaunch,
composeWindowsShellLaunchArgs,
+ isTerminalLaunchEnvName,
isWindowsShellFamily,
isWindowsShellLaunchFailureReason,
launchWithoutSupportFile,
@@ -47,6 +48,7 @@ export {
type TerminalCli,
type TerminalCliInfo,
type TerminalLaunchCommand,
+ terminalLaunchEnvSlots,
WINDOWS_SHELL_FAMILIES,
type WindowsShellFamily,
WindowsShellLaunchError,
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index d827cd27a..71b3562cb 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -165,6 +165,22 @@ describe('Windows launch composition', () => {
).toEqual({ executable: 'claude', args: [] });
});
+ it('keeps the env and PATH dirs of a support-file launch while dropping its arguments', () => {
+ expect(
+ launchWithoutSupportFile({
+ executable: 'claude',
+ args: ['--settings', 'x.json'],
+ env: { A: '1' },
+ pathPrepend: ['/rt/bin'],
+ supportFile: {
+ kind: 'claude-settings',
+ relativePath: '.ok/local/terminal/claude-settings-mcp.json',
+ contents: '{}',
+ },
+ }),
+ ).toEqual({ executable: 'claude', args: [], env: { A: '1' }, pathPrepend: ['/rt/bin'] });
+ });
+
it('composes PowerShell as -NoExit -EncodedCommand with quoted structured args', () => {
const args = composeWindowsShellLaunchArgs('C:\\Program Files\\PowerShell\\7\\pwsh.exe', {
executable: 'native.exe',
@@ -736,3 +752,150 @@ describe('isWindowsShellFamily', () => {
expect(isWindowsShellFamily(['cmd'])).toBe(false);
});
});
+
+describe('composeWindowsShellLaunchArgs with a launch env', () => {
+ const NUL = String.fromCharCode(0);
+ const launch = {
+ executable: 'auggie',
+ args: ['--acp', 'login'],
+ env: { AUGGIE_HOME: 'C:\\Users\\me\\.auggie', AUGGIE_LOGIN_FLOW: 'terminal' },
+ };
+ const decodeArgv = (encoded: string) =>
+ Buffer.from(encoded, 'base64').toString('utf8').split(NUL).filter(Boolean);
+
+ it('bash hands name and slot pairs to a subshell around the login, then drops the slots', () => {
+ const args = composeWindowsShellLaunchArgs(
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
+ launch,
+ ) as string[];
+ expect(decodeArgv(args[5] ?? '')).toEqual(['auggie', '--acp', 'login']);
+ expect(decodeArgv(args[6] ?? '')).toEqual([
+ 'AUGGIE_HOME',
+ 'OK_TERMINAL_LAUNCH_ENV_0',
+ 'AUGGIE_LOGIN_FLOW',
+ 'OK_TERMINAL_LAUNCH_ENV_1',
+ ]);
+ expect(args[3]).toContain(
+ `(for ((__ok_i = 0; __ok_i < \${#__ok_env[@]}; __ok_i += 2)); do __ok_slot="\${__ok_env[__ok_i + 1]}"; export "\${__ok_env[__ok_i]}=\${!__ok_slot}"; done; exec "\${__ok_argv[@]}"); `,
+ );
+ expect(args[3]).toContain(
+ `for ((__ok_i = 1; __ok_i < \${#__ok_env[@]}; __ok_i += 2)); do unset "\${__ok_env[__ok_i]}"; done; exec "$BASH" --login -i`,
+ );
+ expect(args.join(' ')).not.toContain('.auggie');
+ });
+
+ it('PowerShell saves what each name held, assigns the slots for the login, and puts the old values back in a finally block', () => {
+ const args = composeWindowsShellLaunchArgs('pwsh.exe', launch) as string[];
+ const script = Buffer.from(args[2] ?? '', 'base64').toString('utf16le');
+ expect(script).toBe(
+ "$__ok_names = @('AUGGIE_HOME', 'AUGGIE_LOGIN_FLOW'); $__ok_slots = @('OK_TERMINAL_LAUNCH_ENV_0', 'OK_TERMINAL_LAUNCH_ENV_1'); $__ok_prev = @{}; " +
+ 'for ($__ok_i = 0; $__ok_i -lt $__ok_names.Length; $__ok_i++) { ' +
+ '$__ok_prev[$__ok_names[$__ok_i]] = [Environment]::GetEnvironmentVariable($__ok_names[$__ok_i]); ' +
+ "[Environment]::SetEnvironmentVariable($__ok_names[$__ok_i], [Environment]::GetEnvironmentVariable($__ok_slots[$__ok_i]), 'Process') }; " +
+ "try { & 'auggie' '--acp' 'login' } finally { " +
+ 'for ($__ok_i = 0; $__ok_i -lt $__ok_names.Length; $__ok_i++) { ' +
+ "[Environment]::SetEnvironmentVariable($__ok_names[$__ok_i], $__ok_prev[$__ok_names[$__ok_i]], 'Process'); " +
+ "[Environment]::SetEnvironmentVariable($__ok_slots[$__ok_i], $null, 'Process') }; " +
+ 'Remove-Variable __ok_names, __ok_slots, __ok_prev, __ok_i -ErrorAction SilentlyContinue }',
+ );
+ expect(script).not.toContain('.auggie');
+ const plain = composeWindowsShellLaunchArgs('pwsh.exe', {
+ executable: 'auggie',
+ args: ['login'],
+ }) as string[];
+ expect(Buffer.from(plain[2] ?? '', 'base64').toString('utf16le')).toBe("& 'auggie' 'login'");
+ });
+
+ it('cmd runs the login in a child cmd that expands the slots itself, so the tab never holds the names', () => {
+ expect(
+ composeWindowsShellLaunchArgs('cmd.exe', {
+ executable: 'auggie',
+ args: ['login'],
+ env: { AUGGIE_LOGIN_FLOW: 'terminal' },
+ }),
+ ).toBe(
+ '/K cmd /d /v:on /c "set "AUGGIE_LOGIN_FLOW=!OK_TERMINAL_LAUNCH_ENV_0!" & auggie login" & set "OK_TERMINAL_LAUNCH_ENV_0="',
+ );
+ expect(
+ composeWindowsShellLaunchArgs('cmd.exe', {
+ executable: 'auggie',
+ args: ['login'],
+ env: { AUGGIE_HOME: 'C:\\auggie', AUGGIE_LOGIN_FLOW: 'terminal' },
+ }),
+ ).toBe(
+ '/K cmd /d /v:on /c "set "AUGGIE_HOME=!OK_TERMINAL_LAUNCH_ENV_0!" & set "AUGGIE_LOGIN_FLOW=!OK_TERMINAL_LAUNCH_ENV_1!" & auggie login" & set "OK_TERMINAL_LAUNCH_ENV_0=" & set "OK_TERMINAL_LAUNCH_ENV_1="',
+ );
+ expect(
+ composeWindowsShellLaunchArgs('cmd.exe', { executable: 'auggie', args: ['login'] }),
+ ).toBe('/K auggie login');
+ expect(
+ composeWindowsShellLaunchArgs('cmd.exe', {
+ executable: 'auggie',
+ args: ['login'],
+ env: { AUGGIE_HOME: 'C:\\Users\\me space\\.auggie', AUGGIE_LOGIN_FLOW: 'terminal=yes' },
+ }),
+ ).toBe(
+ '/K cmd /d /v:on /c "set "AUGGIE_HOME=!OK_TERMINAL_LAUNCH_ENV_0!" & set "AUGGIE_LOGIN_FLOW=!OK_TERMINAL_LAUNCH_ENV_1!" & auggie login" & set "OK_TERMINAL_LAUNCH_ENV_0=" & set "OK_TERMINAL_LAUNCH_ENV_1="',
+ );
+ for (const value of [
+ 'say "hi"',
+ 'x" & calc & rem "',
+ 'a & calc',
+ 'pipe | more',
+ 'to > file',
+ 'from < file',
+ 'group (x)',
+ 'caret ^x',
+ '%TEMP%',
+ '!OK_TERMINAL_LAUNCH_ENV_0!',
+ 'two\nlines',
+ 'cr\rhere',
+ ]) {
+ expect(() =>
+ composeWindowsShellLaunchArgs('cmd.exe', {
+ executable: 'auggie',
+ args: ['login'],
+ env: { AUGGIE_LOGIN_FLOW: value },
+ }),
+ ).toThrow(
+ expect.objectContaining({ name: 'WindowsShellLaunchError', reason: 'unsafe-argument' }),
+ );
+ }
+ });
+
+ it.each([
+ ['bash', 'C:\\Program Files\\Git\\bin\\bash.exe'],
+ ['PowerShell', 'pwsh.exe'],
+ ['cmd', 'cmd.exe'],
+ ])('%s refuses env names that differ only in case', (_family, shell) => {
+ expect(() =>
+ composeWindowsShellLaunchArgs(shell, {
+ executable: 'auggie',
+ args: ['login'],
+ env: { Path: 'C:\\agent', PATH: 'C:\\other' },
+ }),
+ ).toThrow(
+ expect.objectContaining({ name: 'WindowsShellLaunchError', reason: 'invalid-launch' }),
+ );
+ });
+
+ it.each([
+ ['bash', 'C:\\Program Files\\Git\\bin\\bash.exe'],
+ ['PowerShell', 'pwsh.exe'],
+ ['cmd', 'cmd.exe'],
+ ])('%s refuses env names that are not identifiers and values with NUL', (_family, shell) => {
+ for (const env of [
+ { 'X; Start-Process calc; $y': '1' },
+ { '--split-string': 'evil' },
+ { 'A B': '1' },
+ { '1ABC': '1' },
+ { OK_TERMINAL_LAUNCH_ENV_0: 'reserved for the slot the launch itself uses' },
+ { ok_terminal_launch_env_0: 'the same slot on a case-folding shell' },
+ { OK: `a${NUL}b` },
+ ]) {
+ expect(() =>
+ composeWindowsShellLaunchArgs(shell, { executable: 'auggie', args: ['login'], env }),
+ ).toThrow(WindowsShellLaunchError);
+ }
+ });
+});
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
index 6846db97b..3d52c1a6b 100644
--- a/packages/core/src/handoff/terminal-launch.ts
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -8,6 +8,8 @@ export function shellSingleQuote(s: string): string {
export interface TerminalLaunchCommand {
readonly executable: string;
readonly args: readonly string[];
+ readonly env?: Readonly<Record<string, string>>;
+ readonly pathPrepend?: readonly string[];
readonly supportFile?: {
readonly kind: 'claude-settings';
readonly relativePath: string;
@@ -21,7 +23,8 @@ function claudeSettingsFileArgs(relativePath: string): readonly string[] {
export function launchWithoutSupportFile(launch: TerminalLaunchCommand): TerminalLaunchCommand {
if (launch.supportFile === undefined) return launch;
- return { executable: launch.executable, args: [] };
+ const { supportFile: _supportFile, ...rest } = launch;
+ return { ...rest, args: [] };
}
const WINDOWS_SHELL_FAMILY_VOCABULARY = ['powershell', 'cmd', 'bash'] as const;
@@ -47,9 +50,41 @@ function encodeUtf8Base64(value: string): string {
return btoa(binary);
}
+const TERMINAL_LAUNCH_ENV_SLOT_PREFIX = 'OK_TERMINAL_LAUNCH_ENV_';
+
+export interface TerminalLaunchEnvSlot {
+ readonly name: string;
+ readonly slot: string;
+ readonly value: string;
+}
+
+export function terminalLaunchEnvSlots(
+ env: Readonly<Record<string, string>> | undefined,
+): TerminalLaunchEnvSlot[] {
+ return Object.entries(env ?? {}).map(([name, value], index) => ({
+ name,
+ slot: `${TERMINAL_LAUNCH_ENV_SLOT_PREFIX}${index}`,
+ value,
+ }));
+}
+
const BASH_STRUCTURED_LAUNCH_SCRIPT =
`mapfile -d '' -t __ok_argv < <(printf '%s' "$1" | base64 -d); ` +
- `((\${#__ok_argv[@]})) || exit 1; "\${__ok_argv[@]}"; exec "$BASH" --login -i`;
+ `((\${#__ok_argv[@]})) || exit 1; ` +
+ `mapfile -d '' -t __ok_env < <(printf '%s' "$2" | base64 -d); ` +
+ `(for ((__ok_i = 0; __ok_i < \${#__ok_env[@]}; __ok_i += 2)); do __ok_slot="\${__ok_env[__ok_i + 1]}"; ` +
+ `export "\${__ok_env[__ok_i]}=\${!__ok_slot}"; done; exec "\${__ok_argv[@]}"); ` +
+ `for ((__ok_i = 1; __ok_i < \${#__ok_env[@]}; __ok_i += 2)); do unset "\${__ok_env[__ok_i]}"; done; ` +
+ `exec "$BASH" --login -i`;
+
+const TERMINAL_LAUNCH_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+export function isTerminalLaunchEnvName(name: string): boolean {
+ return (
+ TERMINAL_LAUNCH_ENV_NAME.test(name) &&
+ !name.toUpperCase().startsWith(TERMINAL_LAUNCH_ENV_SLOT_PREFIX)
+ );
+}
export function encodePowerShellCommand(script: string): string {
let binary = '';
@@ -75,6 +110,10 @@ export function resolveWindowsShellFamily(shell: string): WindowsShellFamily | n
return null;
}
+function isCmdSafeEnvValue(value: string): boolean {
+ return !Array.from(value).some((ch) => ch.charCodeAt(0) < 0x20) && !/["%!&|<>^()]/u.test(value);
+}
+
function isCmdSafeToken(value: string): boolean {
return (
value.length > 0 &&
@@ -128,14 +167,29 @@ export function composeWindowsShellLaunchArgs(
) {
throw new WindowsShellLaunchError('invalid-launch');
}
+ const NUL = String.fromCharCode(0);
+ const envEntries = Object.entries(launch.env ?? {});
+ if (envEntries.some(([key, value]) => !isTerminalLaunchEnvName(key) || value.includes(NUL))) {
+ throw new WindowsShellLaunchError('invalid-launch');
+ }
+ const loweredNames = new Set<string>();
+ for (const [key] of envEntries) {
+ const lowered = key.toLowerCase();
+ if (loweredNames.has(lowered)) throw new WindowsShellLaunchError('invalid-launch');
+ loweredNames.add(lowered);
+ }
+ const slots = terminalLaunchEnvSlots(launch.env);
if (family === 'bash') {
+ const argv = [launch.executable, ...launch.args];
+ const pairs = slots.flatMap(({ name, slot }) => [name, slot]);
return [
'--login',
'-i',
'-c',
BASH_STRUCTURED_LAUNCH_SCRIPT,
'bash',
- encodeUtf8Base64(`${[launch.executable, ...launch.args].join('\u0000')}\u0000`),
+ encodeUtf8Base64(`${argv.join(NUL)}${NUL}`),
+ ...(pairs.length === 0 ? [] : [encodeUtf8Base64(`${pairs.join(NUL)}${NUL}`)]),
];
}
const batchTarget = /\.(?:cmd|bat)$/iu.test(launch.executable);
@@ -144,11 +198,35 @@ export function composeWindowsShellLaunchArgs(
if (tokens.some((token) => !isCmdSafeToken(token))) {
throw new WindowsShellLaunchError('unsafe-argument');
}
- if (family === 'cmd') return `/K ${tokens.join(' ')}`;
+ if (family === 'cmd') {
+ if (slots.some(({ value }) => !isCmdSafeEnvValue(value))) {
+ throw new WindowsShellLaunchError('unsafe-argument');
+ }
+ const command = tokens.join(' ');
+ if (slots.length === 0) return `/K ${command}`;
+ const assign = slots.map(({ name, slot }) => `set "${name}=!${slot}!" & `).join('');
+ const clear = slots.map(({ slot }) => ` & set "${slot}="`).join('');
+ return `/K cmd /d /v:on /c "${assign}${command}"${clear}`;
+ }
}
- const script = `& ${psQuoteArg(launch.executable)}${launch.args
+ const command = `& ${psQuoteArg(launch.executable)}${launch.args
.map((arg) => ` ${psQuoteArg(arg)}`)
.join('')}`;
+ if (slots.length === 0) {
+ return ['-NoExit', '-EncodedCommand', encodePowerShellCommand(command)];
+ }
+ const names = slots.map(({ name }) => psQuoteArg(name)).join(', ');
+ const slotNames = slots.map(({ slot }) => psQuoteArg(slot)).join(', ');
+ const script =
+ `$__ok_names = @(${names}); $__ok_slots = @(${slotNames}); $__ok_prev = @{}; ` +
+ 'for ($__ok_i = 0; $__ok_i -lt $__ok_names.Length; $__ok_i++) { ' +
+ '$__ok_prev[$__ok_names[$__ok_i]] = [Environment]::GetEnvironmentVariable($__ok_names[$__ok_i]); ' +
+ "[Environment]::SetEnvironmentVariable($__ok_names[$__ok_i], [Environment]::GetEnvironmentVariable($__ok_slots[$__ok_i]), 'Process') }; " +
+ `try { ${command} } finally { ` +
+ 'for ($__ok_i = 0; $__ok_i -lt $__ok_names.Length; $__ok_i++) { ' +
+ "[Environment]::SetEnvironmentVariable($__ok_names[$__ok_i], $__ok_prev[$__ok_names[$__ok_i]], 'Process'); " +
+ "[Environment]::SetEnvironmentVariable($__ok_slots[$__ok_i], $null, 'Process') }; " +
+ 'Remove-Variable __ok_names, __ok_slots, __ok_prev, __ok_i -ErrorAction SilentlyContinue }';
return ['-NoExit', '-EncodedCommand', encodePowerShellCommand(script)];
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index a63a46876..b8ac7acfe 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -763,6 +763,7 @@ export {
type InstallState,
type IpcChannelReason,
type IpcChannelWithUrn,
+ isTerminalLaunchEnvName,
isWindowsShellFamily,
isWindowsShellLaunchFailureReason,
type LintFixPromptInput,
@@ -785,6 +786,7 @@ export {
type TerminalCli,
type TerminalCliInfo,
type TerminalLaunchCommand,
+ terminalLaunchEnvSlots,
URN_HTTP_ONLY,
URN_IPC_REGISTRY,
type UrnIpcLookup,
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 027884a40..437bd36a6 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -1369,6 +1369,7 @@ function ensureWindowManager() {
} as unknown as Parameters<typeof utilityProcess.fork>[2]);
return child as unknown as UtilityProcessLike;
},
+ terminalAuthAvailable: isTerminalAvailable(),
utilityEntryPath,
...(bundleCliMjsPath !== null
? {
@@ -1429,6 +1430,7 @@ function ensureWindowManager() {
otlpEndpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,
}),
...(singleFile !== undefined ? { singleFile, projectDir } : {}),
+ terminalAuthAvailable: isTerminalAvailable(),
});
let childRef: ReturnType<typeof spawn>;
startupWaterfall.mark('serverSpawned');
diff --git a/packages/desktop/src/main/resolve-detached-spawn-args.test.ts b/packages/desktop/src/main/resolve-detached-spawn-args.test.ts
index 4cd3faf5c..5f2ed3293 100644
--- a/packages/desktop/src/main/resolve-detached-spawn-args.test.ts
+++ b/packages/desktop/src/main/resolve-detached-spawn-args.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'vitest';
import {
type ResolveDetachedSpawnArgsInput,
resolveDetachedSpawnArgs,
+ TERMINAL_AUTH_ARG,
} from './resolve-detached-spawn-args.ts';
const PARENT_APP = '/Applications/OpenKnowledge.app';
@@ -25,6 +26,19 @@ function makeInput(
}
describe('resolveDetachedSpawnArgs', () => {
+ test('terminalAuthAvailable → the bundled CLI is told to advertise terminal sign-in', () => {
+ const { args } = resolveDetachedSpawnArgs(makeInput({ terminalAuthAvailable: true }));
+ expect(args).toContain(TERMINAL_AUTH_ARG);
+ expect(args.indexOf('start')).toBeLessThan(args.indexOf(TERMINAL_AUTH_ARG));
+ });
+
+ test('no terminal → the flag is absent, so the server advertises nothing it cannot honour', () => {
+ expect(resolveDetachedSpawnArgs(makeInput()).args).not.toContain(TERMINAL_AUTH_ARG);
+ expect(
+ resolveDetachedSpawnArgs(makeInput({ terminalAuthAvailable: false })).args,
+ ).not.toContain(TERMINAL_AUTH_ARG);
+ });
+
test('darwin packaged → file targets the helper bundle MacOS binary, not the parent execPath', () => {
const { file } = resolveDetachedSpawnArgs(makeInput());
expect(file).toBe(HELPER_BINARY);
diff --git a/packages/desktop/src/main/resolve-detached-spawn-args.ts b/packages/desktop/src/main/resolve-detached-spawn-args.ts
index 63a7c13b1..719ba5929 100644
--- a/packages/desktop/src/main/resolve-detached-spawn-args.ts
+++ b/packages/desktop/src/main/resolve-detached-spawn-args.ts
@@ -14,8 +14,11 @@ export interface ResolveDetachedSpawnArgsInput {
readonly env: Readonly<Record<string, string | undefined>>;
readonly singleFile?: string;
readonly projectDir?: string;
+ readonly terminalAuthAvailable?: boolean;
}
+export const TERMINAL_AUTH_ARG = '--terminal-auth';
+
export interface ResolvedDetachedSpawnArgs {
readonly file: string;
readonly args: readonly string[];
@@ -77,6 +80,7 @@ export function resolveDetachedSpawnArgs(
env,
singleFile,
projectDir,
+ terminalAuthAvailable,
} = input;
const file =
@@ -94,6 +98,7 @@ export function resolveDetachedSpawnArgs(
...(singleFile !== undefined
? ['--single-file', singleFile, '--project-dir', projectRoot]
: []),
+ ...(terminalAuthAvailable === true ? [TERMINAL_AUTH_ARG] : []),
];
const inheritedPath = readEnvPath(env);
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index e82f7cf71..c7fb42394 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -250,6 +250,7 @@ export interface WindowManagerDeps {
createKeepalive?(opts: { lockDir: string }): KeepaliveHandle;
rendererEntryPath: string;
rendererDevUrl?: string | null;
+ terminalAuthAvailable: boolean;
appVersion: string;
selfProtocolVersion?: number;
selfRuntimeVersion?: string;
@@ -1293,6 +1294,7 @@ export class WindowManager {
consentVersion: opts.consentVersion ?? 1,
...(reactShellDistDir !== null ? { reactShellDistDir } : {}),
...(localOpCliArgs ? { localOpCliArgs } : {}),
+ terminalAuthAvailable: this.deps.terminalAuthAvailable,
},
});
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.ts
index 0357f4905..e31029bef 100644
--- a/packages/desktop/src/utility/pty-host.ts
+++ b/packages/desktop/src/utility/pty-host.ts
@@ -4,11 +4,13 @@ import { userInfo } from 'node:os';
import { basename, win32 } from 'node:path';
import {
composeWindowsShellLaunchArgs,
+ isTerminalLaunchEnvName,
launchWithoutSupportFile,
OK_DESKTOP_TERMINAL_ENV,
resolveWindowsShellFamily,
shellSingleQuote,
type TerminalLaunchCommand,
+ terminalLaunchEnvSlots,
type WindowsShellFamily,
WindowsShellLaunchError,
type WindowsShellLaunchFailureReason,
@@ -28,9 +30,10 @@ import {
import {
commandWithManagedPath,
interactiveShellArgs,
+ quoteShellArg,
shellCommandFamily,
} from '../shared/terminal-shell.ts';
-import { getWindowsEnvValue, windowsWherePathArgs } from '../shared/windows-env.ts';
+import { getWindowsEnvValue, windowsPathKey, windowsWherePathArgs } from '../shared/windows-env.ts';
import {
materializeSupportFileSync,
TERMINAL_SUPPORT_FILE_ESCAPE_CODE,
@@ -239,6 +242,29 @@ function asIncomingMessage(raw: unknown): PtyHostIncomingMessage | null {
typeof (supportFile as Record<string, unknown>).contents === 'string' &&
((supportFile as Record<string, unknown>).contents as string).length <= 16_384 &&
(launch as Record<string, unknown>).executable === 'claude');
+ const launchEnv =
+ typeof launch === 'object' && launch !== null
+ ? (launch as Record<string, unknown>).env
+ : undefined;
+ const launchEnvValid =
+ launchEnv === undefined ||
+ (typeof launchEnv === 'object' &&
+ launchEnv !== null &&
+ !Array.isArray(launchEnv) &&
+ Object.entries(launchEnv as Record<string, unknown>).every(
+ ([key, value]) =>
+ isTerminalLaunchEnvName(key) &&
+ typeof value === 'string' &&
+ !value.includes(String.fromCharCode(0)),
+ ));
+ const launchPathPrepend =
+ typeof launch === 'object' && launch !== null
+ ? (launch as Record<string, unknown>).pathPrepend
+ : undefined;
+ const launchPathPrependValid =
+ launchPathPrepend === undefined ||
+ (Array.isArray(launchPathPrepend) &&
+ launchPathPrepend.every((dir) => typeof dir === 'string' && dir.length > 0));
const launchValid =
launch === undefined ||
typeof launch === 'string' ||
@@ -249,6 +275,8 @@ function asIncomingMessage(raw: unknown): PtyHostIncomingMessage | null {
((launch as Record<string, unknown>).args as unknown[]).every(
(arg) => typeof arg === 'string',
) &&
+ launchEnvValid &&
+ launchPathPrependValid &&
supportFileValid);
return typeof m.cwd === 'string' &&
typeof m.cols === 'number' &&
@@ -522,19 +550,74 @@ export function buildShellArgs(
: [];
}
const interactiveArgs = [...interactiveShellArgs(platform)];
- if (typeof launchCommand !== 'string' || launchCommand.length === 0) return interactiveArgs;
+ const command =
+ typeof launchCommand === 'object'
+ ? composeStructuredLaunch(shell, launchCommand)
+ : launchCommand;
+ if (typeof command !== 'string' || command.length === 0) return interactiveArgs;
+ const binDirs =
+ typeof launchCommand === 'object'
+ ? [...(launchCommand.pathPrepend ?? []), ...managedBinDirs]
+ : managedBinDirs;
+ const unsetStep =
+ typeof launchCommand === 'object'
+ ? unsetEnvStep(
+ shell,
+ terminalLaunchEnvSlots(launchCommand.env).map(({ slot }) => slot),
+ )
+ : '';
const quotedShell = shellSingleQuote(shell);
return [
...interactiveArgs,
'-c',
commandWithManagedPath(
shell,
- `${launchCommand}; exec ${quotedShell} ${interactiveArgs.join(' ')}`,
- managedBinDirs,
+ `${command}; ${unsetStep}exec ${quotedShell} ${interactiveArgs.join(' ')}`,
+ binDirs,
),
];
}
+function unsetEnvStep(shell: string, names: readonly string[]): string {
+ if (names.length === 0) return '';
+ return shellCommandFamily(shell) === 'fish'
+ ? `set -e ${names.join(' ')}; `
+ : `unset ${names.join(' ')}; `;
+}
+
+function composeStructuredLaunch(shell: string, launch: TerminalLaunchCommand): string {
+ const command = [launch.executable, ...launch.args]
+ .map((token) => quoteShellArg(shell, token))
+ .join(' ');
+ const slots = terminalLaunchEnvSlots(launch.env);
+ if (slots.length === 0) return command;
+ if (shellCommandFamily(shell) === 'fish') {
+ const assigns = slots.map(({ name, slot }) => `set -lx ${name} "$${slot}"; `).join('');
+ return `begin; ${assigns}${command}; end`;
+ }
+ const assigns = slots.map(({ name, slot }) => `${name}="$${slot}"`).join(' ');
+ return `(export ${assigns}; exec ${command})`;
+}
+
+export function buildLaunchEnv(
+ platform: NodeJS.Platform,
+ shellEnv: Record<string, string>,
+ launchCommand: string | TerminalLaunchCommand | undefined,
+): Record<string, string> {
+ if (typeof launchCommand !== 'object') return shellEnv;
+ const env = { ...shellEnv };
+ for (const { slot, value } of terminalLaunchEnvSlots(launchCommand.env)) env[slot] = value;
+ const pathPrepend = launchCommand.pathPrepend ?? [];
+ if (platform !== 'win32' || pathPrepend.length === 0) return env;
+ const key = windowsPathKey(env);
+ const existing = env[key];
+ env[key] = [
+ ...pathPrepend,
+ ...(existing === undefined || existing === '' ? [] : [existing]),
+ ].join(';');
+ return env;
+}
+
export function buildShellEnv(
parentEnv: Record<string, string | undefined>,
options: {
@@ -755,7 +838,7 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
cols: message.cols,
rows: message.rows,
cwd: message.cwd,
- env: shellEnv,
+ env: buildLaunchEnv(platform, shellEnv, launchCommand),
encoding: 'utf8',
};
let pty: PtyProcessLike;
diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.ts
index feb1102df..1699b7572 100644
--- a/packages/desktop/src/utility/server-entry.ts
+++ b/packages/desktop/src/utility/server-entry.ts
@@ -23,6 +23,7 @@ export interface UtilityInitMessage {
| 'maxDebounce'
| 'localOpCliArgs'
| 'reactShellDistDir'
+ | 'terminalAuthAvailable'
> & {
didEnsureGit?: boolean;
consentVersion?: number;
@@ -236,6 +237,7 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {
ensurePiAcpBridge: (agentCwd, approvedCanonicalCwd) =>
ensurePiBridge(agentCwd, undefined, undefined, undefined, approvedCanonicalCwd),
serveContentAssets: true,
+ terminalAuthAvailable: msg.opts.terminalAuthAvailable === true,
...(msg.opts.reactShellDistDir ? { reactShellDistDir: msg.opts.reactShellDistDir } : {}),
};
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index cb46b3e9e..f688b2261 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -181,6 +181,7 @@ function buildEnv(): TestEnv {
},
utilityEntryPath: '/fake/utility-entry.js',
rendererEntryPath: '/fake/renderer/index.html',
+ terminalAuthAvailable: true,
appVersion: '9.9.9-test',
setTimeout: (cb, ms) => {
timers.push({ cb, ms });
@@ -272,6 +273,7 @@ describe('WindowManager', () => {
didEnsureGit: false,
consentVersion: 1,
reactShellDistDir: '/fake/renderer',
+ terminalAuthAvailable: true,
},
});
@@ -335,6 +337,25 @@ describe('WindowManager', () => {
await promise;
});
+ test('createProjectWindow tells the server when this host has no terminal to sign in with', async () => {
+ const noPtyEnv = buildEnv();
+ noPtyEnv.deps.terminalAuthAvailable = false;
+ const wm = new WindowManager(noPtyEnv.deps);
+ const promise = wm.createProjectWindow({ projectPath: '/tmp/no-pty-project' });
+
+ const utility = noPtyEnv.utilities[0];
+ if (!utility) throw new Error('utility not forked');
+ expect(utility.postMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'init',
+ opts: expect.objectContaining({ terminalAuthAvailable: false }),
+ }),
+ );
+
+ utility.fire({ type: 'ready', port: 51237, apiOrigin: 'http://localhost:51237' });
+ await promise;
+ });
+
test('createProjectWindow OMITS reactShellDistDir in dev mode (rendererDevUrl set)', async () => {
const devEnv = buildEnv();
devEnv.deps.rendererDevUrl = 'http://localhost:5173/';
@@ -353,6 +374,7 @@ describe('WindowManager', () => {
host: '127.0.0.1',
didEnsureGit: false,
consentVersion: 1,
+ terminalAuthAvailable: true,
},
});
diff --git a/packages/desktop/tests/smoke/terminal-dock.e2e.ts b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
index 7a8860eb8..c808b1ab5 100644
--- a/packages/desktop/tests/smoke/terminal-dock.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-dock.e2e.ts
@@ -982,7 +982,7 @@ test.describe('Docked terminal — live Electron', () => {
await page.evaluate(() => {
window.dispatchEvent(
new CustomEvent('open-knowledge:terminal-launch', {
- detail: { prompt: '', cli: 'claude', stage: false },
+ detail: { kind: 'cli', prompt: '', cli: 'claude', stage: false },
}),
);
});
@@ -1015,7 +1015,7 @@ test.describe('Docked terminal — live Electron', () => {
await page.evaluate(() => {
window.dispatchEvent(
new CustomEvent('open-knowledge:terminal-launch', {
- detail: { prompt: '', cli: 'claude', stage: false },
+ detail: { kind: 'cli', prompt: '', cli: 'claude', stage: false },
}),
);
});
@@ -1089,7 +1089,7 @@ test.describe('Docked terminal — live Electron', () => {
await page.evaluate(() => {
window.dispatchEvent(
new CustomEvent('open-knowledge:terminal-launch', {
- detail: { prompt: '', cli: 'claude', stage: false },
+ detail: { kind: 'cli', prompt: '', cli: 'claude', stage: false },
}),
);
});
diff --git a/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts b/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts
index 6a3499e4b..ca43b7eb1 100644
--- a/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts
+++ b/packages/desktop/tests/smoke/terminal-launch-argv.e2e.ts
@@ -226,7 +226,7 @@ test.describe('Docked terminal launch — composed argv', () => {
await page.evaluate((prompt) => {
window.dispatchEvent(
new CustomEvent('open-knowledge:terminal-launch', {
- detail: { prompt, cli: 'claude', stage: false },
+ detail: { kind: 'cli', prompt, cli: 'claude', stage: false },
}),
);
}, s.prompt);
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
index 69f38e2f4..5c9c79370 100644
--- a/packages/desktop/tests/utility/pty-host.test.ts
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -15,6 +15,7 @@ vi.mock('node:os', async (importOriginal) => {
import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';
import {
+ buildLaunchEnv,
buildShellArgs,
buildShellEnv,
type HostReapProcess,
@@ -953,6 +954,88 @@ describe('setupPtyHost — incoming message validation (asIncomingMessage guard)
]);
});
+ test('accepts a structured POSIX launch, quotes its argv and hands its env to the login alone', () => {
+ const h = makeHarness();
+ h.fireRaw({
+ type: 'create',
+ ptyId: 'p1',
+ cwd: '/x',
+ cols: 80,
+ rows: 24,
+ launchCommand: {
+ executable: '/rt/bin/npx',
+ args: ['-y', '@augmentcode/[email protected]', '--acp', 'login'],
+ env: { AUGGIE_LOGIN_FLOW: 'terminal' },
+ pathPrepend: ['/rt/bin'],
+ },
+ });
+ expect(h.spawnCalls).toHaveLength(1);
+ const [managedBinDir] = buildShellEnv({}, { platform: 'darwin' }).managedBinDirs;
+ expect(h.spawnCalls[0]?.args).toEqual([
+ '-l',
+ '-i',
+ '-c',
+ `case ":$PATH:" in *:'${managedBinDir}':*) ;; *) PATH='${managedBinDir}'"\${PATH:+:$PATH}" ;; esac; case ":$PATH:" in *:'/rt/bin':*) ;; *) PATH='/rt/bin'"\${PATH:+:$PATH}" ;; esac; export PATH; (export AUGGIE_LOGIN_FLOW="$OK_TERMINAL_LAUNCH_ENV_0"; exec '/rt/bin/npx' '-y' '@augmentcode/[email protected]' '--acp' 'login'); unset OK_TERMINAL_LAUNCH_ENV_0; exec '/bin/zsh' -l -i`,
+ ]);
+ expect(h.spawnCalls[0]?.options.env?.OK_TERMINAL_LAUNCH_ENV_0).toBe('terminal');
+ expect(h.spawnCalls[0]?.options.env).not.toHaveProperty('AUGGIE_LOGIN_FLOW');
+ expect(h.spawnCalls[0]?.args).not.toContain('terminal');
+ expect(h.spawnCalls[0]?.options.env?.PATH).not.toContain('/rt/bin');
+ });
+
+ test('drops a structured launch whose env names, values or PATH dirs are malformed', () => {
+ const h = makeHarness();
+ h.fireRaw({
+ type: 'create',
+ ptyId: 'p1',
+ cwd: '/x',
+ cols: 80,
+ rows: 24,
+ launchCommand: { executable: 'agent', args: ['login'], env: { A: 1 } },
+ });
+ h.fireRaw({
+ type: 'create',
+ ptyId: 'p3',
+ cwd: '/x',
+ cols: 80,
+ rows: 24,
+ launchCommand: { executable: 'agent', args: ['login'], env: { '--split-string': 'x' } },
+ });
+ h.fireRaw({
+ type: 'create',
+ ptyId: 'p5',
+ cwd: '/x',
+ cols: 80,
+ rows: 24,
+ launchCommand: {
+ executable: 'agent',
+ args: ['login'],
+ env: { OK_TERMINAL_LAUNCH_ENV_0: 'the slot the launch itself uses' },
+ },
+ });
+ h.fireRaw({
+ type: 'create',
+ ptyId: 'p4',
+ cwd: '/x',
+ cols: 80,
+ rows: 24,
+ launchCommand: {
+ executable: 'agent',
+ args: ['login'],
+ env: { OK: `a${String.fromCharCode(0)}b` },
+ },
+ });
+ h.fireRaw({
+ type: 'create',
+ ptyId: 'p2',
+ cwd: '/x',
+ cols: 80,
+ rows: 24,
+ launchCommand: { executable: 'agent', args: ['login'], pathPrepend: [''] },
+ });
+ expect(h.spawnCalls).toHaveLength(0);
+ });
+
test('accepts a structured Windows launch and composes it after shell resolution', () => {
const h = makeHarness({
platform: 'win32',
@@ -1180,6 +1263,68 @@ describe('buildShellArgs', () => {
]);
});
+ test('a structured POSIX launch reasserts its own dirs ahead of the managed ones', () => {
+ expect(
+ buildShellArgs(
+ 'linux',
+ '/bin/bash',
+ { executable: '/rt/bin/npx', args: ['-y', 'pkg@1', 'login'], pathPrepend: ['/rt/bin'] },
+ ['/managed/bin'],
+ ),
+ ).toEqual([
+ '-i',
+ '-c',
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: shell parameter expansion in an expected command string, not a JS template placeholder
+ "case \":$PATH:\" in *:'/managed/bin':*) ;; *) PATH='/managed/bin'\"${PATH:+:$PATH}\" ;; esac; case \":$PATH:\" in *:'/rt/bin':*) ;; *) PATH='/rt/bin'\"${PATH:+:$PATH}\" ;; esac; export PATH; '/rt/bin/npx' '-y' 'pkg@1' 'login'; exec '/bin/bash' -i",
+ ]);
+ });
+
+ test('several env values map each slot onto the same name in the script and in the spawn env', () => {
+ const h = makeHarness();
+ const env = { ZDOTDIR: '/agent/zdot', AUGGIE_HOME: '/agent/home' };
+ h.fireRaw({
+ type: 'create',
+ ptyId: 'p1',
+ cwd: '/x',
+ cols: 80,
+ rows: 24,
+ launchCommand: { executable: 'agent', args: ['login'], env },
+ });
+ const call = h.spawnCalls[0];
+ if (!call) throw new Error('no spawn');
+ const script = call.args[3] ?? '';
+ expect(script).toContain(
+ `(export ZDOTDIR="$OK_TERMINAL_LAUNCH_ENV_0" AUGGIE_HOME="$OK_TERMINAL_LAUNCH_ENV_1"; exec 'agent' 'login'); unset OK_TERMINAL_LAUNCH_ENV_0 OK_TERMINAL_LAUNCH_ENV_1; exec`,
+ );
+ const pairs = [...script.matchAll(/(\w+)="\$(OK_TERMINAL_LAUNCH_ENV_\d+)"/g)].map((match) => [
+ match[1] ?? '',
+ match[2] ?? '',
+ ]);
+ expect(pairs).toEqual([
+ ['ZDOTDIR', 'OK_TERMINAL_LAUNCH_ENV_0'],
+ ['AUGGIE_HOME', 'OK_TERMINAL_LAUNCH_ENV_1'],
+ ]);
+ for (const [name, slot] of pairs) {
+ expect(call.options.env?.[slot]).toBe(env[name as keyof typeof env]);
+ expect(call.options.env).not.toHaveProperty(name);
+ }
+ });
+
+ test('a structured launch under fish uses fish quoting for every token', () => {
+ expect(
+ buildShellArgs(
+ 'linux',
+ '/usr/bin/fish',
+ { executable: 'agent', args: ["it\\'s", 'trailing\\'], env: { A: "x'y" } },
+ [],
+ ),
+ ).toEqual([
+ '-i',
+ '-c',
+ `begin; set -lx A "$OK_TERMINAL_LAUNCH_ENV_0"; 'agent' 'it\\\\\\'s' 'trailing\\\\'; end; set -e OK_TERMINAL_LAUNCH_ENV_0; exec '/usr/bin/fish' -i`,
+ ]);
+ });
+
test('uses fish list syntax for the reassert when the terminal shell is fish', () => {
expect(buildShellArgs('linux', '/usr/bin/fish', 'claude', ['/managed/bin'])).toEqual([
'-i',
@@ -1918,3 +2063,51 @@ describe('installHostReaping', () => {
expect(proc.exitCodes).toEqual([0, 0]);
});
});
+
+describe('buildLaunchEnv', () => {
+ test('a string launch keeps the shell env as is', () => {
+ const env = { PATH: '/usr/bin', A: '1' };
+ expect(buildLaunchEnv('darwin', env, "codex 'hi'")).toBe(env);
+ });
+
+ test('a structured launch parks its env in slot variables and leaves PATH to the command on POSIX', () => {
+ expect(
+ buildLaunchEnv(
+ 'darwin',
+ { PATH: '/usr/bin', A: '1' },
+ { executable: 'x', args: [], env: { B: '2' }, pathPrepend: ['/rt/bin'] },
+ ),
+ ).toEqual({ PATH: '/usr/bin', A: '1', OK_TERMINAL_LAUNCH_ENV_0: '2' });
+ });
+
+ test("a method env name never reaches the shell's startup environment", () => {
+ const env = buildLaunchEnv(
+ 'darwin',
+ { PATH: '/usr/bin', HOME: '/Users/me' },
+ {
+ executable: 'agent',
+ args: ['login'],
+ env: { ZDOTDIR: '/tmp/agent-owned', HOME: '/tmp/agent-owned', BASH_ENV: '/tmp/x.sh' },
+ },
+ );
+ expect(env).toEqual({
+ PATH: '/usr/bin',
+ HOME: '/Users/me',
+ OK_TERMINAL_LAUNCH_ENV_0: '/tmp/agent-owned',
+ OK_TERMINAL_LAUNCH_ENV_1: '/tmp/agent-owned',
+ OK_TERMINAL_LAUNCH_ENV_2: '/tmp/x.sh',
+ });
+ expect(env).not.toHaveProperty('ZDOTDIR');
+ expect(env).not.toHaveProperty('BASH_ENV');
+ });
+
+ test('a structured launch puts its PATH dirs first on Windows', () => {
+ expect(
+ buildLaunchEnv(
+ 'win32',
+ { Path: 'C:\\Windows', A: '1' },
+ { executable: 'x', args: [], pathPrepend: ['C:\\rt\\bin'] },
+ ),
+ ).toEqual({ Path: 'C:\\rt\\bin;C:\\Windows', A: '1' });
+ });
+});
diff --git a/packages/server/src/acp/terminal-auth.test.ts b/packages/server/src/acp/terminal-auth.test.ts
new file mode 100644
index 000000000..b7f7a75e9
--- /dev/null
+++ b/packages/server/src/acp/terminal-auth.test.ts
@@ -0,0 +1,151 @@
+import { expect, test } from 'vitest';
+import { terminalAuthBaseFor, terminalAuthLaunch, threadAuthMethods } from './terminal-auth.ts';
+
+const PROCESS_ENV = { PATH: '/usr/bin', HOME: '/Users/me', LANG: 'en_US.UTF-8' };
+const NUL = String.fromCharCode(0);
+
+const MANAGED_NPX = {
+ cmd: '/Users/me/.ok/runtimes/cache/node/node-v24/bin/npx',
+ args: ['-y', '@augmentcode/[email protected]', '--acp'],
+ env: { ...PROCESS_ENV, PATH: '/Users/me/.ok/runtimes/cache/node/node-v24/bin:/usr/bin' },
+ kind: 'npx' as const,
+};
+
+const TERMINAL_METHODS = [
+ {
+ id: 'auggie-login',
+ name: 'Log in with Auggie',
+ description: 'Runs the login flow in a terminal.',
+ type: 'terminal',
+ args: ['login'],
+ env: { AUGGIE_LOGIN_FLOW: 'terminal' },
+ },
+ { id: 'oauth', name: 'Sign in with Auggie', type: 'agent' },
+ { id: 'token', name: 'API token', type: 'env_var', vars: [{ name: 'AUGGIE_TOKEN' }] },
+] as never;
+
+test('a managed-runtime launch puts its bin directory ahead of the terminal PATH', () => {
+ expect(terminalAuthBaseFor(MANAGED_NPX, PROCESS_ENV)).toEqual({
+ executable: MANAGED_NPX.cmd,
+ args: ['-y', '@augmentcode/[email protected]', '--acp'],
+ env: {},
+ pathPrepend: ['/Users/me/.ok/runtimes/cache/node/node-v24/bin'],
+ });
+});
+
+test('only the agent overlay survives into the launch env, never the inherited process env or PATH', () => {
+ const base = terminalAuthBaseFor(
+ {
+ cmd: 'auggie',
+ args: ['--acp'],
+ env: {
+ ...PROCESS_ENV,
+ PATH: '/opt/agent/bin:/usr/bin',
+ AUGGIE_HOME: '/Users/me/.auggie',
+ npm_config_cache: '/Users/me/.ok/runtimes/cache/npm',
+ 'BAD NAME': 'dropped',
+ BAD_VALUE: `x${NUL}y`,
+ },
+ kind: 'custom',
+ },
+ PROCESS_ENV,
+ );
+ expect(base).toEqual({
+ executable: 'auggie',
+ args: ['--acp'],
+ env: { AUGGIE_HOME: '/Users/me/.auggie', npm_config_cache: '/Users/me/.ok/runtimes/cache/npm' },
+ pathPrepend: [],
+ });
+});
+
+test('the persisted method only says that a terminal launch exists', () => {
+ const base = terminalAuthBaseFor(
+ { cmd: 'auggie', args: ['--acp'], env: { ...PROCESS_ENV, AUGGIE_HOME: '/x' }, kind: 'custom' },
+ PROCESS_ENV,
+ );
+ expect(threadAuthMethods(TERMINAL_METHODS, base)).toEqual([
+ {
+ id: 'auggie-login',
+ name: 'Log in with Auggie',
+ description: 'Runs the login flow in a terminal.',
+ kind: 'terminal',
+ terminalLaunchAvailable: true,
+ },
+ { id: 'oauth', name: 'Sign in with Auggie', kind: 'agent' },
+ { id: 'token', name: 'API token', kind: 'env_var' },
+ ]);
+ expect(JSON.stringify(threadAuthMethods(TERMINAL_METHODS, base))).not.toContain('/x');
+ expect(JSON.stringify(threadAuthMethods(TERMINAL_METHODS, base))).not.toContain('--acp');
+});
+
+test('the live launch carries the agent overlay and the method env', () => {
+ const base = terminalAuthBaseFor(
+ { cmd: 'auggie', args: ['--acp'], env: { ...PROCESS_ENV, AUGGIE_HOME: '/x' }, kind: 'custom' },
+ PROCESS_ENV,
+ );
+ expect(terminalAuthLaunch(TERMINAL_METHODS, base, 'auggie-login')).toEqual({
+ executable: 'auggie',
+ args: ['--acp', 'login'],
+ env: { AUGGIE_HOME: '/x', AUGGIE_LOGIN_FLOW: 'terminal' },
+ pathPrepend: [],
+ });
+ expect(terminalAuthLaunch(TERMINAL_METHODS, base, 'oauth')).toBeNull();
+ expect(terminalAuthLaunch(TERMINAL_METHODS, base, 'missing')).toBeNull();
+ expect(terminalAuthLaunch(TERMINAL_METHODS, null, 'auggie-login')).toBeNull();
+});
+
+test('hostile env names and NUL values from the method are dropped', () => {
+ const base = terminalAuthBaseFor(
+ { cmd: 'agent', args: [], env: PROCESS_ENV, kind: 'binary' },
+ PROCESS_ENV,
+ );
+ const methods = [
+ {
+ id: 'cli',
+ name: 'CLI',
+ type: 'terminal',
+ env: {
+ 'X; Start-Process calc; $y': '1',
+ '--split-string': 'evil',
+ 'A-B': '1',
+ OK_TERMINAL_LAUNCH_ENV_0: 'reserved for the launch itself',
+ ok_terminal_launch_env_1: 'the same slot on a case-folding shell',
+ OK_NAME: 'kept',
+ WITH_NUL: `a${NUL}b`,
+ },
+ },
+ ] as never;
+ expect(terminalAuthLaunch(methods, base, 'cli')?.env).toEqual({ OK_NAME: 'kept' });
+});
+
+test('a terminal method without a known launch stays a description', () => {
+ expect(
+ threadAuthMethods(
+ [{ id: 'cli', name: 'CLI login', type: 'terminal', args: ['login'] }] as never,
+ null,
+ ),
+ ).toEqual([{ id: 'cli', name: 'CLI login', kind: 'terminal' }]);
+});
+
+test('malformed method entries and non-string fields are dropped', () => {
+ expect(
+ threadAuthMethods(
+ [
+ null,
+ { id: 7, name: 'x' },
+ { id: 'ok', name: 'Fine', type: 'terminal', args: ['login', 3] },
+ ] as never,
+ terminalAuthBaseFor(
+ { cmd: 'agent', args: [], env: PROCESS_ENV, kind: 'binary' },
+ PROCESS_ENV,
+ ),
+ ),
+ ).toEqual([
+ {
+ id: 'ok',
+ name: 'Fine',
+ kind: 'terminal',
+ terminalLaunchAvailable: true,
+ },
+ ]);
+});
diff --git a/packages/server/src/acp/terminal-auth.ts b/packages/server/src/acp/terminal-auth.ts
new file mode 100644
index 000000000..1592e292c
--- /dev/null
+++ b/packages/server/src/acp/terminal-auth.ts
@@ -0,0 +1,109 @@
+import { dirname, isAbsolute } from 'node:path';
+import type { InitializeResponse } from '@agentclientprotocol/sdk';
+import { isTerminalLaunchEnvName } from '@inkeep/open-knowledge-core';
+import type {
+ ThreadAuthMethod,
+ ThreadAuthTerminalLaunch,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import type { ResolvedLaunch } from './launch.ts';
+
+export type TerminalAuthBase = ThreadAuthTerminalLaunch;
+
+const NUL = String.fromCharCode(0);
+
+export function terminalAuthBaseFor(
+ launch: Pick<ResolvedLaunch, 'cmd' | 'args' | 'env' | 'kind'>,
+ processEnv: NodeJS.ProcessEnv = process.env,
+): TerminalAuthBase {
+ const managedRuntime = (launch.kind === 'npx' || launch.kind === 'uvx') && isAbsolute(launch.cmd);
+ const env: Record<string, string> = {};
+ for (const [key, value] of Object.entries(launch.env)) {
+ if (key.toLowerCase() === 'path' || !isTerminalLaunchEnvName(key)) continue;
+ if (value.includes(NUL)) continue;
+ if (processEnv[key] !== value) env[key] = value;
+ }
+ return {
+ executable: launch.cmd,
+ args: [...launch.args],
+ env,
+ pathPrepend: managedRuntime ? [dirname(launch.cmd)] : [],
+ };
+}
+
+function stringList(value: unknown): string[] {
+ return Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === 'string')
+ : [];
+}
+
+function envRecord(value: unknown): Record<string, string> {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return {};
+ const out: Record<string, string> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ if (typeof entry !== 'string' || entry.includes(NUL)) continue;
+ if (!isTerminalLaunchEnvName(key)) continue;
+ out[key] = entry;
+ }
+ return out;
+}
+
+type RawAuthMethod = {
+ id?: unknown;
+ name?: unknown;
+ description?: unknown;
+ type?: unknown;
+ args?: unknown;
+ env?: unknown;
+};
+
+function rawMethod(value: unknown): RawAuthMethod | null {
+ return typeof value === 'object' && value !== null ? (value as RawAuthMethod) : null;
+}
+
+function terminalLaunchFor(
+ method: RawAuthMethod,
+ base: TerminalAuthBase,
+): ThreadAuthTerminalLaunch {
+ return {
+ executable: base.executable,
+ args: [...base.args, ...stringList(method.args)],
+ env: { ...base.env, ...envRecord(method.env) },
+ pathPrepend: [...base.pathPrepend],
+ };
+}
+
+export function threadAuthMethods(
+ methods: InitializeResponse['authMethods'],
+ base: TerminalAuthBase | null,
+): ThreadAuthMethod[] {
+ return (methods ?? []).flatMap((m) => {
+ const method = rawMethod(m);
+ if (method === null) return [];
+ const { id, name, description, type } = method;
+ if (typeof id !== 'string' || typeof name !== 'string') return [];
+ const terminalLaunchAvailable = type === 'terminal' && base !== null;
+ return [
+ {
+ id,
+ name,
+ ...(typeof description === 'string' ? { description } : {}),
+ ...(typeof type === 'string' ? { kind: type } : {}),
+ ...(terminalLaunchAvailable ? { terminalLaunchAvailable: true as const } : {}),
+ },
+ ];
+ });
+}
+
+export function terminalAuthLaunch(
+ methods: InitializeResponse['authMethods'],
+ base: TerminalAuthBase | null,
+ methodId: string,
+): ThreadAuthTerminalLaunch | null {
+ if (base === null) return null;
+ for (const m of methods ?? []) {
+ const method = rawMethod(m);
+ if (method === null || method.id !== methodId || method.type !== 'terminal') continue;
+ return terminalLaunchFor(method, base);
+ }
+ return null;
+}
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
index ae514cb16..f8e2aa99b 100644
--- a/packages/server/src/acp/thread-manager.integration.test.ts
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -102,6 +102,7 @@ function makeManager(
log?: PinoLogger;
projectSkillSourceDir?: string | null;
autoApproveOkTools?: () => boolean;
+ terminalAuthAvailable?: boolean;
},
): AcpThreadManager {
const manager = new AcpThreadManager({
@@ -7223,3 +7224,113 @@ describe('launch failure diagnostics and npx cache recovery', () => {
expect(existsSync(join(localDir, ACP_LAUNCH_FAILURE_LOG))).toBe(false);
}, 30_000);
});
+
+function writeTerminalAuthAgentEntry(
+ localDir: string,
+ id: string,
+ env: Record<string, string>,
+ capsFile: string,
+): string {
+ const agentPath = join(localDir, `${id}.mjs`);
+ writeFileSync(
+ agentPath,
+ `
+import { writeFileSync } from 'node:fs';
+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ if (msg.method === 'initialize') {
+ writeFileSync(${JSON.stringify(capsFile)}, JSON.stringify(msg.params.clientCapabilities ?? {}));
+ write({
+ jsonrpc: '2.0',
+ id: msg.id,
+ result: {
+ protocolVersion: 1,
+ agentCapabilities: {},
+ authMethods: [
+ { type: 'terminal', id: 'cli-login', name: 'CLI login', args: ['login'], env: { FROM_METHOD: '1' } },
+ ],
+ },
+ });
+ } else if (msg.method === 'session/new') {
+ write({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: 'sign in required' } });
+ } else if (msg.id !== undefined) {
+ write({ jsonrpc: '2.0', id: msg.id, result: {} });
+ }
+ }
+});
+`,
+ );
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath], env }]),
+ );
+ return agentPath;
+}
+
+describe('terminal sign-in methods', () => {
+ test('the persisted method only flags the launch, and the live launch carries the env', async () => {
+ const localDir = tmp();
+ const capsFile = join(localDir, 'caps.json');
+ const agentPath = writeTerminalAuthAgentEntry(
+ localDir,
+ 'term-auth',
+ { FIXTURE_HOME: '/tmp/fixture-home' },
+ capsFile,
+ );
+ const manager = makeManager(tmp(), localDir, { terminalAuthAvailable: true });
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'term-auth' } });
+ const statuses: StatusEvent[] = [];
+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));
+ await waitUntil(
+ () => statuses.some((event) => event.status === 'auth_required'),
+ 15_000,
+ 'sign in',
+ );
+ const failure = [...statuses]
+ .reverse()
+ .find((event) => event.status === 'auth_required')?.failure;
+ expect(failure?.authMethods).toEqual([
+ {
+ id: 'cli-login',
+ name: 'CLI login',
+ kind: 'terminal',
+ terminalLaunchAvailable: true,
+ },
+ ]);
+ expect(JSON.stringify(failure)).not.toContain('fixture-home');
+ expect(manager.terminalAuthLaunch(info.threadId, 'cli-login')).toEqual({
+ executable: 'node',
+ args: [agentPath, 'login'],
+ env: { FIXTURE_HOME: '/tmp/fixture-home', FROM_METHOD: '1' },
+ pathPrepend: [],
+ });
+ expect(() => manager.terminalAuthLaunch(info.threadId, 'missing')).toThrow(
+ 'no terminal sign-in',
+ );
+ expect(JSON.parse(readFileSync(capsFile, 'utf8'))).toMatchObject({ auth: { terminal: true } });
+ }, 20_000);
+
+ test('a host without a terminal does not advertise terminal sign-in', async () => {
+ const localDir = tmp();
+ const capsFile = join(localDir, 'caps.json');
+ writeTerminalAuthAgentEntry(localDir, 'term-auth', {}, capsFile);
+ const manager = makeManager(tmp(), localDir);
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'term-auth' } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'auth_required',
+ 15_000,
+ 'sign in',
+ );
+ expect(JSON.parse(readFileSync(capsFile, 'utf8'))).not.toHaveProperty('auth');
+ }, 20_000);
+});
diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.ts
index f76937166..61d6a508c 100644
--- a/packages/server/src/acp/thread-manager.ts
+++ b/packages/server/src/acp/thread-manager.ts
@@ -48,7 +48,7 @@ import type {
QueuedMessage,
SteerMessage,
ThreadAgentInfo,
- ThreadAuthMethod,
+ ThreadAuthTerminalLaunch,
ThreadChatGrant,
ThreadEvent,
ThreadFailureDetail,
@@ -147,6 +147,12 @@ import {
loadCustomAgents,
registryPlatformKey,
} from './registry.ts';
+import {
+ type TerminalAuthBase,
+ terminalAuthBaseFor,
+ terminalAuthLaunch,
+ threadAuthMethods,
+} from './terminal-auth.ts';
import { AcpTerminalSet } from './terminals.ts';
import { type PersistedThreadMeta, ThreadPersistenceStore } from './thread-persistence.ts';
import { clampThreadTitle, deriveThreadTitle } from './thread-title.ts';
@@ -305,6 +311,7 @@ interface ThreadRecord {
child: ChildProcess | null;
conn: ClientConnection | null;
lastInit: InitializeResponse | null;
+ terminalAuthBase: TerminalAuthBase | null;
sessionId: string | null;
agentSessionId: string;
events: ThreadEvent[];
@@ -414,6 +421,7 @@ export interface AcpThreadManagerOptions {
};
resolveLoginShellPath?: () => Promise<string | null>;
projectSkillSourceDir?: string | null;
+ terminalAuthAvailable?: boolean;
log: PinoLogger;
maxThreads?: number;
idleReapMs?: number;
@@ -649,6 +657,7 @@ export class AcpThreadManager {
child: null,
conn: null,
lastInit: null,
+ terminalAuthBase: null,
sessionId: null,
agentSessionId: `acp-${threadId}`,
events: [],
@@ -826,6 +835,7 @@ export class AcpThreadManager {
loginShellPath,
});
+ record.terminalAuthBase = terminalAuthBaseFor(launch);
launch = applyLaunchContextWindow(
launch,
record.agentRef.id,
@@ -1059,6 +1069,7 @@ export class AcpThreadManager {
clientCapabilities: {
fs: { readTextFile: true, writeTextFile: true },
terminal: true,
+ ...(this.opts.terminalAuthAvailable === true ? { auth: { terminal: true } } : {}),
session: { configOptions: { boolean: {} } },
},
});
@@ -1924,7 +1935,7 @@ export class AcpThreadManager {
reason: 'auth-required',
agentMessage: agentErrorMessage(err),
machineDetail: authMachineDetail(err, record),
- authMethods: threadAuthMethods(init.authMethods),
+ authMethods: threadAuthMethods(init.authMethods, record.terminalAuthBase),
});
} else {
const tail = await stderrTailDetail(record);
@@ -2231,6 +2242,15 @@ export class AcpThreadManager {
}
}
+ terminalAuthLaunch(threadId: string, methodId: string): ThreadAuthTerminalLaunch {
+ const t = this.mustGet(threadId);
+ const launch = terminalAuthLaunch(t.lastInit?.authMethods, t.terminalAuthBase, methodId);
+ if (launch === null) {
+ throw new ThreadOpError('not-ready', 'this agent offers no terminal sign-in by that name');
+ }
+ return launch;
+ }
+
async authenticateThread(threadId: string, methodId: string): Promise<ThreadInfo> {
if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
const t = this.mustGet(threadId);
@@ -2271,7 +2291,7 @@ export class AcpThreadManager {
reason: 'auth-required',
agentMessage: message,
machineDetail: authMachineDetail(err, t),
- authMethods: threadAuthMethods(init.authMethods),
+ authMethods: threadAuthMethods(init.authMethods, t.terminalAuthBase),
});
throw new ThreadOpError('not-ready', message);
}
@@ -2299,7 +2319,7 @@ export class AcpThreadManager {
reason: 'auth-required',
agentMessage: agentErrorMessage(err),
machineDetail: authMachineDetail(err, t),
- authMethods: threadAuthMethods(init.authMethods),
+ authMethods: threadAuthMethods(init.authMethods, t.terminalAuthBase),
});
}
throw err;
@@ -2774,7 +2794,7 @@ export class AcpThreadManager {
reason: 'auth-required',
agentMessage: agentErrorMessage(err),
machineDetail: authMachineDetail(err, t),
- authMethods: threadAuthMethods(t.lastInit?.authMethods),
+ authMethods: threadAuthMethods(t.lastInit?.authMethods, t.terminalAuthBase),
});
return;
}
@@ -3655,6 +3675,7 @@ function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {
child: null,
conn: null,
lastInit: null,
+ terminalAuthBase: null,
sessionId: meta.sessionId,
agentSessionId: `acp-${meta.info.threadId}`,
events: [],
@@ -3828,24 +3849,3 @@ function resumableFromCapabilities(init: InitializeResponse): boolean {
const caps = init.agentCapabilities;
return caps?.sessionCapabilities?.resume != null || caps?.loadSession === true;
}
-
-function threadAuthMethods(methods: InitializeResponse['authMethods']): ThreadAuthMethod[] {
- return (methods ?? []).flatMap((m) => {
- if (typeof m !== 'object' || m === null) return [];
- const { id, name, description, type } = m as {
- id?: unknown;
- name?: unknown;
- description?: unknown;
- type?: unknown;
- };
- if (typeof id !== 'string' || typeof name !== 'string') return [];
- return [
- {
- id,
- name,
- ...(typeof description === 'string' ? { description } : {}),
- ...(typeof type === 'string' ? { kind: type } : {}),
- },
- ];
- });
-}
diff --git a/packages/server/src/acp/thread-socket.test.ts b/packages/server/src/acp/thread-socket.test.ts
index b88e49cef..ec9a17fba 100644
--- a/packages/server/src/acp/thread-socket.test.ts
+++ b/packages/server/src/acp/thread-socket.test.ts
@@ -62,7 +62,10 @@ process.stdin.on('data', (chunk) => {
if (msg.method === 'initialize') {
const agentCapabilities = {};
if (caps.includes('resume')) agentCapabilities.sessionCapabilities = { resume: {} };
- reply({ protocolVersion: 1, agentCapabilities });
+ const authMethods = caps.includes('terminal-login')
+ ? [{ id: 'cli-login', name: 'CLI login', type: 'terminal', args: ['login'], env: { FROM_METHOD: '1' } }]
+ : undefined;
+ reply({ protocolVersion: 1, agentCapabilities, ...(authMethods ? { authMethods } : {}) });
} else if (msg.method === 'session/new') {
reply({ sessionId: 'sess-fixed' });
} else if (msg.method === 'session/prompt') {
@@ -370,6 +373,41 @@ describe('/collab/thread socket — history ops', () => {
socket.close();
}, 45_000);
+ test('terminal_auth_launch answers the reqId with the composed launch, and refuses an unknown method', async () => {
+ const localDir = tmp();
+ writeFixtureAgent(localDir, 'terminal-login');
+ const manager = makeManager(tmp(), localDir);
+ await manager.init();
+ const socket = attachFakeSocket(manager);
+
+ socket.emit(
+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),
+ );
+ const created = await socket.awaitFrame('created');
+ const threadId = created.info.threadId;
+ await waitStatus(manager, threadId, 'ready');
+
+ socket.emit(
+ JSON.stringify({ op: 'terminal_auth_launch', threadId, reqId: 'tl1', methodId: 'cli-login' }),
+ );
+ const ready = await socket.awaitFrame('terminal_auth_launch_ready');
+ expect(ready.reqId).toBe('tl1');
+ expect(ready.launch).toMatchObject({
+ executable: 'node',
+ args: [join(localDir, 'fixture-agent.mjs'), 'login'],
+ env: { FAKE_CAPS: 'terminal-login', FROM_METHOD: '1' },
+ pathPrepend: [],
+ });
+
+ socket.emit(
+ JSON.stringify({ op: 'terminal_auth_launch', threadId, reqId: 'tl2', methodId: 'missing' }),
+ );
+ const err = await socket.awaitFrame('error');
+ expect(err.code).toBe('not-ready');
+ expect(err.reqId).toBe('tl2');
+ socket.close();
+ }, 45_000);
+
test('rename round-trips live and archived; a manual title survives first-prompt adoption', async () => {
const localDir = tmp();
writeFixtureAgent(localDir, '');
diff --git a/packages/server/src/acp/thread-socket.ts b/packages/server/src/acp/thread-socket.ts
index 324d21819..c83c72954 100644
--- a/packages/server/src/acp/thread-socket.ts
+++ b/packages/server/src/acp/thread-socket.ts
@@ -82,6 +82,11 @@ export function attachAcpThreadSocket(
send({ op: 'retried', reqId: frame.reqId, info });
return;
}
+ case 'terminal_auth_launch': {
+ const launch = manager.terminalAuthLaunch(frame.threadId, frame.methodId);
+ send({ op: 'terminal_auth_launch_ready', reqId: frame.reqId, launch });
+ return;
+ }
case 'authenticate': {
const info = await manager.authenticateThread(frame.threadId, frame.methodId);
send({ op: 'authenticated', reqId: frame.reqId, info });
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 9518915ad..9c2b4b72f 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -152,6 +152,7 @@ export interface BootServerOptions
probeHarnessManagedMcpEntry?: AcpThreadManagerOptions['probeHarnessManagedMcpEntry'];
probePiAcpBridge?: AcpThreadManagerOptions['probePiAcpBridge'];
ensurePiAcpBridge?: AcpThreadManagerOptions['ensurePiAcpBridge'];
+ terminalAuthAvailable?: boolean;
idleShutdownMs?: number | null;
serveContentAssets?: boolean;
reactShellDistDir?: string;
@@ -478,6 +479,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
probeHarnessManagedMcpEntry: opts.probeHarnessManagedMcpEntry,
probePiAcpBridge: opts.probePiAcpBridge,
ensurePiAcpBridge: opts.ensurePiAcpBridge,
+ terminalAuthAvailable: opts.terminalAuthAvailable === true,
hostSnapshot: () =>
collectServerHostSnapshot({ env: 'local-web', resolve: opts.agentIntegrations?.probe }),
autoApproveOkTools: () =>