Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(acp): honest Installing status, once-per-process pins (PRD-8711) (#4684)

Nick Gomezf19433b49722
diff --git a/.changeset/agent-start-status-and-adapter-reuse.md b/.changeset/agent-start-status-and-adapter-reuse.md
new file mode 100644
index 000000000..32521ed80
--- /dev/null
+++ b/.changeset/agent-start-status-and-adapter-reuse.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Opening, resuming, or retrying an in-app agent now reports "Starting" rather than "Installing" unless it is really fetching a catalog agent's adapter, and screen readers announce how the wait ends. That adapter now resolves once, not per conversation; retrying one that failed to start re-resolves only that agent.
diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdx
index eb6f9d4be..826301c7b 100644
--- a/docs/content/features/editor.mdx
+++ b/docs/content/features/editor.mdx
@@ -132,7 +132,11 @@ The composer stays out of the way where it doesn't belong: it's hidden inside an
### In-app agent release-date policies
-Catalog-managed in-app agents use npm or uv to acquire their adapter. OpenKnowledge preserves your package manager's release-date policy, such as npm's `min-release-age` in your user `.npmrc` or uv's `UV_EXCLUDE_NEWER`: an older eligible release at or below the catalog version may run when the pinned release is too new. npm tries the exact stable pin first and considers older releases only after a dated refusal; uv resolves an isolated tool request bounded by the catalog version. Custom agent commands keep their existing behavior.
+Catalog-managed in-app agents use npm or uv to acquire their adapter. OpenKnowledge preserves your package manager's release-date policy, such as npm's `min-release-age` in your user `.npmrc` or uv's `UV_EXCLUDE_NEWER`: an older eligible release at or below the catalog version may run when the pinned release is too new. npm tries the exact stable pin first and considers older releases only after a dated refusal; uv resolves an isolated tool request bounded by the catalog version. An npm adapter resolved at the exact catalog pin is reused for as long as that OpenKnowledge server keeps running, while a fallback to an older release is re-derived an hour later; uv resolves on every launch. So a release-date policy you change while OpenKnowledge is running reaches a new conversation's fallback within the hour, and reaches an exact pin only after that server restarts: closing the editor window leaves the server running, and by default it exits on its own after 30 minutes with no editor connected.
+
+To apply it sooner, stop that server yourself. [`ok stop`](/docs/reference/cli#manage-local-servers), run from anywhere inside the project, ends it immediately, but it declines while any editor window for that project is still connected: close those windows and run it from a terminal outside the app, or add `--force`. A terminal outside the app needs the `ok` command [on its `PATH`](/docs/reference/what-open-knowledge-writes#shell-and-path); the [built-in terminal](#terminal) carries it, but the window hosting it is itself one of those connections, so in the app the command always needs `--force`. Either way you stop the one server the whole project shares — every other window open on it drops its connection, and any in-app agent conversation running inside it stops with it — though the server does save pending changes and releases its lock on the way down.
+
+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.
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/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsx
index 157292274..08929edb6 100644
--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx
+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx
@@ -3965,9 +3965,22 @@ describe('ThreadView auth-required dead ends', () => {
});
test('a thread genuinely still starting keeps its progress message and offers nothing', () => {
- for (const status of ['installing', 'spawning'] as const) {
+ vi.useFakeTimers();
+ const progressMessages = ['Installing Claude…', 'Starting Claude…'] as const;
+ for (const [status, message] of [
+ ['installing', 'Installing Claude…'],
+ ['spawning', 'Starting Claude…'],
+ ] as const) {
const view = render(<ThreadView info={makeInfo({ archived: false, status })} />);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
expect(screen.queryByTestId('agent-thread-auth-action')).toBeNull();
+ const surface = screen.getByTestId('agent-thread-transcript');
+ const shown = progressMessages.filter((candidate) =>
+ surface.textContent?.includes(candidate),
+ );
+ expect({ status, shown }).toEqual({ status, shown: [message] });
view.unmount();
}
});
@@ -4164,6 +4177,350 @@ describe('ThreadView auth-required dead ends', () => {
});
});
+describe('ThreadView start progress', () => {
+ function transcriptItem(): RenderedItem {
+ return { kind: 'message', role: 'user', text: 'summarise the standup', messageId: 'u1' };
+ }
+
+ test('a thread that already has a transcript still says installing rather than starting', () => {
+ vi.useFakeTimers();
+ const progressMessages = ['Installing Claude…', 'Starting Claude…'] as const;
+ for (const [status, message] of [
+ ['installing', 'Installing Claude…'],
+ ['spawning', 'Starting Claude…'],
+ ] as const) {
+ model = makeModel({ turnActive: false, items: [transcriptItem()] });
+ const view = render(<ThreadView info={makeInfo({ archived: false, status })} />);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+
+ const starting = screen.getByTestId('agent-thread-starting');
+ const shown = progressMessages.filter((candidate) =>
+ starting.textContent?.includes(candidate),
+ );
+ expect({ status, shown }).toEqual({ status, shown: [message] });
+ view.unmount();
+ }
+ });
+
+ test('a thread that already has a transcript still announces its start status', () => {
+ vi.useFakeTimers();
+ for (const [status, message] of [
+ ['installing', 'Installing Claude…'],
+ ['spawning', 'Starting Claude…'],
+ ] as const) {
+ model = makeModel({ turnActive: false, items: [transcriptItem()] });
+ const view = render(<ThreadView info={makeInfo({ archived: false, status })} />);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe(message);
+ expect(screen.getByTestId('agent-thread-starting').textContent).toContain(message);
+ view.unmount();
+ }
+ });
+
+ test('the start-status live region is mounted before there is a start to announce', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ render(<ThreadView info={makeInfo({ archived: true, status: 'exited' })} />);
+
+ const region = screen.getByTestId('agent-thread-start-status');
+ expect(region.getAttribute('role')).toBe('status');
+ expect(region.getAttribute('aria-live')).toBe('polite');
+ expect(region.getAttribute('aria-atomic')).toBe('true');
+ expect(region.textContent).toBe('');
+ });
+
+ test('the start status is announced on the same region across the install probe', () => {
+ vi.useFakeTimers();
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+
+ const region = screen.getByTestId('agent-thread-start-status');
+ expect(region.textContent).toBe('Starting Claude…');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'installing' })} />);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Installing Claude…');
+ expect(screen.getByTestId('agent-thread-start-status')).toBe(region);
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />);
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+ expect(screen.getByTestId('agent-thread-start-status')).toBe(region);
+ });
+
+ test('reaching ready announces the end of the wait', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Claude is ready');
+ });
+
+ test('a thread that was already ready announces nothing', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ render(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('');
+ });
+
+ test('returning to ready after a turn does not re-announce the start', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Claude is ready');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'running' })} />);
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('');
+ });
+
+ test('a start that pauses for sign-in still announces when it becomes ready', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'auth_required' })} />);
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'authenticating' })} />);
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Claude is ready');
+ });
+
+ test('a thread that mounts already waiting on sign-in announces when it becomes ready', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'auth_required' })} />,
+ );
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'authenticating' })} />);
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Claude is ready');
+ });
+
+ test('a sign-in forced mid-conversation announces that the thread is usable again', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'ready' })} />,
+ );
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'running' })} />);
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'auth_required' })} />);
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'authenticating' })} />);
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Claude is ready');
+ });
+
+ test.each(['error', 'exited'] as const)(
+ 'a wait that begins at sign-in and ends in %s announces the failure',
+ (status) => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'auth_required' })} />,
+ );
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe(
+ "Claude couldn't start",
+ );
+ },
+ );
+
+ test.each(['error', 'exited'] as const)(
+ 'a start that ends in %s announces the failure',
+ (status) => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe(
+ "Claude couldn't start",
+ );
+ },
+ );
+
+ test.each([
+ ['error', 'exited'],
+ ['exited', 'error'],
+ ] as const)(
+ 'a start that ends in %s and then %s holds the failure announcement',
+ (first, second) => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: first })} />);
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe(
+ "Claude couldn't start",
+ );
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: second })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe(
+ "Claude couldn't start",
+ );
+ },
+ );
+
+ test('a start that had already succeeded when the agent exited announces no failure', () => {
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'ready' })} />);
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Claude is ready');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'exited' })} />);
+
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('');
+ });
+
+ test('a probe that settles inside the show delay never paints the install label', () => {
+ vi.useFakeTimers();
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'installing' })} />);
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+ expect(screen.getByTestId('agent-thread-transcript').textContent).not.toContain('Installing');
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />);
+ act(() => {
+ vi.advanceTimersByTime(1_000);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+ expect(screen.getByTestId('agent-thread-transcript').textContent).not.toContain('Installing');
+ });
+
+ test('the install label paints only after the show delay and in both places at once', () => {
+ vi.useFakeTimers();
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'installing' })} />);
+ act(() => {
+ vi.advanceTimersByTime(199);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+ expect(screen.getByTestId('agent-thread-transcript').textContent).toContain('Starting Claude…');
+
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Installing Claude…');
+ expect(screen.getByTestId('agent-thread-transcript').textContent).toContain(
+ 'Installing Claude…',
+ );
+ });
+
+ test('once painted, the install label holds for its minimum visible window', () => {
+ vi.useFakeTimers();
+ model = makeModel({ turnActive: false, items: [] });
+ const { rerender } = render(
+ <ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />,
+ );
+
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'installing' })} />);
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Installing Claude…');
+
+ act(() => {
+ vi.advanceTimersByTime(50);
+ });
+ rerender(<ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />);
+ act(() => {
+ vi.advanceTimersByTime(249);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Installing Claude…');
+ expect(screen.getByTestId('agent-thread-transcript').textContent).toContain(
+ 'Installing Claude…',
+ );
+
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(screen.getByTestId('agent-thread-start-status').textContent).toBe('Starting Claude…');
+ expect(screen.getByTestId('agent-thread-transcript').textContent).toContain('Starting Claude…');
+ });
+
+ test('a brand-new thread commits the start-status region before its first label', async () => {
+ model = makeModel({ turnActive: false, items: [] });
+ const steps: string[] = [];
+ const inRegion = (node: Node | null): boolean => {
+ const el = node instanceof HTMLElement ? node : (node?.parentElement ?? null);
+ return el?.getAttribute('data-testid') === 'agent-thread-start-status';
+ };
+ let regionSeen = false;
+ const observer = new MutationObserver((records) => {
+ for (const record of records) {
+ if (inRegion(record.target)) {
+ steps.push('label');
+ continue;
+ }
+ for (const added of record.addedNodes) {
+ if (
+ !regionSeen &&
+ added instanceof HTMLElement &&
+ added.querySelector('[data-testid="agent-thread-start-status"]') !== null
+ ) {
+ regionSeen = true;
+ steps.push('region');
+ }
+ }
+ }
+ });
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true });
+
+ try {
+ render(<ThreadView info={makeInfo({ archived: false, status: 'spawning' })} />);
+ await waitFor(() => {
+ expect(steps).toEqual(['region', 'label']);
+ });
+ } finally {
+ observer.disconnect();
+ }
+ });
+});
+
describe('ThreadView attachment budget and clear fence (PRD-8453)', () => {
const makeDropTransfer = (files: readonly File[]) => ({
types: ['Files'],
diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsx
index 062be79e7..778993a60 100644
--- a/packages/app/src/components/acp/ThreadView.tsx
+++ b/packages/app/src/components/acp/ThreadView.tsx
@@ -186,6 +186,7 @@ import {
} from './thread-auth-offer';
import { transcriptItemId } from './transcript-item-id';
import { type ResendTarget, UserMessageActions, UserMessageEditor } from './UserMessageActions';
+import { useDelayedInstallStatus } from './use-delayed-install-status';
import { activeToolKind, useThinkingLine, workingStatusText } from './working-status';
const CANCEL_STALL_MS = 10_000;
@@ -436,6 +437,58 @@ export function ThreadView({
const [resumePending, setResumePending] = useState(false);
const [newChatPending, setNewChatPending] = useState(false);
const [resumeError, setResumeError] = useState<ThreadResumeError | null>(null);
+ const displayedStartStatus = useDelayedInstallStatus(status);
+ const wasStarting = useRef(false);
+ const [startOutcome, setStartOutcome] = useState<'ready' | 'failed' | null>(null);
+ useEffect(() => {
+ if (
+ status === 'installing' ||
+ status === 'spawning' ||
+ status === 'auth_required' ||
+ status === 'authenticating'
+ ) {
+ wasStarting.current = true;
+ setStartOutcome(null);
+ return;
+ }
+ if (status === 'ready') {
+ if (!wasStarting.current) return;
+ wasStarting.current = false;
+ setStartOutcome('ready');
+ return;
+ }
+ if (status === 'error' || status === 'exited') {
+ if (!wasStarting.current) {
+ setStartOutcome((announced) => (announced === 'failed' ? announced : null));
+ return;
+ }
+ wasStarting.current = false;
+ setStartOutcome('failed');
+ return;
+ }
+ if (status === 'running' || status === 'awaiting_permission') {
+ wasStarting.current = false;
+ setStartOutcome(null);
+ return;
+ }
+ const exhaustive: never = status;
+ void exhaustive;
+ }, [status]);
+ const startStatusMessage =
+ displayedStartStatus === 'installing'
+ ? t`Installing ${agentName}…`
+ : displayedStartStatus === 'spawning'
+ ? t`Starting ${agentName}…`
+ : startOutcome === 'ready'
+ ? t`${agentName} is ready`
+ : startOutcome === 'failed'
+ ? t`${agentName} couldn't start`
+ : '';
+ const [startRegionMounted, setStartRegionMounted] = useState(false);
+ useEffect(() => {
+ setStartRegionMounted(true);
+ }, []);
+ const announcedStartStatus = startRegionMounted ? startStatusMessage : '';
const hasRecoverablePromptFailure =
!archived &&
status === 'error' &&
@@ -1011,6 +1064,7 @@ export function ThreadView({
) : (
<ThreadEmptyState
status={status}
+ displayedStartStatus={displayedStartStatus}
archived={archived}
agent={info.agent}
authOffer={authOffer}
@@ -1085,8 +1139,7 @@ export function ThreadView({
data-testid="agent-thread-starting"
>
<Spinner className="size-3.5" aria-hidden="true" />
- {}
- <span className="shimmer">{t`Starting the agent…`}</span>
+ <span className="shimmer">{startStatusMessage}</span>
</div>
) : null}
</MessageScrollerContent>
@@ -1161,6 +1214,15 @@ export function ThreadView({
>
{resumeFailureMessage}
</span>
+ <span
+ className="sr-only"
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ data-testid="agent-thread-start-status"
+ >
+ {announcedStartStatus}
+ </span>
{resumeFailureMessage !== '' ? (
<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"
@@ -1822,6 +1884,7 @@ function ThreadAuthOfferButton({
function ThreadEmptyState({
status,
+ displayedStartStatus,
archived,
agent,
authOffer,
@@ -1829,6 +1892,7 @@ function ThreadEmptyState({
runningAuthAction,
}: {
status: ThreadInfo['status'];
+ displayedStartStatus: ThreadInfo['status'];
archived: boolean;
agent: ThreadInfo['agent'];
authOffer: ThreadAuthOfferWithoutSignIn;
@@ -1874,9 +1938,9 @@ function ThreadEmptyState({
}
const loadingMessage =
- status === 'installing'
+ displayedStartStatus === 'installing'
? t`Installing ${agentName}…`
- : status === 'spawning'
+ : displayedStartStatus === 'spawning'
? t`Starting ${agentName}…`
: status === 'authenticating'
? t`Signing in to ${agentName}…`
diff --git a/packages/app/src/components/acp/use-delayed-install-status.ts b/packages/app/src/components/acp/use-delayed-install-status.ts
new file mode 100644
index 000000000..7bc50f8f5
--- /dev/null
+++ b/packages/app/src/components/acp/use-delayed-install-status.ts
@@ -0,0 +1,41 @@
+import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { useEffect, useRef, useState } from 'react';
+
+const INSTALLING_SHOW_DELAY_MS = 200;
+const INSTALLING_MIN_VISIBLE_MS = 300;
+
+export function useDelayedInstallStatus(status: ThreadInfo['status']): ThreadInfo['status'] {
+ const [installVisible, setInstallVisible] = useState(false);
+ const shownAt = useRef<number | null>(null);
+
+ useEffect(() => {
+ if (status === 'installing') {
+ if (shownAt.current !== null) return;
+ const timer = setTimeout(() => {
+ shownAt.current = Date.now();
+ setInstallVisible(true);
+ }, INSTALLING_SHOW_DELAY_MS);
+ return () => {
+ clearTimeout(timer);
+ };
+ }
+ if (shownAt.current === null) return;
+ if (status !== 'spawning') {
+ shownAt.current = null;
+ setInstallVisible(false);
+ return;
+ }
+ const remaining = Math.max(0, INSTALLING_MIN_VISIBLE_MS - (Date.now() - shownAt.current));
+ const timer = setTimeout(() => {
+ shownAt.current = null;
+ setInstallVisible(false);
+ }, remaining);
+ return () => {
+ clearTimeout(timer);
+ };
+ }, [status]);
+
+ if (status === 'installing') return installVisible ? 'installing' : 'spawning';
+ if (status === 'spawning' && installVisible) return 'installing';
+ return status;
+}
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index bf35ef7a2..43c11e227 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -3575,6 +3575,7 @@
"_IX_7x": ["أخرى"],
"_IfSZn": ["توجد سمة محفوظة بهذا الاسم بالفعل."],
"_JOGC0": ["إرسال ملاحظات…"],
+ "_KnFpR": ["تعذّر تشغيل ", ["agentName"]],
"_LK4d6": ["قد تكون هذه القائمة قديمة."],
"_LczaQ": ["مرفوض — ", ["optionName"]],
"_NWEid": ["ابحث في ملفات المخططات بالمسار"],
@@ -5281,6 +5282,7 @@
"phM8Kh": ["عُثر على المستودع لكن تعذّر فتح المشروع. يرجى المحاولة مرة أخرى."],
"pha01Y": ["صفحات على مستوى المشروع بلا حواف واردة في الرسم البياني."],
"pkAft1": ["فشل البحث."],
+ "pkmXTp": [["agentName"], " جاهز"],
"pmUArF": ["مساحة العمل"],
"poAsUN": ["بدون وكلاء — تُحفظ ولا تُثبَّت في أي مكان"],
"ppDgFi": ["أعد التشغيل بنسخة هذا التطبيق"],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index f6ef2b012..b8f53f7d0 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -568,6 +568,10 @@ msgstr "مخزن المهارات المركزي لـ {agent} غير موجود
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "لا يمكن لـ {agentName} استئناف هذه المحادثة. يُحتفظ بنص المحادثة، لذا ابدأ محادثة جديدة للمتابعة."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "تعذّر تشغيل {agentName}"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "تعذّر على {agentName} بدء محادثة."
@@ -581,6 +585,10 @@ msgstr "تعذّر تشغيل {agentName}."
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} لا يقبل مرفقات الصور."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} جاهز"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} لا يعمل. ابدأ محادثة جديدة لتسجيل الدخول."
@@ -13423,7 +13431,6 @@ msgstr "يجري بدء تدفق تسجيل الدخول"
msgid "Starting terminal…"
msgstr "جارٍ بدء تشغيل الطرفية…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "يجري تشغيل الوكيل…"
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index 2b8be480f..38f24ca8a 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -3027,6 +3027,7 @@
"_IX_7x": ["অন্যান্য"],
"_IfSZn": ["এই নামে ইতিমধ্যেই একটি সংরক্ষিত থিম আছে।"],
"_JOGC0": ["মতামত পাঠান…"],
+ "_KnFpR": [["agentName"], " শুরু হতে পারেনি"],
"_LK4d6": ["এই তালিকা পুরোনো হতে পারে।"],
"_LczaQ": ["প্রত্যাখ্যাত — ", ["optionName"]],
"_NWEid": ["পথ দিয়ে স্কিমা ফাইল খুঁজুন"],
@@ -4485,6 +4486,7 @@
"phM8Kh": ["রিপোজিটরি পাওয়া গেছে কিন্তু প্রকল্পটি খোলা যায়নি। অনুগ্রহ করে আবার চেষ্টা করুন।"],
"pha01Y": ["যেসব প্রকল্প-স্তরের পাতার কোনো আগত গ্রাফ প্রান্ত নেই।"],
"pkAft1": ["অনুসন্ধান ব্যর্থ।"],
+ "pkmXTp": [["agentName"], " প্রস্তুত"],
"pmUArF": ["ওয়ার্কস্পেস"],
"poAsUN": ["কোনো এজেন্ট নেই — সংরক্ষিত, কোথাও ইনস্টল হয়নি"],
"ppDgFi": ["এই অ্যাপের সংস্করণ দিয়ে পুনরায় চালু করুন"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index f7991ec1d..51cf73e32 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -568,6 +568,10 @@ msgstr "{agent}-এর কেন্দ্রীয় স্কিল স্ট
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} এই চ্যাটটি আর চালিয়ে নিতে পারছে না। ট্রান্সক্রিপ্ট রাখা আছে, তাই চালিয়ে যেতে একটি নতুন চ্যাট শুরু করুন।"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} শুরু হতে পারেনি"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} কথোপকথন শুরু করতে পারেনি।"
@@ -581,6 +585,10 @@ msgstr "{agentName} শুরু হতে পারেনি।"
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} ছবি সংযুক্তি গ্রহণ করে না।"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} প্রস্তুত"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} চলছে না। সাইন ইন করতে একটি নতুন চ্যাট শুরু করুন।"
@@ -13419,7 +13427,6 @@ msgstr "সাইন-ইন প্রক্রিয়া শুরু কর
msgid "Starting terminal…"
msgstr "টার্মিনাল চালু হচ্ছে…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "এজেন্ট শুরু করা হচ্ছে…"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 2c23bd4a5..7ecc2cafd 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -3108,6 +3108,7 @@
"_IX_7x": ["Other"],
"_IfSZn": ["A saved theme already uses this name."],
"_JOGC0": ["Send feedback…"],
+ "_KnFpR": [["agentName"], " couldn't start"],
"_LK4d6": ["This list may be out of date."],
"_LczaQ": ["Denied — ", ["optionName"]],
"_NWEid": ["Search schema files by path"],
@@ -4638,6 +4639,7 @@
"phM8Kh": ["Found the repo but could not open the project. Please try again."],
"pha01Y": ["Project-level pages with no incoming graph edges."],
"pkAft1": ["Search failed."],
+ "pkmXTp": [["agentName"], " is ready"],
"pmUArF": ["Workspace"],
"poAsUN": ["no agents — saved, not installed anywhere"],
"ppDgFi": ["Restart with this app's version"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index b0c005aed..b6e5400fe 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -568,6 +568,10 @@ msgstr "{agent}'s central skills store does not exist yet; start {agent} once so
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} couldn't start"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} couldn't start a conversation."
@@ -581,6 +585,10 @@ msgstr "{agentName} couldn't start."
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} doesn't accept image attachments."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} is ready"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} isn't running. Start a new chat to sign in."
@@ -13423,7 +13431,6 @@ msgstr "Starting sign-in flow"
msgid "Starting terminal…"
msgstr "Starting terminal…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "Starting the agent…"
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index c94a83e2f..7c2c39fcf 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -3610,6 +3610,7 @@
"_IX_7x": ["Otro"],
"_IfSZn": ["Ya existe un tema guardado con este nombre."],
"_JOGC0": ["Enviar comentarios…"],
+ "_KnFpR": [["agentName"], " no pudo iniciarse"],
"_LK4d6": ["Puede que esta lista esté desactualizada."],
"_LczaQ": ["Denegado — ", ["optionName"]],
"_NWEid": ["Busca archivos de esquema por ruta"],
@@ -5366,6 +5367,7 @@
],
"pha01Y": ["Páginas de todo el proyecto sin aristas entrantes en el grafo."],
"pkAft1": ["Falló la búsqueda."],
+ "pkmXTp": [["agentName"], " está listo"],
"pmUArF": ["Espacio de trabajo"],
"poAsUN": ["sin agentes — guardadas, no instaladas en ningún sitio"],
"ppDgFi": ["Reiniciar con la versión de esta aplicación"],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 80707a7ea..dec8b7250 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -568,6 +568,10 @@ msgstr "El almacén central de habilidades de {agent} aún no existe; inicia {ag
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} no puede retomar este chat. La transcripción se conserva, así que empieza un chat nuevo para continuar."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} no pudo iniciarse"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} no pudo iniciar una conversación."
@@ -581,6 +585,10 @@ msgstr "{agentName} no pudo iniciarse."
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} no acepta adjuntos de imagen."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} está listo"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} no está en ejecución. Empieza un chat nuevo para iniciar sesión."
@@ -13423,7 +13431,6 @@ msgstr "Iniciando el flujo de inicio de sesión"
msgid "Starting terminal…"
msgstr "Iniciando terminal…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "Iniciando el agente…"
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index 4bbedcb12..4a92d8175 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -3655,6 +3655,7 @@
"_IX_7x": ["Autre"],
"_IfSZn": ["Un thème enregistré utilise déjà ce nom."],
"_JOGC0": ["Envoyer un retour…"],
+ "_KnFpR": [["agentName"], " n’a pas pu démarrer"],
"_LK4d6": ["Cette liste n'est peut-être pas à jour."],
"_LczaQ": ["Refusé — ", ["optionName"]],
"_NWEid": ["Rechercher des fichiers de schéma par chemin"],
@@ -5417,6 +5418,7 @@
"phM8Kh": ["Dépôt trouvé, mais le projet n'a pas pu être ouvert. Veuillez réessayer."],
"pha01Y": ["Pages du projet sans arête entrante dans le graphe."],
"pkAft1": ["La recherche a échoué."],
+ "pkmXTp": [["agentName"], " est prêt"],
"pmUArF": ["Espace de travail"],
"poAsUN": ["aucun agent — enregistrées, installées nulle part"],
"ppDgFi": ["Redémarrer avec la version de cette application"],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index e6c3b40f8..90a1fb56e 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -568,6 +568,10 @@ msgstr "Le magasin central de compétences de {agent} n'existe pas encore ; lanc
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} ne peut pas reprendre ce chat. La transcription est conservée, alors démarrez un nouveau chat pour continuer."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} n’a pas pu démarrer"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} n’a pas pu démarrer de conversation."
@@ -581,6 +585,10 @@ msgstr "{agentName} n’a pas pu démarrer."
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} n'accepte pas les pièces jointes d'image."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} est prêt"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} n'est pas en cours d'exécution. Démarrez un nouveau chat pour vous connecter."
@@ -13423,7 +13431,6 @@ msgstr "Démarrage du processus de connexion"
msgid "Starting terminal…"
msgstr "Démarrage du terminal…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "Démarrage de l'agent…"
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index efceab405..02e2d4d0c 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -3022,6 +3022,7 @@
"_IX_7x": ["अन्य"],
"_IfSZn": ["एक सहेजी गई थीम पहले से इस नाम का उपयोग कर रही है।"],
"_JOGC0": ["प्रतिक्रिया भेजें…"],
+ "_KnFpR": [["agentName"], " शुरू नहीं हो सका"],
"_LK4d6": ["यह सूची पुरानी हो सकती है।"],
"_LczaQ": ["अस्वीकृत — ", ["optionName"]],
"_NWEid": ["स्कीमा फ़ाइलें पथ से खोजें"],
@@ -4482,6 +4483,7 @@
"phM8Kh": ["रिपॉज़िटरी मिल गई पर प्रोजेक्ट नहीं खोला जा सका। कृपया फिर कोशिश करें।"],
"pha01Y": ["वे प्रोजेक्ट-स्तर के पेज जिनके कोई आने वाले ग्राफ़ किनारे नहीं हैं।"],
"pkAft1": ["खोज विफल।"],
+ "pkmXTp": [["agentName"], " तैयार है"],
"pmUArF": ["कार्यक्षेत्र"],
"poAsUN": ["कोई एजेंट नहीं — सहेजी गईं, कहीं इंस्टॉल नहीं"],
"ppDgFi": ["इस ऐप के संस्करण के साथ पुनः आरंभ करें"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 93895d6d0..95b9c7b9c 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -568,6 +568,10 @@ msgstr "{agent} का केंद्रीय स्किल स्टोर
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} इस चैट को आगे नहीं बढ़ा सकता। ट्रांसक्रिप्ट सुरक्षित है, इसलिए जारी रखने के लिए नई चैट शुरू करें।"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} शुरू नहीं हो सका"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} बातचीत शुरू नहीं कर सका।"
@@ -581,6 +585,10 @@ msgstr "{agentName} शुरू नहीं हो सका।"
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} छवि अनुलग्नक स्वीकार नहीं करता।"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} तैयार है"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} नहीं चल रहा है। साइन इन करने के लिए नई चैट शुरू करें।"
@@ -13419,7 +13427,6 @@ msgstr "साइन-इन प्रक्रिया शुरू की ज
msgid "Starting terminal…"
msgstr "टर्मिनल शुरू हो रहा है…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "एजेंट शुरू किया जा रहा है…"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 8c3c4a41b..187e57ee1 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -3134,6 +3134,7 @@
"_IX_7x": ["Lainnya"],
"_IfSZn": ["Tema tersimpan lain sudah menggunakan nama ini."],
"_JOGC0": ["Kirim masukan…"],
+ "_KnFpR": [["agentName"], " tidak dapat dijalankan"],
"_LK4d6": ["Daftar ini mungkin tidak mutakhir."],
"_LczaQ": ["Ditolak — ", ["optionName"]],
"_NWEid": ["Cari berkas skema berdasarkan jalur"],
@@ -4670,6 +4671,7 @@
"phM8Kh": ["Repo ditemukan tetapi proyeknya tidak dapat dibuka. Silakan coba lagi."],
"pha01Y": ["Halaman tingkat proyek yang tidak punya sisi graf masuk."],
"pkAft1": ["Pencarian gagal."],
+ "pkmXTp": [["agentName"], " siap"],
"pmUArF": ["Ruang kerja"],
"poAsUN": ["tanpa agen — disimpan, tidak dipasang di mana pun"],
"ppDgFi": ["Mulai ulang dengan versi aplikasi ini"],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index 0c8d72d8e..b03a3b997 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -568,6 +568,10 @@ msgstr "Penyimpanan keterampilan pusat {agent} belum ada; jalankan {agent} sekal
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} tidak dapat melanjutkan obrolan ini. Transkrip tetap tersimpan, jadi mulai obrolan baru untuk melanjutkan."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} tidak dapat dijalankan"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} tidak dapat memulai percakapan."
@@ -581,6 +585,10 @@ msgstr "{agentName} tidak dapat dijalankan."
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} tidak menerima lampiran gambar."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} siap"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} tidak berjalan. Mulai obrolan baru untuk masuk."
@@ -13419,7 +13427,6 @@ msgstr "Memulai alur masuk"
msgid "Starting terminal…"
msgstr "Memulai terminal…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "Memulai agennya…"
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 132c748cc..cc67c1d6a 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -3002,6 +3002,7 @@
"_IX_7x": ["기타"],
"_IfSZn": ["이미 이 이름을 사용하는 저장된 테마가 있습니다."],
"_JOGC0": ["피드백 보내기…"],
+ "_KnFpR": [["agentName"], " 시작 실패"],
"_LK4d6": ["이 목록은 최신 상태가 아닐 수 있습니다."],
"_LczaQ": ["거부됨: ", ["optionName"]],
"_NWEid": ["경로로 스키마 파일 검색"],
@@ -4464,6 +4465,7 @@
"phM8Kh": ["저장소를 찾았지만 프로젝트를 열 수 없습니다. 다시 시도하세요."],
"pha01Y": ["들어오는 그래프 연결이 없는 프로젝트 수준 페이지입니다."],
"pkAft1": ["검색에 실패했습니다."],
+ "pkmXTp": [["agentName"], " 준비 완료"],
"pmUArF": ["워크스페이스"],
"poAsUN": ["에이전트 없음 — 저장만 되고 어디에도 설치되지 않음"],
"ppDgFi": ["이 앱의 버전으로 다시 시작"],
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 1778c791d..cfceef286 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -568,6 +568,10 @@ msgstr "{agent}의 중앙 스킬 저장소가 아직 없습니다. {agent}을(
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName}이(가) 이 채팅을 이어갈 수 없습니다. 대화 기록은 유지되므로 새 채팅을 시작하세요."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} 시작 실패"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} 대화 시작 실패."
@@ -581,6 +585,10 @@ msgstr "{agentName} 시작 실패."
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName}: 이미지 첨부 미지원"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} 준비 완료"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName}이(가) 실행 중이 아닙니다. 로그인하려면 새 채팅을 시작하세요."
@@ -13423,7 +13431,6 @@ msgstr "로그인 흐름 시작 중"
msgid "Starting terminal…"
msgstr "터미널 시작 중…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "에이전트 시작 중…"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index b10288eae..e2d72b6d2 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -3108,6 +3108,7 @@
"_IX_7x": ["Ōţĥēŕ"],
"_IfSZn": ["À śàvēď ţĥēḿē àĺŕēàďŷ ũśēś ţĥĩś ńàḿē."],
"_JOGC0": ["Śēńď ƒēēďƀàćķ…"],
+ "_KnFpR": [["agentName"], " ćōũĺďń'ţ śţàŕţ"],
"_LK4d6": ["Ţĥĩś ĺĩśţ ḿàŷ ƀē ōũţ ōƒ ďàţē."],
"_LczaQ": ["Ďēńĩēď — ", ["optionName"]],
"_NWEid": ["Śēàŕćĥ śćĥēḿà ƒĩĺēś ƀŷ ƥàţĥ"],
@@ -4638,6 +4639,7 @@
"phM8Kh": ["Ƒōũńď ţĥē ŕēƥō ƀũţ ćōũĺď ńōţ ōƥēń ţĥē ƥŕōĴēćţ. Ƥĺēàśē ţŕŷ àĝàĩń."],
"pha01Y": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńō ĩńćōḿĩńĝ ĝŕàƥĥ ēďĝēś."],
"pkAft1": ["Śēàŕćĥ ƒàĩĺēď."],
+ "pkmXTp": [["agentName"], " ĩś ŕēàďŷ"],
"pmUArF": ["Ŵōŕķśƥàćē"],
"poAsUN": ["ńō àĝēńţś — śàvēď, ńōţ ĩńśţàĺĺēď àńŷŵĥēŕē"],
"ppDgFi": ["Ŕēśţàŕţ ŵĩţĥ ţĥĩś àƥƥ'ś vēŕśĩōń"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 7fb01f239..5a2cd7ba6 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -568,6 +568,10 @@ msgstr ""
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr ""
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr ""
@@ -581,6 +585,10 @@ msgstr ""
msgid "{agentName} doesn't accept image attachments."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr ""
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr ""
@@ -13419,7 +13427,6 @@ msgstr ""
msgid "Starting terminal…"
msgstr ""
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 3ccccaa0f..f862bddec 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -3546,6 +3546,7 @@
"_IX_7x": ["Outro"],
"_IfSZn": ["Um tema salvo já usa este nome."],
"_JOGC0": ["Enviar comentários…"],
+ "_KnFpR": [["agentName"], " não conseguiu iniciar"],
"_LK4d6": ["Esta lista pode estar desatualizada."],
"_LczaQ": ["Negado — ", ["optionName"]],
"_NWEid": ["Busque arquivos de esquema por caminho"],
@@ -5254,6 +5255,7 @@
],
"pha01Y": ["Páginas de todo o projeto sem arestas de entrada no grafo."],
"pkAft1": ["A busca falhou."],
+ "pkmXTp": [["agentName"], " está pronto"],
"pmUArF": ["Espaço de trabalho"],
"poAsUN": ["nenhum agente — salvas, não instaladas em lugar algum"],
"ppDgFi": ["Reiniciar com a versão deste app"],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index c684db42c..5a9716e6d 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -568,6 +568,10 @@ msgstr "O repositório central de habilidades do {agent} ainda não existe; inic
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} não consegue retomar este chat. A transcrição é mantida, então comece um novo chat para continuar."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} não conseguiu iniciar"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} não conseguiu iniciar uma conversa."
@@ -581,6 +585,10 @@ msgstr "{agentName} não conseguiu iniciar."
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} não aceita anexos de imagem."
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} está pronto"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} não está em execução. Comece um novo chat para fazer login."
@@ -13419,7 +13427,6 @@ msgstr "Iniciando o fluxo de login"
msgid "Starting terminal…"
msgstr "Iniciando terminal…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "Iniciando o agente…"
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index 0da33e967..b0d0966b4 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -3178,6 +3178,7 @@
"_IX_7x": ["دیگر"],
"_IfSZn": ["اس نام کی ایک محفوظ شدہ تھیم پہلے سے موجود ہے۔"],
"_JOGC0": ["رائے بھیجیں…"],
+ "_KnFpR": [["agentName"], " شروع نہ ہو سکا"],
"_LK4d6": ["یہ فہرست پرانی ہو سکتی ہے۔"],
"_LczaQ": ["مسترد — ", ["optionName"]],
"_NWEid": ["اسکیما فائلیں راستے سے تلاش کریں"],
@@ -4736,6 +4737,7 @@
"phM8Kh": ["ریپو مل گیا مگر پروجیکٹ نہیں کھل سکا۔ براہِ کرم دوبارہ کوشش کریں۔"],
"pha01Y": ["پروجیکٹ کی سطح کے وہ صفحات جن کے گراف میں آنے والے کنارے نہیں۔"],
"pkAft1": ["تلاش ناکام رہی۔"],
+ "pkmXTp": [["agentName"], " تیار ہے"],
"pmUArF": ["ورک اسپیس"],
"poAsUN": ["کوئی ایجنٹ نہیں — محفوظ، کہیں نصب نہیں"],
"ppDgFi": ["اس ایپ کے ورژن کے ساتھ دوبارہ چلائیں"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index 08323e85e..306369bef 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -568,6 +568,10 @@ msgstr "{agent} کا مرکزی اسکل اسٹور ابھی موجود نہیں
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} اس چیٹ کو دوبارہ جاری نہیں رکھ سکتا۔ ٹرانسکرپٹ محفوظ ہے، اس لیے جاری رکھنے کے لیے نئی چیٹ شروع کریں۔"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} شروع نہ ہو سکا"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} گفتگو شروع نہ کر سکا۔"
@@ -581,6 +585,10 @@ msgstr "{agentName} شروع نہ ہو سکا۔"
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} تصویری منسلکات قبول نہیں کرتا۔"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} تیار ہے"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} نہیں چل رہا۔ سائن اِن کرنے کے لیے نئی چیٹ شروع کریں۔"
@@ -13423,7 +13431,6 @@ msgstr "سائن اِن کا عمل شروع کیا جا رہا ہے"
msgid "Starting terminal…"
msgstr "ٹرمینل شروع ہو رہا ہے…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "ایجنٹ شروع کیا جا رہا ہے…"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index c592c4c83..ca5274644 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -2731,6 +2731,7 @@
"_IX_7x": ["其他"],
"_IfSZn": ["已有一个已保存的主题使用此名称。"],
"_JOGC0": ["发送反馈…"],
+ "_KnFpR": [["agentName"], " 无法启动"],
"_LK4d6": ["此列表可能不是最新的。"],
"_LczaQ": ["已拒绝 — ", ["optionName"]],
"_NWEid": ["按路径搜索架构文件"],
@@ -4045,6 +4046,7 @@
"phM8Kh": ["找到了仓库,但无法打开项目。请重试。"],
"pha01Y": ["没有入链的项目级页面。"],
"pkAft1": ["搜索失败。"],
+ "pkmXTp": [["agentName"], " 已就绪"],
"pmUArF": ["工作区"],
"poAsUN": ["未选择智能体 — 仅保存,不安装到任何位置"],
"ppDgFi": ["用这个应用的版本重启"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 55566c4c2..a5268c76e 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -568,6 +568,10 @@ msgstr "{agent} 的中央技能库还不存在;先启动一次 {agent} 让它
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} 无法继续此对话。记录会保留,请开始新对话以继续。"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} 无法启动"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} 无法开始对话。"
@@ -581,6 +585,10 @@ msgstr "{agentName} 无法启动。"
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} 不接受图像附件。"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} 已就绪"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} 未在运行。请开始新对话以登录。"
@@ -13423,7 +13431,6 @@ msgstr "正在启动登录流程"
msgid "Starting terminal…"
msgstr "正在启动终端…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "正在启动智能体…"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index d054f30d8..3430f1b96 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -2747,6 +2747,7 @@
"_IX_7x": ["其他"],
"_IfSZn": ["已有已儲存的主題使用這個名稱。"],
"_JOGC0": ["傳送意見回饋…"],
+ "_KnFpR": [["agentName"], " 無法啟動"],
"_LK4d6": ["這份清單可能不是最新的。"],
"_LczaQ": ["已拒絕 — ", ["optionName"]],
"_NWEid": ["依路徑搜尋結構描述檔案"],
@@ -4065,6 +4066,7 @@
"phM8Kh": ["找到儲存庫了,但無法開啟專案。請再試一次。"],
"pha01Y": ["沒有連入關係圖邊的專案層級頁面。"],
"pkAft1": ["搜尋失敗。"],
+ "pkmXTp": [["agentName"], " 已就緒"],
"pmUArF": ["工作區"],
"poAsUN": ["未選擇代理 — 僅保存,不安裝到任何位置"],
"ppDgFi": ["用這個應用程式的版本重新啟動"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 397024b70..d0e9b5689 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -568,6 +568,10 @@ msgstr "{agent} 的中央技能庫還不存在;先啟動一次 {agent} 讓它
msgid "{agentName} can't pick this chat back up. The transcript is kept, so start a new chat to continue."
msgstr "{agentName} 無法繼續此對話。記錄會保留,請開始新的對話以繼續。"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} couldn't start"
+msgstr "{agentName} 無法啟動"
+
#: src/components/acp/ThreadView.tsx
msgid "{agentName} couldn't start a conversation."
msgstr "{agentName} 無法開始對話。"
@@ -581,6 +585,10 @@ msgstr "{agentName} 無法啟動。"
msgid "{agentName} doesn't accept image attachments."
msgstr "{agentName} 不接受圖片附件。"
+#: src/components/acp/ThreadView.tsx
+msgid "{agentName} is ready"
+msgstr "{agentName} 已就緒"
+
#: src/components/acp/thread-auth-offer.ts
msgid "{agentName} isn't running. Start a new chat to sign in."
msgstr "{agentName} 未在執行。請開始新的對話以登入。"
@@ -13423,7 +13431,6 @@ msgstr "正在啟動登入流程"
msgid "Starting terminal…"
msgstr "正在啟動終端機…"
-#: src/components/acp/ThreadView.tsx
#: src/components/SessionsHost.tsx
msgid "Starting the agent…"
msgstr "正在啟動代理…"
diff --git a/packages/server/src/acp/acquisition-contract.test-helper.ts b/packages/server/src/acp/acquisition-contract.test-helper.ts
index 94ba0eba2..c364af40c 100644
--- a/packages/server/src/acp/acquisition-contract.test-helper.ts
+++ b/packages/server/src/acp/acquisition-contract.test-helper.ts
@@ -81,8 +81,10 @@ export function acquisitionFailureContract(factory: AcquisitionFactory): void {
});
}
+export type AcquisitionRegistryControl = { closeRegistry: () => Promise<void> };
+
export async function withLocalAcquisitionRegistry(
- run: (home: string) => Promise<void>,
+ run: (home: string, control: AcquisitionRegistryControl) => Promise<void>,
): Promise<void> {
await withAcquisitionHome(async (home) => {
const packages = new Map<string, Map<string, { bytes: Buffer; published: string }>>();
@@ -181,11 +183,17 @@ export async function withLocalAcquisitionRegistry(
process.env.npm_config_registry = `http://127.0.0.1:${address.port}/`;
process.env.UV_OFFLINE = '0';
process.env.UV_DEFAULT_INDEX = `http://127.0.0.1:${address.port}/simple`;
- try {
- await run(home);
- } finally {
+ let stopped = false;
+ const closeRegistry = async (): Promise<void> => {
+ if (stopped) return;
+ stopped = true;
endpoint.closeAllConnections();
await new Promise<void>((resolve) => endpoint.close(() => resolve()));
+ };
+ try {
+ await run(home, { closeRegistry });
+ } finally {
+ await closeRegistry();
}
});
}
diff --git a/packages/server/src/acp/launch-probe-scope.test.ts b/packages/server/src/acp/launch-probe-scope.test.ts
new file mode 100644
index 000000000..3268812ce
--- /dev/null
+++ b/packages/server/src/acp/launch-probe-scope.test.ts
@@ -0,0 +1,592 @@
+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';
+import {
+ AgentLaunchError,
+ type ResolvedLaunch,
+ resetAcquisitionCache,
+ resolveRegistryLaunch,
+} from './launch.ts';
+import {
+ installNodeFixture,
+ npmNative,
+ probedDescriptors,
+ registryPackage,
+ withAcquisitionHome,
+ writeExecutable,
+ writeRecordingNpm,
+} from './package-acquisition.test-helper.ts';
+
+const log = getLogger('launch-probe-scope-test');
+
+function acquisitionBin(home: string): { bin: string; probeLog: string } {
+ const bin = join(home, 'bin');
+ mkdirSync(bin);
+ installNodeFixture(bin);
+ writeExecutable(join(bin, 'npx'), 'process.exit(0);');
+ return { bin, probeLog: join(home, 'probes.log') };
+}
+
+function recordingNpmBin(home: string): { bin: string; probeLog: string } {
+ const { bin, probeLog } = acquisitionBin(home);
+ writeRecordingNpm(bin, probeLog);
+ return { bin, probeLog };
+}
+
+function releaseAgeNpmBin(home: string, admitted: string): { bin: string; probeLog: string } {
+ const { bin, probeLog } = acquisitionBin(home);
+ writeExecutable(
+ join(bin, 'npm'),
+ `require('node:fs').appendFileSync(${JSON.stringify(probeLog)}, JSON.stringify(process.argv.slice(2)) + '\\n');
+ const spec = process.argv[3];
+ const at = spec.lastIndexOf('@');
+ const name = spec.slice(0, at);
+ const range = spec.slice(at + 1);
+ if (process.env.npm_config_before && !range.includes(' - ')) {
+ process.stderr.write('npm error code ETARGET\\nnpm error notarget No matching version found for ' + spec + ' with a date before the release-age cutoff.\\n');
+ process.exit(1);
+ }
+ const version = range.includes(' - ') ? ${JSON.stringify(admitted)} : range;
+ process.stdout.write(JSON.stringify([{ name, version }]));`,
+ );
+ return { bin, probeLog };
+}
+
+function gatedNpmBin(
+ home: string,
+ gatedOutcome: 'refuse' | 'admit',
+): { bin: string; probeLog: string; entered: string; release: string } {
+ const { bin, probeLog } = acquisitionBin(home);
+ const entered = join(home, 'entered');
+ const release = join(home, 'release');
+ writeExecutable(
+ join(bin, 'npm'),
+ `const fs = require('node:fs');
+ let gated = false;
+ try {
+ fs.writeFileSync(${JSON.stringify(entered)}, '', { flag: 'wx' });
+ gated = true;
+ } catch {}
+ fs.appendFileSync(${JSON.stringify(probeLog)}, JSON.stringify(process.argv.slice(2)) + '\\n');
+ const spec = process.argv[3];
+ const at = spec.lastIndexOf('@');
+ const admit = () =>
+ process.stdout.write(
+ JSON.stringify([{ name: spec.slice(0, at), version: spec.slice(at + 1) }]),
+ );
+ const refuse = () => {
+ process.stderr.write('npm error code EAGAIN\\nnpm error the fixture registry refused this probe\\n');
+ process.exit(1);
+ };
+ const settle = () => {
+ if (!fs.existsSync(${JSON.stringify(release)})) setTimeout(settle, 20);
+ else if (${JSON.stringify(gatedOutcome)} === 'refuse') refuse();
+ else admit();
+ };
+ if (gated) settle();
+ else admit();`,
+ );
+ return { bin, probeLog, entered, release };
+}
+
+function retryRefusingNpmBin(home: string): {
+ bin: string;
+ probeLog: string;
+ entered: string;
+ release: string;
+} {
+ const { bin, probeLog } = acquisitionBin(home);
+ const admitted = join(home, 'admitted');
+ const entered = join(home, 'entered');
+ const release = join(home, 'release');
+ writeExecutable(
+ join(bin, 'npm'),
+ `const fs = require('node:fs');
+ fs.appendFileSync(${JSON.stringify(probeLog)}, JSON.stringify(process.argv.slice(2)) + '\\n');
+ const spec = process.argv[3];
+ const at = spec.lastIndexOf('@');
+ const claim = (path) => {
+ try {
+ fs.writeFileSync(path, '', { flag: 'wx' });
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const admit = () =>
+ process.stdout.write(
+ JSON.stringify([{ name: spec.slice(0, at), version: spec.slice(at + 1) }]),
+ );
+ const refuse = () => {
+ process.stderr.write('npm error code EAGAIN\\nnpm error the fixture registry refused this re-acquisition\\n');
+ process.exit(1);
+ };
+ const settle = () => {
+ if (fs.existsSync(${JSON.stringify(release)})) refuse();
+ else setTimeout(settle, 20);
+ };
+ if (claim(${JSON.stringify(admitted)}) || !claim(${JSON.stringify(entered)})) admit();
+ else settle();`,
+ );
+ return { bin, probeLog, entered, release };
+}
+
+const HOUR_MS = 60 * 60 * 1000;
+
+const awaitGate = (entered: string): Promise<void> =>
+ vi.waitFor(() => expect(existsSync(entered)).toBe(true), { timeout: 15_000, interval: 20 });
+
+async function awaitGateOffFakeClock(entered: string): Promise<void> {
+ const deadline = performance.now() + 15_000;
+ while (!existsSync(entered)) {
+ if (performance.now() > deadline) throw new Error(`the gated probe never entered: ${entered}`);
+ await new Promise((settle) => setTimeout(settle, 20));
+ }
+}
+
+function pinnedOpen(
+ descriptor: string,
+ env: Record<string, string>,
+ acquisition?: { reacquire: true },
+): Promise<ResolvedLaunch | null> {
+ return resolveRegistryLaunch(
+ registryPackage(descriptor, 'npx', env),
+ null,
+ log,
+ undefined,
+ (candidate) => Promise.resolve(candidate),
+ acquisition,
+ );
+}
+
+describe('registry launch probe scope', () => {
+ test('repeated opens of one pinned adapter acquire it once per process', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingNpmBin(home);
+ const env = { PATH: bin };
+ const first = await resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', env),
+ null,
+ log,
+ );
+ const second = await resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', env),
+ null,
+ log,
+ );
+ const third = await resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', env),
+ null,
+ log,
+ );
+
+ expect(first.args).toEqual(['-y', '[email protected]', '--version']);
+ expect(second.args).toEqual(first.args);
+ expect(third.args).toEqual(first.args);
+ expect(probedDescriptors(probeLog)).toEqual(['[email protected]']);
+ });
+ });
+
+ test('a resolved acquisition reports how long its probe took', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, entered, release } = gatedNpmBin(home, 'admit');
+ const env = { PATH: bin };
+ const resolutions: { source: string; elapsedMs: number }[] = [];
+ const acquisition = {
+ onResolved: (resolution: { source: string; elapsedMs: number }) => {
+ resolutions.push(resolution);
+ },
+ };
+ const open = (): Promise<ResolvedLaunch | null> =>
+ resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', env),
+ null,
+ log,
+ undefined,
+ (candidate) => Promise.resolve(candidate),
+ acquisition,
+ );
+
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ const startedAt = new Date('2026-09-17T00:00:00Z');
+ vi.setSystemTime(startedAt);
+ const probing = open();
+ await awaitGateOffFakeClock(entered);
+ vi.setSystemTime(new Date(startedAt.getTime() + 5_000));
+ writeFileSync(release, '');
+ await probing;
+ await open();
+
+ expect(resolutions.map((entry) => entry.source)).toEqual(['probe', 'memo']);
+ expect(resolutions[0]?.elapsedMs).toBe(5_000);
+ expect(resolutions[1]?.elapsedMs).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ }, 30_000);
+
+ test('a distinct pin is acquired on its own rather than served from another pin', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingNpmBin(home);
+ const env = { PATH: bin };
+ const ceiling = await resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', env),
+ null,
+ log,
+ );
+ const lower = await resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', env),
+ null,
+ log,
+ );
+ const other = await resolveRegistryLaunch(
+ registryPackage('[email protected]', 'npx', env),
+ null,
+ log,
+ );
+
+ expect(ceiling.args).toEqual(['-y', '[email protected]', '--version']);
+ expect(lower.args).toEqual(['-y', '[email protected]', '--version']);
+ expect(other.args).toEqual(['-y', '[email protected]', '--version']);
+ expect(probedDescriptors(probeLog)).toEqual([
+ ]);
+ });
+ });
+
+ test('two adapters sharing a pin but not their npm configuration are acquired apart', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = releaseAgeNpmBin(home, '6.0.0');
+ const descriptor = '[email protected]';
+
+ const bounded = await resolveRegistryLaunch(
+ registryPackage(descriptor, 'npx', {
+ PATH: bin,
+ npm_config_before: '2018-04-01T00:00:00Z',
+ }),
+ null,
+ log,
+ );
+ const unbounded = await resolveRegistryLaunch(
+ registryPackage(descriptor, 'npx', { PATH: bin }),
+ null,
+ log,
+ );
+
+ expect(bounded.args).toEqual(['-y', '[email protected]', '--version']);
+ expect(unbounded.args).toEqual(['-y', '[email protected]', '--version']);
+ expect(probedDescriptors(probeLog)).toEqual([
+ descriptor,
+ '[email protected] - 7.0.0',
+ descriptor,
+ ]);
+ });
+ });
+
+ test('a release-age-bounded acquisition is re-probed once its freshness window closes', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = releaseAgeNpmBin(home, '6.0.0');
+ const env = { PATH: bin, npm_config_before: '2018-04-01T00:00:00Z' };
+ const descriptor = '[email protected]';
+ const boundedProbe = ['[email protected]', '[email protected] - 7.0.0'];
+ const resolve = () =>
+ resolveRegistryLaunch(registryPackage(descriptor, 'npx', env), null, log);
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ vi.setSystemTime(new Date('2026-09-17T00:00:00Z'));
+ const first = await resolve();
+ expect(first.args).toEqual(['-y', '[email protected]', '--version']);
+ expect(probedDescriptors(probeLog)).toEqual(boundedProbe);
+
+ vi.setSystemTime(new Date('2026-09-17T00:30:00Z'));
+ const withinWindow = await resolve();
+ expect(withinWindow.args).toEqual(first.args);
+ expect(probedDescriptors(probeLog)).toEqual(boundedProbe);
+
+ vi.setSystemTime(new Date(Date.now() + HOUR_MS));
+ const afterWindow = await resolve();
+ expect(afterWindow.args).toEqual(first.args);
+ expect(probedDescriptors(probeLog)).toEqual([...boundedProbe, ...boundedProbe]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ });
+
+ test('an exact pin stays acquired for the process however long it is held', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingNpmBin(home);
+ const env = { PATH: bin };
+ const resolve = () =>
+ resolveRegistryLaunch(registryPackage('[email protected]', 'npx', env), null, log);
+ vi.useFakeTimers({ toFake: ['Date'] });
+ try {
+ vi.setSystemTime(new Date('2026-09-17T00:00:00Z'));
+ const first = await resolve();
+
+ vi.setSystemTime(new Date(Date.now() + 48 * HOUR_MS));
+ const later = await resolve();
+
+ expect(later.args).toEqual(first.args);
+ expect(probedDescriptors(probeLog)).toEqual(['[email protected]']);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ });
+
+ test('overlapping opens of one pinned adapter share a single probe', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog, entered, release } = gatedNpmBin(home, 'admit');
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const resolve = () =>
+ resolveRegistryLaunch(registryPackage(descriptor, 'npx', env), null, log);
+
+ const first = resolve();
+ const second = resolve();
+ await awaitGate(entered);
+ writeFileSync(release, '');
+ const [opened, alsoOpened] = await Promise.all([first, second]);
+
+ expect(opened.args).toEqual(['-y', descriptor, '--version']);
+ expect(alsoOpened.args).toEqual(opened.args);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor]);
+ });
+ }, 30_000);
+
+ test('an open that joins a probe already running for its pin is reported as joined', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog, entered, release } = gatedNpmBin(home, 'admit');
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const sources: string[] = [];
+ const acquisition = {
+ onResolved: (resolution: { source: string }) => {
+ sources.push(resolution.source);
+ },
+ };
+ const open = (): Promise<ResolvedLaunch | null> =>
+ resolveRegistryLaunch(
+ registryPackage(descriptor, 'npx', env),
+ null,
+ log,
+ undefined,
+ (candidate) => Promise.resolve(candidate),
+ acquisition,
+ );
+
+ const first = open();
+ await awaitGate(entered);
+ const second = open();
+ writeFileSync(release, '');
+ const [opened, alsoOpened] = await Promise.all([first, second]);
+
+ expect(opened?.args).toEqual(['-y', descriptor, '--version']);
+ expect(alsoOpened?.args).toEqual(opened?.args);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor]);
+ expect(
+ sources,
+ 'a caller that joined an open probe must not be reported as having originated it',
+ ).toEqual(['probe', 'joined']);
+ });
+ }, 30_000);
+
+ test('a failed acquisition is not remembered, so the next open probes again', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog, release } = gatedNpmBin(home, 'refuse');
+ writeFileSync(release, '');
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const resolve = () =>
+ resolveRegistryLaunch(registryPackage(descriptor, 'npx', env), null, log);
+
+ const refused = await resolve().catch((error: unknown) => error);
+ expect(refused).toBeInstanceOf(AgentLaunchError);
+
+ const recovered = await resolve();
+
+ expect(recovered.args).toEqual(['-y', descriptor, '--version']);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor, descriptor]);
+ });
+ }, 30_000);
+
+ test('an acquisition that found no npm sibling is attempted again on the next open', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = acquisitionBin(home);
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const resolve = () =>
+ resolveRegistryLaunch(registryPackage(descriptor, 'npx', env), null, log);
+
+ const forwarded = await resolve();
+ expect(forwarded.args).toEqual(['-y', descriptor, '--version']);
+ expect(probedDescriptors(probeLog)).toEqual([]);
+
+ writeRecordingNpm(bin, probeLog);
+ const probed = await resolve();
+
+ expect(probed.args).toEqual(['-y', descriptor, '--version']);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor]);
+ });
+ });
+
+ test('a failing probe that outlives a reset does not evict the entry that replaced it', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog, entered, release } = gatedNpmBin(home, 'refuse');
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const resolve = () =>
+ resolveRegistryLaunch(registryPackage(descriptor, 'npx', env), null, log);
+
+ const stalled = resolve().catch((error: unknown) => error);
+ await awaitGate(entered);
+ resetAcquisitionCache();
+ const replacement = await resolve();
+ writeFileSync(release, '');
+ expect(replacement.args).toEqual(['-y', descriptor, '--version']);
+ expect(await stalled).toBeInstanceOf(AgentLaunchError);
+
+ const reused = await resolve();
+
+ expect(reused.args).toEqual(replacement.args);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor, descriptor]);
+ });
+ }, 30_000);
+
+ test('a refused re-acquisition still serves the held pin to an open that never asked for one', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog, entered, release } = retryRefusingNpmBin(home);
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const open = (acquisition?: { reacquire: true }) => pinnedOpen(descriptor, env, acquisition);
+ const acquired = ['-y', descriptor, '--version'];
+
+ const cold = await open();
+ expect(cold?.args).toEqual(acquired);
+
+ const retried = open({ reacquire: true }).catch((error: unknown) => error);
+ await awaitGate(entered);
+ const bystander = open().catch((error: unknown) => error);
+ writeFileSync(release, '');
+
+ expect(await retried).toBeInstanceOf(AgentLaunchError);
+ expect(
+ await bystander,
+ 'an open that never asked to re-acquire must not inherit the retry failure',
+ ).toMatchObject({ args: acquired });
+
+ const afterRefusal = await open();
+
+ expect(afterRefusal?.args).toEqual(acquired);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor, descriptor]);
+ });
+ }, 30_000);
+
+ test('a re-acquisition joins the probe already open for its pin', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog, entered, release } = gatedNpmBin(home, 'admit');
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const open = (acquisition?: { reacquire: true }) => pinnedOpen(descriptor, env, acquisition);
+
+ const cold = open();
+ await awaitGate(entered);
+ const retried = open({ reacquire: true });
+ writeFileSync(release, '');
+ const [opened, reacquired] = await Promise.all([cold, retried]);
+
+ expect(opened?.args).toEqual(['-y', descriptor, '--version']);
+ expect(reacquired?.args).toEqual(opened?.args);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor]);
+ });
+ }, 30_000);
+
+ test('a re-acquisition joins a refresh already open over the held pin', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog, entered, release } = retryRefusingNpmBin(home);
+ const env = { PATH: bin };
+ const descriptor = '[email protected]';
+ const open = (acquisition?: { reacquire: true }) => pinnedOpen(descriptor, env, acquisition);
+ const acquired = ['-y', descriptor, '--version'];
+
+ const cold = await open();
+ expect(cold?.args).toEqual(acquired);
+
+ const retried = open({ reacquire: true }).catch((error: unknown) => error);
+ await awaitGate(entered);
+ const alsoRetried = open({ reacquire: true }).catch((error: unknown) => error);
+ writeFileSync(release, '');
+
+ expect(await retried).toBeInstanceOf(AgentLaunchError);
+ expect(
+ await alsoRetried,
+ 'a re-acquisition arriving over a refresh already in flight must share it rather than open a second probe',
+ ).toBeInstanceOf(AgentLaunchError);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor, descriptor]);
+
+ const afterRefusal = await open();
+
+ expect(afterRefusal?.args).toEqual(acquired);
+ expect(probedDescriptors(probeLog)).toEqual([descriptor, descriptor]);
+ });
+ }, 30_000);
+
+ test('an unreachable registry still launches a pin the local npm cache can answer', async () => {
+ await withLocalAcquisitionRegistry(async (home, control) => {
+ const warm = await npmNative([
+ 'pack',
+ '--dry-run',
+ '--ignore-scripts',
+ '--json',
+ ]);
+ expect(warm.code, warm.stderr).toBe(0);
+
+ await control.closeRegistry();
+
+ const uncached = await npmNative([
+ 'pack',
+ '@agentclientprotocol/[email protected]',
+ '--dry-run',
+ '--ignore-scripts',
+ '--json',
+ ]);
+ expect(uncached.code, `${home}: the registry must be unreachable`).not.toBe(0);
+ expect(uncached.stderr).toContain('ECONNREFUSED');
+
+ const offline = await npmNative([
+ 'pack',
+ '--dry-run',
+ '--ignore-scripts',
+ '--json',
+ '--offline',
+ ]);
+ expect(offline.code, 'the local cache must hold an answer').toBe(0);
+
+ const launch = await resolveRegistryLaunch(registryPackage('[email protected]'), null, log);
+ expect(launch.args).toEqual(['-y', '[email protected]', '--version']);
+
+ const refused = await resolveRegistryLaunch(
+ registryPackage('@agentclientprotocol/[email protected]'),
+ null,
+ log,
+ ).catch((error: unknown) => error);
+ expect(
+ refused,
+ 'a pin the cache cannot answer must fail acquisition rather than reach npx unvalidated',
+ ).toBeInstanceOf(AgentLaunchError);
+ expect(refused).toMatchObject({
+ code: 'install-failed',
+ machineDetail: expect.stringContaining('ECONNREFUSED'),
+ });
+ });
+ }, 90_000);
+});
diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.ts
index b0303987d..3777d0e79 100644
--- a/packages/server/src/acp/launch.ts
+++ b/packages/server/src/acp/launch.ts
@@ -97,6 +97,24 @@ export function withHostedAgentMarker(env: Record<string, string>): Record<strin
type PrepareRegistryLaunch = (launch: ResolvedLaunch) => Promise<ResolvedLaunch | null>;
+type ProbedNpmOutcome = 'exact' | 'release-age-bounded';
+
+type NpmPackageResolution = {
+ outcome: 'forwarded' | ProbedNpmOutcome;
+ acquired: string;
+ elapsedMs: number;
+};
+
+type ResolvedNpmAcquisition =
+ | { outcome: ProbedNpmOutcome; acquired: string; source: 'memo'; elapsedMs: 0 }
+ | (NpmPackageResolution & { source: 'probe' | 'joined' });
+
+type NpmAcquisitionOptions = {
+ reacquire?: boolean;
+ onProbeStart?: () => void;
+ onResolved?: (resolution: ResolvedNpmAcquisition) => void;
+};
+
export function resolveRegistryLaunch(
agent: RegistryAgent,
platformKey: string | null,
@@ -109,6 +127,7 @@ export function resolveRegistryLaunch(
log: PinoLogger,
binaryCacheDir: string | undefined,
prepare: PrepareRegistryLaunch,
+ acquisition?: NpmAcquisitionOptions,
): Promise<ResolvedLaunch | null>;
export async function resolveRegistryLaunch(
agent: RegistryAgent,
@@ -116,6 +135,7 @@ export async function resolveRegistryLaunch(
log: PinoLogger,
binaryCacheDir: string = defaultBinaryCacheDir(),
prepare?: PrepareRegistryLaunch,
+ acquisition?: NpmAcquisitionOptions,
): Promise<ResolvedLaunch | null> {
const dist = agent.distribution;
if (dist.npx !== undefined) {
@@ -133,7 +153,13 @@ export async function resolveRegistryLaunch(
dist.npx.package,
);
if (pin?.groups === undefined) return launch;
- const selected = await acquireNpmPackage(launch, pin.groups.name, pin.groups.version, log);
+ const selected = await acquireNpmPackage(
+ launch,
+ pin.groups.name,
+ pin.groups.version,
+ log,
+ acquisition,
+ );
return { ...launch, args: ['-y', selected, ...(dist.npx.args ?? [])] };
}
if (dist.uvx !== undefined) {
@@ -306,12 +332,111 @@ async function probeNpmPackage(
}
}
-async function acquireNpmPackage(
+const ACQUISITION_FRESHNESS_MS = 60 * 60 * 1000;
+
+type HeldNpmPackage = {
+ acquired: string;
+ outcome: ProbedNpmOutcome;
+ probedAt: number;
+};
+
+type AcquiredNpmPackage =
+ | { state: 'probing'; probe: Promise<NpmPackageResolution> }
+ | ({ state: 'held' } & HeldNpmPackage)
+ | ({ state: 'revalidating'; probe: Promise<NpmPackageResolution> } & HeldNpmPackage);
+
+const acquiredNpmPackages = new Map<string, AcquiredNpmPackage>();
+
+export function resetAcquisitionCache(): void {
+ acquiredNpmPackages.clear();
+}
+
+function acquisitionKey(launch: ResolvedLaunch, name: string, ceiling: string): string {
+ const env = Object.entries(launch.env).sort(([left], [right]) =>
+ left < right ? -1 : left > right ? 1 : 0,
+ );
+ return JSON.stringify([launch.cmd, env, name, ceiling]);
+}
+
+function heldNpmPackage(entry: AcquiredNpmPackage | undefined): HeldNpmPackage | null {
+ return entry === undefined || entry.state === 'probing' ? null : entry;
+}
+
+function openNpmProbe(entry: AcquiredNpmPackage | undefined): Promise<NpmPackageResolution> | null {
+ return entry === undefined || entry.state === 'held' ? null : entry.probe;
+}
+
+function heldPackageStillCurrent(held: HeldNpmPackage): boolean {
+ return held.outcome === 'exact' || Date.now() - held.probedAt < ACQUISITION_FRESHNESS_MS;
+}
+
+function acquireNpmPackage(
launch: ResolvedLaunch,
name: string,
ceiling: string,
log: PinoLogger,
+ acquisition?: NpmAcquisitionOptions,
): Promise<string> {
+ const key = acquisitionKey(launch, name, ceiling);
+ const cached = acquiredNpmPackages.get(key);
+ const held = heldNpmPackage(cached);
+ if (acquisition?.reacquire !== true && held !== null && heldPackageStillCurrent(held)) {
+ acquisition?.onResolved?.({
+ acquired: held.acquired,
+ outcome: held.outcome,
+ source: 'memo',
+ elapsedMs: 0,
+ });
+ return Promise.resolve(held.acquired);
+ }
+ const joined = openNpmProbe(cached);
+ const probe = joined ?? beginNpmAcquisition(key, held, launch, name, ceiling, log, acquisition);
+ const source: 'probe' | 'joined' = joined === null ? 'probe' : 'joined';
+ return probe.then((resolved) => {
+ acquisition?.onResolved?.({ ...resolved, source });
+ return resolved.acquired;
+ });
+}
+
+function beginNpmAcquisition(
+ key: string,
+ held: HeldNpmPackage | null,
+ launch: ResolvedLaunch,
+ name: string,
+ ceiling: string,
+ log: PinoLogger,
+ acquisition?: NpmAcquisitionOptions,
+): Promise<NpmPackageResolution> {
+ const probe = acquireNpmPackageUncached(launch, name, ceiling, log, acquisition);
+ const entry: AcquiredNpmPackage =
+ held === null ? { state: 'probing', probe } : { ...held, state: 'revalidating', probe };
+ acquiredNpmPackages.set(key, entry);
+ const replace = (next: AcquiredNpmPackage | null): void => {
+ if (acquiredNpmPackages.get(key) !== entry) return;
+ if (next === null) acquiredNpmPackages.delete(key);
+ else acquiredNpmPackages.set(key, next);
+ };
+ const restore = (): void => replace(held === null ? null : { ...held, state: 'held' });
+ void probe.then((resolved) => {
+ if (resolved.outcome === 'forwarded') restore();
+ else
+ replace({
+ state: 'held',
+ acquired: resolved.acquired,
+ outcome: resolved.outcome,
+ probedAt: Date.now(),
+ });
+ }, restore);
+ return probe;
+}
+
+async function acquireNpmPackageUncached(
+ launch: ResolvedLaunch,
+ name: string,
+ ceiling: string,
+ log: PinoLogger,
+ acquisition?: NpmAcquisitionOptions,
+): Promise<NpmPackageResolution> {
let descriptor = `${name}@${ceiling}`;
const npm = await npmCommand(launch);
if (npm === null) {
@@ -319,8 +444,10 @@ async function acquireNpmPackage(
{ package: descriptor },
'[acp-launch] package acquisition probe skipped: no executable npm sibling; forwarding the catalog pin to npx',
);
- return descriptor;
+ return { outcome: 'forwarded', acquired: descriptor, elapsedMs: 0 };
}
+ acquisition?.onProbeStart?.();
+ const probeStartedAt = Date.now();
let result = await probeNpmPackage(launch, descriptor, npm);
let bounded = false;
if (result.code !== 0 && datedNpmRefusal(result.detail)) {
@@ -359,7 +486,11 @@ async function acquireNpmPackage(
{ machineDetail: result.detail },
);
}
- return `${name}@${selected.version}`;
+ return {
+ outcome: bounded ? 'release-age-bounded' : 'exact',
+ acquired: `${name}@${selected.version}`,
+ elapsedMs: Date.now() - probeStartedAt,
+ };
}
export function resolveCustomLaunch(entry: CustomAgentEntry): ResolvedLaunch {
@@ -628,6 +759,16 @@ export function declinedRepairHint(launch: ResolvedLaunch): string {
return `OK's own copy of ${runtime} is damaged and can't run this agent. Start the agent again to let OK download a fresh copy.`;
}
+export function expiredRepairHint(launch: ResolvedLaunch): string {
+ const runtime = launch.kind === 'uvx' ? 'uv' : 'Node.js';
+ return `OK's own copy of ${runtime} is damaged and can't run this agent. The offer to download a fresh copy expired before it was answered — start the agent again to get it back.`;
+}
+
+export function expiredFallbackHint(launch: ResolvedLaunch, base: string): string {
+ const runtime = launch.kind === 'uvx' ? 'uv' : 'Node.js';
+ return `${base} The offer to download a private copy of ${runtime} expired before it was answered — start the agent again to get it back.`;
+}
+
const PROBE_OUTPUT_MAX = 2_000;
const PROBE_DETAIL_MAX = 300;
@@ -786,6 +927,10 @@ export function incompatibleNodeHint(launch: ResolvedLaunch, detail: string): st
return `\`${launch.cmd}\` cannot run this agent with the selected Node.js runtime (${detail}). Upgrade Node.js or let Open Knowledge download a private compatible copy.`;
}
+export function expiredIncompatibleNodeHint(launch: ResolvedLaunch, detail: string): string {
+ return `\`${launch.cmd}\` cannot run this agent with the selected Node.js runtime (${detail}). The offer to download a private compatible copy of Node.js expired before it was answered — upgrade Node.js, or start the agent again to get it back.`;
+}
+
export function envPath(env: Record<string, string>): string | undefined {
for (const [k, v] of Object.entries(env)) {
if (k.toLowerCase() === 'path') return v;
diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.ts
index 420b93caf..f2eb92230 100644
--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts
+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts
@@ -16,7 +16,12 @@ import type {
ThreadEvent,
ThreadServerFrame,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
-import { afterEach, describe, expect, test } from 'vitest';
+import { THREAD_REOPEN_OP_TIMEOUT_MS } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+const BLOCKING_CONSENT_BUDGET_MS = Math.floor(THREAD_REOPEN_OP_TIMEOUT_MS / 2);
+const OPEN_PATH_CONSENT_BUDGET_MS = 5 * 60 * 1000;
+
import { ZipFile } from 'yazl';
import type { AgentSessionManager } from '../agent-sessions.ts';
import { getLogger } from '../logger.ts';
@@ -239,6 +244,17 @@ describe('package admission after runtime preparation', () => {
await expect
.poll(() => manager.getInfo(info.threadId)?.status, { timeout: 25_000 })
.toBe('error');
+ if (source === 'managed') {
+ const consentAt = events.findIndex((event) => event.kind === 'runtime_consent_request');
+ expect(consentAt).toBeGreaterThanOrEqual(0);
+ const afterConsent = events
+ .slice(consentAt)
+ .flatMap((event) => (event.kind === 'status' ? [event.status] : []));
+ expect(
+ afterConsent,
+ 'a managed runtime that really downloads must report installing',
+ ).toContain('installing');
+ }
expect(
existsSync(admissionLog),
'selected npm must perform admission before ACP starts',
@@ -308,8 +324,12 @@ describe('package admission after runtime preparation', () => {
.toBe('error');
}
expect(existsSync(join(home, 'npm-cache', '_cacache'))).toBe(false);
+ const consentAt = events.findIndex((event) => event.kind === 'runtime_consent_request');
+ expect(consentAt).toBeGreaterThanOrEqual(0);
expect(
- events.some((event) => event.kind === 'status' && event.status === 'spawning'),
+ events
+ .slice(consentAt)
+ .some((event) => event.kind === 'status' && event.status === 'spawning'),
).toBe(false);
} finally {
await manager.destroy();
@@ -515,6 +535,60 @@ describe('managed-runtime consent + download flow', () => {
expect(errEvent?.detail).toContain(`Node.js ${MINIMUM_NPX_NODE_MAJOR} or newer is required`);
}, 20_000);
+ test('letting the incompatible-Node offer expire drops the offer it just withdrew', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ const runtimeRoot = tmp();
+ const oldBin = tmp();
+ writeFileSync(join(oldBin, 'npx'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ writeNodeVersion(oldBin, 'v16.14.2');
+ const manager = makeManager({
+ contentDir,
+ localDir,
+ runtimeRoot,
+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'x'.repeat(64), {
+ ...NPX_AGENT,
+ distribution: { npx: { package: '@fake/agent', env: { PATH: oldBin } } },
+ }),
+ });
+
+ const events: ThreadEvent[] = [];
+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ await collect(manager, info.threadId, events);
+ await waitFor(() => findConsentRequest(events) !== undefined, 10_000, 'consent request');
+ await vi.advanceTimersByTimeAsync(OPEN_PATH_CONSENT_BUDGET_MS + 1_000);
+ await waitFor(
+ () => events.some((e) => e.kind === 'runtime_consent_resolved'),
+ 10_000,
+ 'the offer to expire on the budget the start is waiting on',
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ const resolved = events.find(
+ (e): e is Extract<ThreadEvent, { kind: 'runtime_consent_resolved' }> =>
+ e.kind === 'runtime_consent_resolved',
+ );
+ expect(resolved?.decision).toBe('timeout');
+ await waitFor(
+ () => events.some((e) => e.kind === 'status' && e.status === 'error'),
+ 20_000,
+ 'incompatible runtime error',
+ );
+ const expiredEvent = events.find(
+ (e): e is Extract<ThreadEvent, { kind: 'status' }> =>
+ e.kind === 'status' && e.status === 'error',
+ );
+ expect(expiredEvent?.detail).toContain('Node.js v16.14.2 is incompatible');
+ expect(expiredEvent?.detail).toContain('expired before it was answered');
+ expect(
+ expiredEvent?.detail,
+ 'offering the download again would contradict the sentence reporting that the offer lapsed',
+ ).not.toContain('let Open Knowledge download a private compatible copy');
+ }, 30_000);
+
test.skipIf(process.platform === 'win32')(
'a compatible login-shell Node replaces a stale GUI-inherited Node',
async () => {
@@ -792,6 +866,55 @@ describe('interpreter health probe', () => {
expect(errEvent?.detail).not.toContain("isn't installed");
}, 30_000);
+ test('letting the repair offer expire says it lapsed, not that it was declined', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ const runtimeRoot = tmp();
+ const stage = tmp();
+ const { bytes, sha } = fakeNodeTarball(stage);
+ const fetchImpl = fakeNodeFetch(bytes, sha);
+ const installed = await ensureManagedRuntime('node', log, { root: runtimeRoot, fetchImpl });
+ const launcher = installed.kind === 'node' ? installed.npxBin : installed.uvxBin;
+ writeFileSync(launcher, '#!/bin/sh\nkill -ABRT $$\n', { mode: 0o755 });
+
+ const manager = makeManager({ contentDir, localDir, runtimeRoot, fetchImpl });
+ const events: ThreadEvent[] = [];
+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ await collect(manager, info.threadId, events);
+ await waitFor(() => findConsentRequest(events) !== undefined, 10_000, 'repair offer');
+ await vi.advanceTimersByTimeAsync(OPEN_PATH_CONSENT_BUDGET_MS + 1_000);
+ await waitFor(
+ () => events.some((e) => e.kind === 'runtime_consent_resolved'),
+ 10_000,
+ 'the offer to expire on the budget the start is waiting on',
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ const resolved = events.find(
+ (e): e is Extract<ThreadEvent, { kind: 'runtime_consent_resolved' }> =>
+ e.kind === 'runtime_consent_resolved',
+ );
+ expect(resolved?.decision).toBe('timeout');
+ await waitFor(
+ () => events.some((e) => e.kind === 'status' && e.status === 'error'),
+ 20_000,
+ 'error status',
+ );
+
+ const errEvent = events.find(
+ (e): e is Extract<ThreadEvent, { kind: 'status' }> =>
+ e.kind === 'status' && e.status === 'error',
+ );
+ expect(errEvent?.detail).toContain('damaged');
+ expect(errEvent?.detail).toContain('expired before it was answered');
+ expect(errEvent?.detail).not.toContain(
+ 'Start the agent again to let OK download a fresh copy.',
+ );
+ }, 30_000);
+
test('Retry re-probes an interpreter that broke after it was cached healthy', async () => {
const contentDir = tmp();
const localDir = tmp();
@@ -830,6 +953,78 @@ describe('interpreter health probe', () => {
);
}, 30_000);
+ test('Retry gives the runtime offer the budget the caller is waiting on', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ const runtimeRoot = tmp();
+ const binDir = tmp();
+ const npxPath = join(binDir, 'npx');
+ writeFileSync(npxPath, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ writeNodeVersion(binDir, 'v24.0.0');
+ const manager = makeManager({
+ contentDir,
+ localDir,
+ runtimeRoot,
+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'x'.repeat(64), {
+ ...NPX_AGENT,
+ distribution: { npx: { package: '@fake/agent', env: { PATH: binDir } } },
+ }),
+ });
+
+ const events: ThreadEvent[] = [];
+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });
+ await collect(manager, info.threadId, events);
+ await waitFor(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 10_000,
+ 'the thread to fail',
+ );
+
+ writeFileSync(npxPath, '#!/bin/sh\nkill -ABRT $$\n', { mode: 0o755 });
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ void manager.retryThread(info.threadId).catch(() => {});
+ await waitFor(
+ () => findConsentRequest(events) !== undefined,
+ 10_000,
+ 'the retry to offer the managed runtime',
+ );
+
+ await vi.advanceTimersByTimeAsync(BLOCKING_CONSENT_BUDGET_MS + 1_000);
+ await waitFor(
+ () => events.some((e) => e.kind === 'runtime_consent_resolved'),
+ 10_000,
+ 'the offer to expire on the budget the client is waiting on',
+ );
+ const resolved = events.find(
+ (e): e is Extract<ThreadEvent, { kind: 'runtime_consent_resolved' }> =>
+ e.kind === 'runtime_consent_resolved',
+ );
+ expect(resolved?.decision).toBe('timeout');
+
+ await waitFor(
+ () => events.filter((e) => e.kind === 'status' && e.status === 'error').length >= 2,
+ 10_000,
+ 'the retry to surface the expired offer',
+ );
+ const surfaced = events
+ .filter(
+ (e): e is Extract<ThreadEvent, { kind: 'status' }> =>
+ e.kind === 'status' && e.status === 'error',
+ )
+ .at(-1);
+ expect(surfaced?.detail).toContain('expired before it was answered');
+ expect(
+ surfaced?.detail,
+ 'the expiry sentence is shared with the incompatible-Node route, so it cannot pin this one',
+ ).toContain('is installed but failed to run');
+ expect(surfaced?.detail).toContain('Reinstall or repair Node.js');
+ expect(surfaced?.detail).not.toContain("isn't installed");
+ } finally {
+ vi.useRealTimers();
+ }
+ }, 60_000);
+
test('a healthy interpreter is probed once, not once per thread', async () => {
const contentDir = tmp();
const localDir = tmp();
diff --git a/packages/server/src/acp/package-acquisition.test-helper.ts b/packages/server/src/acp/package-acquisition.test-helper.ts
index 24832242e..06df22fa5 100644
--- a/packages/server/src/acp/package-acquisition.test-helper.ts
+++ b/packages/server/src/acp/package-acquisition.test-helper.ts
@@ -15,6 +15,7 @@ import { z } from 'zod';
import {
npmPackResult,
type ResolvedLaunch,
+ resetAcquisitionCache,
resolveWindowsCommand,
spawnAcpAgent,
terminateAgentTree,
@@ -51,6 +52,27 @@ export function installNodeFixture(bin: string): void {
else symlinkSync(process.execPath, join(bin, 'node'));
}
+export function writeRecordingNpm(bin: string, probeLog: string): void {
+ writeExecutable(
+ join(bin, 'npm'),
+ `require('node:fs').appendFileSync(${JSON.stringify(probeLog)}, JSON.stringify(process.argv.slice(2)) + '\\n');
+ const spec = process.argv[3];
+ const at = spec.lastIndexOf('@');
+ const range = spec.slice(at + 1);
+ const version = range.includes(' - ') ? range.split(' - ')[1] : range;
+ process.stdout.write(JSON.stringify([{ name: spec.slice(0, at), version }]));`,
+ );
+}
+
+export function probedDescriptors(probeLog: string): string[] {
+ if (!existsSync(probeLog)) return [];
+ return readFileSync(probeLog, 'utf8')
+ .trim()
+ .split('\n')
+ .filter((line) => line !== '')
+ .map((line) => (JSON.parse(line) as string[])[1] ?? '');
+}
+
export function withAcquisitionHome<T>(run: (home: string) => Promise<T>): Promise<T> {
return acquisitionHome(run, false);
}
@@ -100,6 +122,7 @@ async function acquisitionHome<T>(run: (home: string) => Promise<T>, network: bo
for (const [key, value] of Object.entries(env)) if (value !== undefined) process.env[key] = value;
writeFileSync(join(home.path, '.npmrc'), '');
writeFileSync(join(home.path, 'global.npmrc'), '');
+ resetAcquisitionCache();
try {
return await run(home.path);
} finally {
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
index 0715a6c6d..fcfe5e718 100644
--- a/packages/server/src/acp/thread-manager.integration.test.ts
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -8,7 +8,8 @@ import type {
ThreadInfo,
ThreadServerFrame,
} from '@inkeep/open-knowledge-core/acp/thread-protocol';
-import { afterEach, describe, expect, test } from 'vitest';
+import { THREAD_REOPEN_OP_TIMEOUT_MS } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import codexFixture from '../../../../test-support/fixtures/codex-legacy-warning-envelopes.json' with {
type: 'json',
@@ -21,8 +22,11 @@ import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper
import {
installNodeFixture,
npmCli,
+ probedDescriptors,
registryPackage,
+ withAcquisitionHome,
writeExecutable,
+ writeRecordingNpm,
} from './package-acquisition.test-helper.ts';
import { AcpPermissionStore } from './permissions.ts';
import { AcpRegistry } from './registry.ts';
@@ -34,6 +38,7 @@ import {
} from './thread-manager.ts';
const log = getLogger('acp-thread-test');
+const BLOCKING_CONSENT_BUDGET_MS = Math.floor(THREAD_REOPEN_OP_TIMEOUT_MS / 2);
const EXAMPLE_AGENT = join(
dirname(Bun.resolveSync('@agentclientprotocol/sdk', import.meta.dirname)),
@@ -73,6 +78,7 @@ function makeManager(
unwatchedTurnKillMs?: number;
isIgnoredPath?: (relPosix: string) => boolean;
registry?: AcpRegistry;
+ runtimeInstall?: AcpThreadManagerOptions['runtimeInstall'];
resolveLoginShellPath?: () => Promise<string | null>;
agentPresenceBroadcaster?: AgentPresenceBroadcaster;
sessionManager?: AgentSessionManager;
@@ -405,6 +411,15 @@ async function waitUntil(pred: () => boolean, ms: number, what: string): Promise
}
}
+async function statusesOf(manager: AcpThreadManager, threadId: string): Promise<string[]> {
+ const statuses: string[] = [];
+ await manager.subscribe(threadId, 0, (frame) => {
+ const events = frame.op === 'event' ? [frame.event] : frame.op === 'events' ? frame.events : [];
+ for (const event of events) if (event.kind === 'status') statuses.push(event.status);
+ });
+ return statuses;
+}
+
describe('AcpThreadManager (real subprocess)', () => {
test('runs a full turn against the SDK example agent, permission round-trip included', async () => {
expect(existsSync(EXAMPLE_AGENT)).toBe(true);
@@ -420,7 +435,7 @@ describe('AcpThreadManager (real subprocess)', () => {
const events: Array<{ seq: number; event: ThreadEvent }> = [];
const info = await manager.createThread({ agent: { source: 'custom', id: 'example' } });
- expect(['installing', 'spawning']).toContain(info.status);
+ expect(info.status).toBe('spawning');
await manager.subscribe(info.threadId, 0, (frame: ThreadServerFrame) => {
if (frame.op === 'event') events.push({ seq: frame.seq, event: frame.event });
if (frame.op === 'events') {
@@ -979,12 +994,8 @@ process.stdin.on('data', (chunk) => {
}, 30_000);
});
-function writeResumableAgentEntry(localDir: string, id: string, env: Record<string, string>): void {
- const agentPath = join(localDir, `${id}.mjs`);
- writeFileSync(
- agentPath,
- `
-import { appendFileSync } from 'node:fs';
+const RESUMABLE_AGENT_SOURCE = `
+const { appendFileSync } = process.getBuiltinModule('node:fs');
const caps = (process.env.FAKE_CAPS ?? '').split(',').filter(Boolean);
const withConfig = process.env.FAKE_CONFIG === '1';
const withModes = process.env.FAKE_MODES === '1';
@@ -1097,8 +1108,11 @@ process.stdin.on('data', (chunk) => {
}
}
});
-`,
- );
+`;
+
+function writeResumableAgentEntry(localDir: string, id: string, env: Record<string, string>): void {
+ const agentPath = join(localDir, `${id}.mjs`);
+ writeFileSync(agentPath, RESUMABLE_AGENT_SOURCE);
writeFileSync(
join(localDir, 'acp-agents.json'),
JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath], env }]),
@@ -5581,3 +5595,459 @@ describe.skipIf(process.platform === 'win32')('a typed session notice mid-turn',
expect(thread.manager.getInfo(thread.threadId)?.status).toBe('ready');
}, 60_000);
});
+
+describe('status frames for an open that installs nothing', () => {
+ test('a custom agent start never reports installing', async () => {
+ const localDir = tmp();
+ writeExampleAgentEntry(localDir);
+ const manager = makeManager(tmp(), localDir);
+
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'example' } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 15_000,
+ 'the custom agent to become ready',
+ );
+
+ const statuses = await statusesOf(manager, info.threadId);
+ expect(info.status).toBe('spawning');
+ expect(statuses[0]).toBe('spawning');
+ expect(statuses).not.toContain('installing');
+ }, 30_000);
+
+ test('a custom agent retry never reports installing', async () => {
+ const localDir = tmp();
+ writeRequestingAgentEntry(
+ localDir,
+ 'retry-no-install',
+ "write({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: 'prompt failed' } });",
+ );
+ const manager = makeManager(tmp(), localDir);
+
+ const info = await manager.createThread({
+ agent: { source: 'custom', id: 'retry-no-install' },
+ });
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');
+ manager.sendPrompt(info.threadId, 'fail this turn');
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 15_000,
+ 'the prompt failure',
+ );
+ writeRequestingAgentEntry(localDir, 'retry-no-install', 'finish();');
+ const beforeRetry = (await statusesOf(manager, info.threadId)).length;
+
+ expect((await manager.retryThread(info.threadId)).status).toBe('ready');
+
+ const afterRetry = (await statusesOf(manager, info.threadId)).slice(beforeRetry);
+ expect(afterRetry[0]).toBe('spawning');
+ expect(afterRetry).not.toContain('installing');
+ }, 45_000);
+
+ test('a custom agent resume never reports installing', async () => {
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'resume-no-install', { FAKE_CAPS: 'resume,load' });
+ const manager = makeManager(tmp(), localDir);
+ await manager.init();
+
+ const info = await manager.createThread({
+ agent: { source: 'custom', id: 'resume-no-install' },
+ });
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');
+ manager.sendPrompt(info.threadId, 'retain this session');
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'turn ended');
+ await manager.closeThread(info.threadId);
+ const beforeResume = (await statusesOf(manager, info.threadId)).length;
+
+ await manager.resumeThread(info.threadId);
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 15_000,
+ 'the resumed thread to become ready',
+ );
+
+ const afterResume = (await statusesOf(manager, info.threadId)).slice(beforeResume);
+ expect(afterResume[0]).toBe('spawning');
+ expect(afterResume).not.toContain('installing');
+ }, 45_000);
+});
+
+describe('registry adapter acquisition probe scope across thread opens', () => {
+ const PINNED_ADAPTER = 'probe-scope-manager-fixture';
+ const PINNED_DESCRIPTOR = `${PINNED_ADAPTER}@7.0.0`;
+
+ const acquisitionBin = (home: string, agentSource: string): { bin: string; probeLog: string } => {
+ const bin = join(home, 'bin');
+ mkdirSync(bin);
+ installNodeFixture(bin);
+ const probeLog = join(home, 'probes.log');
+ writeExecutable(
+ join(bin, 'npx'),
+ `if (process.argv.slice(2).join(' ') === '--version') process.exit(0);\n${agentSource}`,
+ );
+ writeRecordingNpm(bin, probeLog);
+ return { bin, probeLog };
+ };
+
+ const recordingAcquisitionBin = (home: string): { bin: string; probeLog: string } =>
+ acquisitionBin(
+ home,
+ `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 reply = { jsonrpc: '2.0', id: JSON.parse(line).id, error: { code: -32603, message: 'fixture adapter declines to initialize' } };
+ process.stdout.write(JSON.stringify(reply) + '\\n');
+ }
+ });`,
+ );
+
+ const resumableAcquisitionBin = (home: string): { bin: string; probeLog: string } =>
+ acquisitionBin(home, RESUMABLE_AGENT_SOURCE);
+
+ const pinnedAdapterManager = (
+ home: string,
+ bin: string,
+ env?: Record<string, string>,
+ ): { agentId: string; manager: AcpThreadManager } => {
+ const localDir = tmp();
+ const agent = registryPackage(PINNED_DESCRIPTOR, 'npx', { PATH: bin, ...env });
+ const registry = new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),
+ });
+ return { agentId: agent.id, manager: makeManager(home, localDir, { registry }) };
+ };
+
+ test('two thread opens of one pinned registry adapter acquire it once', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingAcquisitionBin(home);
+ const { agentId, manager } = pinnedAdapterManager(home, bin);
+
+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(first.threadId)?.status === 'error',
+ 20_000,
+ 'the first open to settle',
+ );
+ const second = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(second.threadId)?.status === 'error',
+ 20_000,
+ 'the second open to settle',
+ );
+
+ expect(probedDescriptors(probeLog)).toEqual([PINNED_DESCRIPTOR]);
+ });
+ }, 60_000);
+
+ test('a retry re-acquires the pinned adapter instead of reusing the open probe', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingAcquisitionBin(home);
+ const { agentId, manager } = pinnedAdapterManager(home, bin);
+
+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 20_000,
+ 'the open to settle',
+ );
+ expect(probedDescriptors(probeLog)).toEqual([PINNED_DESCRIPTOR]);
+
+ await manager.retryThread(info.threadId).catch(() => {});
+
+ expect(probedDescriptors(probeLog)).toEqual([PINNED_DESCRIPTOR, PINNED_DESCRIPTOR]);
+ });
+ }, 60_000);
+
+ test('a resume reuses the acquisition its open made instead of probing again', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = resumableAcquisitionBin(home);
+ const { agentId, manager } = pinnedAdapterManager(home, bin, {
+ FAKE_CAPS: 'resume,load',
+ });
+ await manager.init();
+
+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 20_000,
+ 'the open to become ready',
+ );
+ manager.sendPrompt(info.threadId, 'retain this session');
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 20_000,
+ 'the turn to end',
+ );
+ await manager.closeThread(info.threadId);
+ const beforeResume = (await statusesOf(manager, info.threadId)).length;
+
+ await manager.resumeThread(info.threadId);
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 20_000,
+ 'the resumed thread to become ready',
+ );
+
+ expect(probedDescriptors(probeLog)).toEqual([PINNED_DESCRIPTOR]);
+ const afterResume = (await statusesOf(manager, info.threadId)).slice(beforeResume);
+ expect(afterResume[0]).toBe('spawning');
+ expect(afterResume).not.toContain('installing');
+ });
+ }, 90_000);
+
+ test('a resume whose runtime offer goes unanswered expires on the budget the resume waits on', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin } = resumableAcquisitionBin(home);
+ const localDir = tmp();
+ const runtimeRoot = tmp();
+ const agent = registryPackage(PINNED_DESCRIPTOR, 'npx', {
+ PATH: bin,
+ FAKE_CAPS: 'resume,load',
+ });
+ const registry = new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),
+ });
+ const manager = makeManager(home, localDir, {
+ registry,
+ runtimeInstall: { root: runtimeRoot },
+ });
+ await manager.init();
+
+ const events: ThreadEvent[] = [];
+ const info = await manager.createThread({ agent: { source: 'registry', id: agent.id } });
+ await manager.subscribe(info.threadId, 0, (frame) => {
+ if (frame.op === 'event') events.push(frame.event);
+ else if (frame.op === 'events') events.push(...frame.events);
+ });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 20_000,
+ 'the open to become ready',
+ );
+ manager.sendPrompt(info.threadId, 'retain this session');
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 20_000,
+ 'the turn to end',
+ );
+ expect(internals(manager).sessionId(info.threadId)).toBe('sess-fixed');
+ await manager.closeThread(info.threadId);
+ expect(manager.getInfo(info.threadId)?.archived).toBe(true);
+
+ for (const leaf of ['npx', 'npx.cjs', 'npx.cmd']) {
+ rmSync(join(bin, leaf), { force: true });
+ }
+
+ let refusal: unknown;
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ const resuming = manager.resumeThread(info.threadId).catch((error: unknown) => error);
+ await waitUntil(
+ () => events.some((event) => event.kind === 'runtime_consent_request'),
+ 20_000,
+ 'the resume to offer the managed runtime',
+ );
+ await vi.advanceTimersByTimeAsync(BLOCKING_CONSENT_BUDGET_MS + 1_000);
+ await waitUntil(
+ () => events.some((event) => event.kind === 'runtime_consent_resolved'),
+ 20_000,
+ 'the offer to expire on the budget the resume is waiting on',
+ );
+ refusal = await resuming;
+ } finally {
+ vi.useRealTimers();
+ }
+
+ const resolved = events.find(
+ (event): event is Extract<ThreadEvent, { kind: 'runtime_consent_resolved' }> =>
+ event.kind === 'runtime_consent_resolved',
+ );
+ expect(resolved?.decision).toBe('timeout');
+ expect(refusal).toMatchObject({
+ message: expect.stringContaining('expired before it was answered'),
+ });
+
+ await waitUntil(
+ () => events.some((event) => event.kind === 'status' && event.status === 'exited'),
+ 20_000,
+ 'the resume to record its terminal status',
+ );
+ const terminal = events
+ .filter(
+ (event): event is Extract<ThreadEvent, { kind: 'status' }> => event.kind === 'status',
+ )
+ .at(-1);
+ expect(terminal?.status).toBe('exited');
+ expect(terminal?.failure?.agentMessage).toContain('expired before it was answered');
+ expect(
+ terminal?.failure?.agentMessage,
+ 're-offering the download would tell the user an offer they let expire was never made',
+ ).not.toContain('OK can download a private copy');
+ });
+ }, 120_000);
+
+ test('an open that really probes the registry reports installing while it probes', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingAcquisitionBin(home);
+ const { agentId, manager } = pinnedAdapterManager(home, bin);
+
+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 20_000,
+ 'the open to settle',
+ );
+
+ expect(probedDescriptors(probeLog)).toEqual([PINNED_DESCRIPTOR]);
+ expect(await statusesOf(manager, info.threadId)).toEqual([
+ 'spawning',
+ 'installing',
+ 'spawning',
+ 'error',
+ ]);
+ });
+ }, 60_000);
+
+ test('a second open served from the warm memo never reports installing', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingAcquisitionBin(home);
+ const { agentId, manager } = pinnedAdapterManager(home, bin);
+
+ const first = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(first.threadId)?.status === 'error',
+ 20_000,
+ 'the first open to settle',
+ );
+ const second = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(second.threadId)?.status === 'error',
+ 20_000,
+ 'the second open to settle',
+ );
+
+ expect(probedDescriptors(probeLog)).toEqual([PINNED_DESCRIPTOR]);
+ const statuses = await statusesOf(manager, second.threadId);
+ expect(statuses[0]).toBe('spawning');
+ expect(statuses).not.toContain('installing');
+ });
+ }, 60_000);
+
+ test('an unpinned registry package resolves without reporting installing', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingAcquisitionBin(home);
+ const localDir = tmp();
+ const agent = registryPackage(PINNED_ADAPTER, 'npx', { PATH: bin });
+ const registry = new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: async () => new Response(JSON.stringify({ agents: [agent] })),
+ });
+ const manager = makeManager(home, localDir, { registry });
+
+ const info = await manager.createThread({ agent: { source: 'registry', id: agent.id } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 20_000,
+ 'the open to settle',
+ );
+
+ expect(probedDescriptors(probeLog)).toEqual([]);
+ const statuses = await statusesOf(manager, info.threadId);
+ expect(statuses[0]).toBe('spawning');
+ expect(statuses).not.toContain('installing');
+ });
+ }, 60_000);
+
+ test('a custom agent launched through the same npx never reports installing', async () => {
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingAcquisitionBin(home);
+ const localDir = tmp();
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ {
+ id: 'custom-npx',
+ name: 'Custom npx agent',
+ command: join(bin, 'npx'),
+ args: ['-y', PINNED_DESCRIPTOR],
+ },
+ ]),
+ );
+ const manager = makeManager(home, localDir);
+
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'custom-npx' } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 20_000,
+ 'the open to settle',
+ );
+
+ expect(probedDescriptors(probeLog)).toEqual([]);
+ const statuses = await statusesOf(manager, info.threadId);
+ expect(statuses[0]).toBe('spawning');
+ expect(statuses).not.toContain('installing');
+ });
+ }, 60_000);
+
+ test('a retry re-acquires its own adapter and leaves a second adapter memoized', async () => {
+ const BYSTANDER_DESCRIPTOR = '[email protected]';
+ await withAcquisitionHome(async (home) => {
+ const { bin, probeLog } = recordingAcquisitionBin(home);
+ const localDir = tmp();
+ const retried = {
+ ...registryPackage(PINNED_DESCRIPTOR, 'npx', { PATH: bin }),
+ id: 'adapter-retried',
+ };
+ const bystander = {
+ ...registryPackage(BYSTANDER_DESCRIPTOR, 'npx', { PATH: bin }),
+ id: 'adapter-bystander',
+ };
+ const registry = new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: async () => new Response(JSON.stringify({ agents: [retried, bystander] })),
+ });
+ const manager = makeManager(home, localDir, { registry });
+ const settle = async (agentId: string): Promise<string> => {
+ const info = await manager.createThread({ agent: { source: 'registry', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'error',
+ 20_000,
+ `the ${agentId} open to settle`,
+ );
+ return info.threadId;
+ };
+
+ const retriedThread = await settle(retried.id);
+ await settle(bystander.id);
+ expect(probedDescriptors(probeLog)).toEqual([PINNED_DESCRIPTOR, BYSTANDER_DESCRIPTOR]);
+
+ await manager.retryThread(retriedThread).catch(() => {});
+ expect(probedDescriptors(probeLog)).toEqual([
+ PINNED_DESCRIPTOR,
+ BYSTANDER_DESCRIPTOR,
+ PINNED_DESCRIPTOR,
+ ]);
+
+ await settle(bystander.id);
+
+ expect(probedDescriptors(probeLog)).toEqual([
+ PINNED_DESCRIPTOR,
+ BYSTANDER_DESCRIPTOR,
+ PINNED_DESCRIPTOR,
+ ]);
+ });
+ }, 90_000);
+});
diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.ts
index ff8a0a3f6..9953785f1 100644
--- a/packages/server/src/acp/thread-manager.ts
+++ b/packages/server/src/acp/thread-manager.ts
@@ -86,6 +86,9 @@ import {
brokenInterpreterHint,
declinedRepairHint,
envPath,
+ expiredFallbackHint,
+ expiredIncompatibleNodeHint,
+ expiredRepairHint,
incompatibleManagedRuntimeHint,
incompatibleNodeHint,
isPathQualified,
@@ -161,6 +164,8 @@ const RESUME_REPLAY_MAX_WAIT_MS = 3_000;
const AUTH_REQUIRED_CODE = -32000;
const CONCURRENT_OVERWRITE_REFUSED_CODE = -32009;
+type AcquisitionPolicy = 'reuse' | 'reacquire';
+
export const ACP_ENVIRONMENT_NOTE =
'Note on your environment: you are running inside the OpenKnowledge app, ' +
'connected over ACP (Agent Client Protocol) — not inside your own terminal app. ' +
@@ -185,6 +190,15 @@ export class ThreadOpError extends Error {
}
}
+class RuntimeConsentRefusedError extends AgentLaunchError {
+ readonly refusal: 'declined' | 'timeout';
+ constructor(refusal: 'declined' | 'timeout', message: string) {
+ super('command-not-found', message);
+ this.name = 'RuntimeConsentRefusedError';
+ this.refusal = refusal;
+ }
+}
+
class AuthenticateTimeoutError extends Error {
constructor() {
super('authenticate timed out');
@@ -538,7 +552,7 @@ export class AcpThreadManager {
threadId,
agent: agentInfo,
title: agentInfo.name,
- status: 'installing',
+ status: 'spawning',
createdAt: now,
lastActivityAt: now,
promptCapabilities: null,
@@ -591,7 +605,7 @@ export class AcpThreadManager {
envNotePending: false,
};
this.threads.set(threadId, record);
- this.emitStatus(record, 'installing');
+ this.emitStatus(record, 'spawning');
void this.startThread(record, params, custom).catch((err) => {
this.opts.log.error({ err, threadId }, '[acp-threads] thread start failed');
@@ -641,10 +655,12 @@ export class AcpThreadManager {
private async connectAgent(
record: ThreadRecord,
custom: CustomAgentEntry | null,
+ acquisition: AcquisitionPolicy = 'reuse',
+ consentBudgetMs: number,
): Promise<{ conn: ClientConnection; init: InitializeResponse; launch: ResolvedLaunch } | null> {
let launch: ResolvedLaunch | null;
if (custom !== null) {
- launch = await this.ensureLaunchable(record, resolveCustomLaunch(custom));
+ launch = await this.ensureLaunchable(record, resolveCustomLaunch(custom), consentBudgetMs);
} else {
const manifest = await this.opts.registry.getAgent(record.agentRef.id);
if (manifest === undefined) throw new ThreadOpError('unknown-agent', 'agent vanished');
@@ -653,7 +669,23 @@ export class AcpThreadManager {
registryPlatformKey(),
this.opts.log,
undefined,
- (candidate) => this.ensureLaunchable(record, candidate),
+ (candidate) => this.ensureLaunchable(record, candidate, consentBudgetMs),
+ {
+ reacquire: acquisition === 'reacquire',
+ onProbeStart: () => this.emitStatus(record, 'installing'),
+ onResolved: ({ acquired, outcome, source, elapsedMs }) =>
+ this.opts.log.info(
+ {
+ threadId: record.info.threadId,
+ agentId: record.info.agent.id,
+ package: acquired,
+ outcome,
+ source,
+ elapsedMs,
+ },
+ '[acp-threads] agent package acquired',
+ ),
+ },
);
}
if (launch === null || record.closed) return null;
@@ -872,6 +904,7 @@ export class AcpThreadManager {
private async ensureLaunchable(
record: ThreadRecord,
launch: ResolvedLaunch,
+ consentBudgetMs: number,
): Promise<ResolvedLaunch | null> {
let candidate: ResolvedLaunch;
try {
@@ -880,16 +913,18 @@ export class AcpThreadManager {
} catch (err) {
if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;
const viaLoginShell = await this.retryWithLoginShellPath(launch);
- if (viaLoginShell === null) return this.fallbackToManagedRuntime(record, launch, err);
+ if (viaLoginShell === null)
+ return this.fallbackToManagedRuntime(record, launch, err, undefined, consentBudgetMs);
candidate = viaLoginShell;
}
if (record.closed) return null;
- return this.ensureInterpreterRuns(record, candidate);
+ return this.ensureInterpreterRuns(record, candidate, consentBudgetMs);
}
private async ensureInterpreterRuns(
record: ThreadRecord,
launch: ResolvedLaunch,
+ consentBudgetMs: number,
): Promise<ResolvedLaunch | null> {
if (launch.kind !== 'npx' && launch.kind !== 'uvx') return launch;
const failure = await this.probeInterpreterOnce(launch);
@@ -939,20 +974,34 @@ export class AcpThreadManager {
},
'[acp-threads] interpreter cannot run this agent — offering the managed runtime',
);
- const cause = new AgentLaunchError(
+ const incompatible = failure.kind === 'incompatible';
+ const declined = new AgentLaunchError(
'command-not-found',
- failure.kind === 'incompatible'
+ incompatible
? incompatibleNodeHint(launch, failure.detail)
: brokenInterpreterHint(launch, failure.detail),
);
- return this.fallbackToManagedRuntime(record, launch, cause, cause);
+ const expired = new AgentLaunchError(
+ 'command-not-found',
+ incompatible
+ ? expiredIncompatibleNodeHint(launch, failure.detail)
+ : expiredFallbackHint(launch, declined.message),
+ );
+ return this.fallbackToManagedRuntime(
+ record,
+ launch,
+ declined,
+ { declined, expired },
+ consentBudgetMs,
+ );
}
private async fallbackToManagedRuntime(
record: ThreadRecord,
launch: ResolvedLaunch,
cause: AgentLaunchError,
- declineCause?: AgentLaunchError,
+ refusalCauses: { declined: AgentLaunchError; expired: AgentLaunchError } | undefined,
+ consentBudgetMs: number,
): Promise<ResolvedLaunch | null> {
if (launch.kind !== 'npx' && launch.kind !== 'uvx') throw cause;
const runtimeKind = runtimeForInterpreter(launch.kind);
@@ -960,10 +1009,11 @@ export class AcpThreadManager {
const runtime = await this.provideManagedRuntime(
record,
runtimeKind,
- declineCause === undefined ? 'missing' : 'broken',
+ refusalCauses === undefined ? 'missing' : 'broken',
+ consentBudgetMs,
).catch((err: unknown) => {
- if (declineCause !== undefined && err instanceof AgentLaunchError) {
- throw err.code === 'command-not-found' ? declineCause : err;
+ if (refusalCauses !== undefined && err instanceof RuntimeConsentRefusedError) {
+ throw err.refusal === 'timeout' ? refusalCauses.expired : refusalCauses.declined;
}
throw err;
});
@@ -978,7 +1028,13 @@ export class AcpThreadManager {
incompatibleManagedRuntimeHint(brokenManaged.detail),
);
}
- return this.repairManagedRuntime(record, launch, runtimeKind, brokenManaged.detail);
+ return this.repairManagedRuntime(
+ record,
+ launch,
+ runtimeKind,
+ brokenManaged.detail,
+ consentBudgetMs,
+ );
}
private async repairManagedRuntime(
@@ -986,6 +1042,7 @@ export class AcpThreadManager {
launch: ResolvedLaunch,
runtimeKind: ManagedRuntimeKind,
detail: string,
+ consentBudgetMs: number,
): Promise<ResolvedLaunch | null> {
const logContext = {
threadId: record.info.threadId,
@@ -1006,14 +1063,20 @@ export class AcpThreadManager {
throw new AgentLaunchError('install-failed', undeletableManagedRuntimeHint(launch, detail));
}
- const fresh = await this.provideManagedRuntime(record, runtimeKind, 'damaged').catch(
- (err: unknown) => {
- if (err instanceof AgentLaunchError && err.code === 'command-not-found') {
- throw new AgentLaunchError('command-not-found', declinedRepairHint(launch));
- }
- throw err;
- },
- );
+ const fresh = await this.provideManagedRuntime(
+ record,
+ runtimeKind,
+ 'damaged',
+ consentBudgetMs,
+ ).catch((err: unknown) => {
+ if (err instanceof RuntimeConsentRefusedError) {
+ throw new AgentLaunchError(
+ 'command-not-found',
+ err.refusal === 'timeout' ? expiredRepairHint(launch) : declinedRepairHint(launch),
+ );
+ }
+ throw err;
+ });
if (fresh === null) return null;
const rewritten = rewriteLaunchToManagedRuntime(launch, fresh);
await preflightLaunch(rewritten);
@@ -1088,16 +1151,20 @@ export class AcpThreadManager {
record: ThreadRecord,
runtimeKind: ManagedRuntimeKind,
reason: 'missing' | 'broken' | 'damaged',
+ consentBudgetMs: number,
): Promise<ManagedRuntime | null> {
const root = this.opts.runtimeInstall?.root;
await cleanupManagedRuntimeStaging(runtimeKind, this.opts.log, root);
const existing = await findManagedRuntime(runtimeKind, root).catch(() => null);
if (existing !== null) return existing;
- const decision = await this.requestRuntimeConsent(record, runtimeKind, reason);
+ const decision = await this.requestRuntimeConsent(record, runtimeKind, reason, consentBudgetMs);
if (decision === 'closed' || record.closed) return null;
if (decision !== 'granted') {
- throw new AgentLaunchError('command-not-found', declinedRuntimeHint(runtimeKind));
+ throw new RuntimeConsentRefusedError(
+ decision,
+ decision === 'timeout' ? expiredRuntimeHint(runtimeKind) : declinedRuntimeHint(runtimeKind),
+ );
}
try {
@@ -1116,6 +1183,7 @@ export class AcpThreadManager {
record: ThreadRecord,
runtimeKind: ManagedRuntimeKind,
reason: 'missing' | 'broken' | 'damaged',
+ consentBudgetMs: number,
): Promise<'granted' | 'declined' | 'timeout' | 'closed'> {
const requestId = crypto.randomUUID();
const d = describeRuntime(runtimeKind);
@@ -1142,7 +1210,7 @@ export class AcpThreadManager {
ts: Date.now(),
});
resolvePromise('timeout');
- }, CONSENT_TIMEOUT_MS);
+ }, consentBudgetMs);
timer.unref?.();
record.pendingRuntimeConsent.set(requestId, { resolve: resolvePromise, timer });
});
@@ -1514,10 +1582,11 @@ export class AcpThreadManager {
},
custom: CustomAgentEntry | null,
consentBudgetMs: number = CONSENT_TIMEOUT_MS,
+ acquisition: AcquisitionPolicy = 'reuse',
): Promise<void> {
let handshake: Awaited<ReturnType<AcpThreadManager['connectAgent']>>;
try {
- handshake = await this.connectAgent(record, custom);
+ handshake = await this.connectAgent(record, custom, acquisition, consentBudgetMs);
} catch (err) {
const failure = await connectionFailureDetail(err, record);
this.emitStatus(record, 'error', failure.agentMessage, failure);
@@ -1662,7 +1731,7 @@ export class AcpThreadManager {
this.echoUserMessage(t, prompt ?? '', attachments);
this.flushBroadcast(t);
}
- this.emitStatus(t, 'installing');
+ this.emitStatus(t, 'spawning');
try {
if (sessionId === null) {
this.opts.log.warn(
@@ -1674,7 +1743,7 @@ export class AcpThreadManager {
'this thread never completed an agent session',
);
}
- const handshake = await this.connectAgent(t, custom);
+ const handshake = await this.connectAgent(t, custom, 'reuse', BLOCKING_CONSENT_TIMEOUT_MS);
if (handshake === null) {
throw new ThreadOpError('not-ready', 'thread closed during resume');
}
@@ -1865,13 +1934,14 @@ export class AcpThreadManager {
t.stderrTail = [];
t.cancelRequested = false;
t.turnActive = false;
- this.emitStatus(t, 'installing');
+ this.emitStatus(t, 'spawning');
try {
await this.startThread(
t,
{ agent: t.agentRef, settings: t.launchSettings },
custom,
BLOCKING_CONSENT_TIMEOUT_MS,
+ 'reacquire',
);
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
@@ -3220,6 +3290,15 @@ function declinedRuntimeHint(runtimeKind: ManagedRuntimeKind): string {
return `This agent needs \`${d.provides}\`, which isn't installed. OK can download a private copy of ${d.displayName} for you, or install ${d.displayName} yourself (${installUrl}) and it'll be used automatically.`;
}
+function expiredRuntimeHint(runtimeKind: ManagedRuntimeKind): string {
+ const d = describeRuntime(runtimeKind);
+ const installUrl =
+ runtimeKind === 'node'
+ ? 'https://nodejs.org'
+ : 'https://docs.astral.sh/uv/getting-started/installation/';
+ return `This agent needs \`${d.provides}\`, which isn't installed. The offer to download a private copy of ${d.displayName} expired before it was answered — start the agent again to get it back, or install ${d.displayName} yourself (${installUrl}) and it'll be used automatically.`;
+}
+
function isAuthRequiredError(err: unknown): boolean {
if (typeof err !== 'object' || err === null) return false;
const e = err as { code?: unknown; data?: unknown };