diff --git a/.github/workflows/build-cli.yml b/.github/workflows/build-cli.yml index 4d1aefc50b5..067646d1004 100644 --- a/.github/workflows/build-cli.yml +++ b/.github/workflows/build-cli.yml @@ -81,6 +81,11 @@ jobs: sleep "$((attempt * 10))" done + - name: Build macOS executable verifier + if: startsWith(matrix.target, 'darwin-') + working-directory: packages/macos-process-metrics + run: npx --yes node-gyp@12.4.0 rebuild + - name: Build distribution working-directory: packages/cli env: diff --git a/apps/desktop/src/renderer/lib/terminal/continue-native-background.test.ts b/apps/desktop/src/renderer/lib/terminal/continue-native-background.test.ts new file mode 100644 index 00000000000..d297910344d --- /dev/null +++ b/apps/desktop/src/renderer/lib/terminal/continue-native-background.test.ts @@ -0,0 +1,99 @@ +import { expect, test } from "bun:test"; +import { continueNativeBackground } from "./continue-native-background"; + +const input = { + workspaceId: "workspace", + terminalId: "old", + expectedRevision: "captured-source", +}; +test("Continue prefers the existing background view and never requests another account", async () => { + let reads = 0; + let resumes = 0; + const result = await continueNativeBackground(input, { + reconnect: async () => ({ + reconnected: true, + terminalId: "view", + label: "Claude", + }), + source: async () => { + reads++; + return null; + }, + resume: async () => { + resumes++; + return { resumed: false }; + }, + }); + expect(result).toEqual({ terminalId: "view", label: "Claude" }); + expect(reads).toBe(0); + expect(resumes).toBe(0); +}); +test("a cleanly ended conversation can resume only its same immutable original account", async () => { + const requested: unknown[] = []; + const result = await continueNativeBackground(input, { + reconnect: async () => ({ reconnected: false }), + source: async () => ({ + provider: "claude", + ready: true, + revision: input.expectedRevision, + account: { selection: "/original/profile", identity: "exact-original" }, + }), + resume: async (request) => { + requested.push(request); + return { resumed: true, terminalId: "exact-replay", label: "Claude" }; + }, + }); + expect(result?.terminalId).toBe("exact-replay"); + expect(requested).toEqual([ + { + ...input, + account: { selection: "/original/profile", identity: "exact-original" }, + }, + ]); +}); +test("changed or incomplete source context cannot become a default-account resume", async () => { + for (const saved of [ + null, + { + provider: "claude", + ready: false, + revision: input.expectedRevision, + account: { selection: null, identity: "account" }, + }, + { + provider: "claude", + ready: true, + revision: "changed", + account: { selection: "/different", identity: "new" }, + }, + ]) { + let resumes = 0; + expect( + await continueNativeBackground(input, { + reconnect: async () => ({ reconnected: false }), + source: async () => saved, + resume: async () => { + resumes++; + return { resumed: false }; + }, + }), + ).toBeNull(); + expect(resumes).toBe(0); + } +}); +test("a lost attachment response cannot fall through and launch a second worker", async () => { + let resumes = 0; + await expect( + continueNativeBackground(input, { + reconnect: async () => { + throw new Error("offline"); + }, + source: async () => null, + resume: async () => { + resumes++; + return { resumed: false }; + }, + }), + ).rejects.toThrow("offline"); + expect(resumes).toBe(0); +}); diff --git a/apps/desktop/src/renderer/lib/terminal/continue-native-background.ts b/apps/desktop/src/renderer/lib/terminal/continue-native-background.ts new file mode 100644 index 00000000000..f21f8f3517b --- /dev/null +++ b/apps/desktop/src/renderer/lib/terminal/continue-native-background.ts @@ -0,0 +1,57 @@ +interface Input { + workspaceId: string; + terminalId: string; + expectedRevision: string; +} +interface Successor { + terminalId: string; + label: string; +} +interface Account { + selection: string | null; + identity: string; +} +interface ContinueNativeIO { + reconnect( + input: Input, + ): Promise< + | { reconnected: false } + | ({ reconnected: true } & Successor) + | ({ reconnected: false; attachmentPending: true } & Successor) + >; + source(input: { workspaceId: string; terminalId: string }): Promise<{ + provider: string; + ready: boolean; + revision: string; + account: Account | null; + } | null>; + resume( + input: Input & { account: Account }, + ): Promise<{ resumed: false } | ({ resumed: true } & Successor)>; +} +export async function continueNativeBackground( + input: Input, + io: ContinueNativeIO, +): Promise { + const live = await io.reconnect(input); + if (live.reconnected || "attachmentPending" in live) + return { terminalId: live.terminalId, label: live.label }; + const saved = await io.source(input); + if ( + !saved?.ready || + saved.provider !== "claude" || + saved.revision !== input.expectedRevision || + !saved.account + ) + return null; + const result = await io.resume({ + ...input, + account: { + selection: saved.account.selection, + identity: saved.account.identity, + }, + }); + return result.resumed + ? { terminalId: result.terminalId, label: result.label } + : null; +} diff --git a/apps/desktop/src/renderer/lib/terminal/resume-with-background-reconnect.test.ts b/apps/desktop/src/renderer/lib/terminal/resume-with-background-reconnect.test.ts new file mode 100644 index 00000000000..4b65f065c13 --- /dev/null +++ b/apps/desktop/src/renderer/lib/terminal/resume-with-background-reconnect.test.ts @@ -0,0 +1,117 @@ +import { expect, test } from "bun:test"; +import { resumeWithBackgroundReconnect } from "./resume-with-background-reconnect"; + +function fixture() { + let resumes = 0; + let attaches = 0; + const input = { workspaceId: "workspace", terminalId: "original" }; + const resume = async () => { + resumes++; + return { resumed: false as const }; + }; + const recovery = { + capabilities: async () => ({ version: 1, claudeLiveAttach: true }), + source: async () => ({ provider: "claude", revision: "a".repeat(64) }), + reconnect: async (_input: typeof input & { expectedRevision: string }) => { + attaches++; + return { + reconnected: true as const, + terminalId: "existing-worker-view", + label: "Claude", + }; + }, + }; + return { input, resume, recovery, counts: () => ({ resumes, attaches }) }; +} +test("Continue focuses the confirmed existing worker and never launches a resume", async () => { + const f = fixture(); + expect( + await resumeWithBackgroundReconnect( + f.input, + "claude", + f.recovery, + f.resume, + ), + ).toEqual({ + resumed: true, + terminalId: "existing-worker-view", + label: "Claude", + }); + expect(f.counts()).toEqual({ resumes: 0, attaches: 1 }); +}); +test("older hosts fall back only on a missing additive capability", async () => { + const f = fixture(); + f.recovery.capabilities = async () => { + throw { data: { code: "NOT_FOUND" } }; + }; + expect( + await resumeWithBackgroundReconnect( + f.input, + "claude", + f.recovery, + f.resume, + ), + ).toEqual({ resumed: false }); + expect(f.counts()).toEqual({ resumes: 1, attaches: 0 }); +}); +test("transport, permission and malformed capability failures never launch another worker", async () => { + for (const error of [ + new Error("offline"), + { data: { code: "UNAUTHORIZED" } }, + { code: "NOT_FOUND" }, + ]) { + const f = fixture(); + f.recovery.capabilities = async () => { + throw error; + }; + await expect( + resumeWithBackgroundReconnect(f.input, "claude", f.recovery, f.resume), + ).rejects.toBe(error); + expect(f.counts().resumes).toBe(0); + } +}); +test("verification failure after supported capability never falls through", async () => { + const f = fixture(); + f.recovery.reconnect = async () => { + throw new Error("worker changed"); + }; + await expect( + resumeWithBackgroundReconnect(f.input, "claude", f.recovery, f.resume), + ).rejects.toThrow("worker changed"); + expect(f.counts().resumes).toBe(0); +}); +test("an explicit no-background result preserves ordinary resume", async () => { + const f = fixture(); + const recovery = { + ...f.recovery, + reconnect: async () => ({ reconnected: false as const }), + }; + expect( + await resumeWithBackgroundReconnect(f.input, "claude", recovery, f.resume), + ).toEqual({ resumed: false }); + expect(f.counts().resumes).toBe(1); +}); +test("an unconfirmed view is opened but never presented as confirmed identity", async () => { + const f = fixture(); + const recovery = { + ...f.recovery, + reconnect: async () => ({ + reconnected: false as const, + attachmentPending: true as const, + terminalId: "pending-view", + label: "Claude", + }), + }; + expect( + await resumeWithBackgroundReconnect(f.input, "claude", recovery, f.resume), + ).toMatchObject({ resumed: true, terminalId: "pending-view" }); + expect(f.counts().resumes).toBe(0); +}); +test("Codex does not receive Claude capability or attachment calls", async () => { + const f = fixture(); + f.recovery.capabilities = async () => { + throw new Error("should not run"); + }; + await resumeWithBackgroundReconnect(f.input, "codex", f.recovery, f.resume); + expect(f.counts()).toEqual({ resumes: 1, attaches: 0 }); +}); diff --git a/apps/desktop/src/renderer/lib/terminal/resume-with-background-reconnect.ts b/apps/desktop/src/renderer/lib/terminal/resume-with-background-reconnect.ts new file mode 100644 index 00000000000..f7753618f2d --- /dev/null +++ b/apps/desktop/src/renderer/lib/terminal/resume-with-background-reconnect.ts @@ -0,0 +1,64 @@ +interface ResumeInput { + workspaceId: string; + terminalId: string; +} +type ResumeResult = + | { resumed: false } + | { resumed: true; terminalId: string; label: string }; +interface BackgroundRecovery { + capabilities(): Promise<{ version: number; claudeLiveAttach: boolean }>; + source( + input: ResumeInput, + ): Promise<{ provider: string; revision: string } | null>; + reconnect(input: ResumeInput & { expectedRevision: string }): Promise< + | { reconnected: false } + | { reconnected: true; terminalId: string; label: string } + | { + reconnected: false; + attachmentPending: true; + terminalId: string; + label: string; + } + >; +} +function missingProcedure(error: unknown): boolean { + if (!error || typeof error !== "object" || !("data" in error)) return false; + const data = error.data; + return ( + !!data && + typeof data === "object" && + "code" in data && + data.code === "NOT_FOUND" + ); +} +/** Network/verification failures never fall through to a second worker launch. */ +export async function resumeWithBackgroundReconnect( + input: ResumeInput, + provider: string, + recovery: BackgroundRecovery, + resume: (input: ResumeInput) => Promise, +): Promise { + if (provider !== "claude") return resume(input); + let capability: Awaited>; + try { + capability = await recovery.capabilities(); + } catch (error) { + if (missingProcedure(error)) return resume(input); + throw error; + } + if (capability.version !== 1 || !capability.claudeLiveAttach) + return resume(input); + const source = await recovery.source(input); + if (!source || source.provider !== "claude") return resume(input); + const result = await recovery.reconnect({ + ...input, + expectedRevision: source.revision, + }); + if (result.reconnected || "attachmentPending" in result) + return { + resumed: true, + terminalId: result.terminalId, + label: result.label, + }; + return resume(input); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/AccountTerminalDialog.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/AccountTerminalDialog.tsx new file mode 100644 index 00000000000..88b21b77cf4 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/AccountTerminalDialog.tsx @@ -0,0 +1,161 @@ +import { useLingui } from "@lingui/react/macro"; +import { errorMessage } from "@superset/i18n/errors"; +import { useWorkspaceClient } from "@superset/workspace-client"; +import { useQuery } from "@tanstack/react-query"; +import { TRPCClientError } from "@trpc/client"; +import { useState } from "react"; +import { useHostUsageQuota } from "renderer/hooks/host-service/useHostUsageQuota"; +import { useV2AgentConfigs } from "renderer/hooks/useV2AgentConfigs"; +import { getHostServiceClientByUrl } from "renderer/lib/host-service-client"; +import type { CreateAccountTerminal } from "../../hooks/useAgentSessionLauncher"; +import { useChatWiring } from "../../hooks/usePaneRegistry/components/ChatSession/hooks/useSessionClient"; +import { AccountTerminalDialogFrame } from "./components/AccountTerminalDialogFrame"; +import { AccountTerminalForm } from "./components/AccountTerminalForm"; + +export function AccountTerminalDialog({ + onClose, + onLaunch, + surface = "terminal", + returnFocus, +}: { + surface?: "terminal" | "chat"; + returnFocus: HTMLElement | null; + onClose: () => void; + onLaunch: CreateAccountTerminal; +}) { + const { t } = useLingui(); + const { hostUrl } = useWorkspaceClient(); + const configs = useV2AgentConfigs(hostUrl); + const wiring = useChatWiring(); + const capabilities = useQuery({ + queryKey: ["account-chat-capabilities", hostUrl], + enabled: surface === "chat" && Boolean(hostUrl), + queryFn: () => wiring.transport.accountCapabilities(), + retry: false, + }); + const [configId, setConfigId] = useState(""); + const [launching, setLaunching] = useState(false); + const [refreshing, setRefreshing] = useState(false); + const [refreshError, setRefreshError] = useState(null); + const choices = (configs.data ?? []).filter( + (config) => config.presetId === "claude" || config.presetId === "codex", + ); + const selectedConfigId = configId || choices[0]?.id || ""; + const selectedConfigExists = choices.some( + (config) => config.id === selectedConfigId, + ); + const accounts = useQuery({ + queryKey: ["agent-launch-accounts", hostUrl, surface, selectedConfigId], + enabled: Boolean(hostUrl && selectedConfigExists), + queryFn: () => { + if (!hostUrl) throw new Error("Host unavailable"); + return getHostServiceClientByUrl(hostUrl).agents.launchAccounts.query({ + agent: selectedConfigId, + surface, + }); + }, + retry: false, + staleTime: 0, + }); + const provider = choices.find( + (config) => config.id === selectedConfigId, + )?.presetId; + const quota = useHostUsageQuota(accounts.data?.supported ? hostUrl : null); + const unsupportedHost = + accounts.error instanceof TRPCClientError && + accounts.error.data?.code === "NOT_FOUND" && + accounts.error.message.includes("agents.launchAccounts"); + const preset = choices.find( + (config) => config.id === selectedConfigId, + )?.presetId; + const chatUnsupported = + surface === "chat" && + !capabilities.isPending && + (capabilities.isError || + !capabilities.data?.harnesses.includes( + `${preset}-acp` as "claude-acp" | "codex-acp", + )); + const error = chatUnsupported + ? t({ + message: + "This host does not support account selection for native chats.", + }) + : !hostUrl + ? t({ message: "Host service is not running" }) + : unsupportedHost + ? t({ + message: + "Update this host to choose an account for a new terminal.", + }) + : configs.isError || accounts.isError + ? errorMessage( + configs.error ?? accounts.error, + t({ message: "Could not load accounts" }), + ) + : !configs.isPending && !selectedConfigExists + ? t({ message: "No agent is configured on this host" }) + : accounts.data?.supported === false + ? t({ + message: + "This agent configuration does not support account selection.", + }) + : null; + return ( + + { + setRefreshing(true); + setRefreshError(null); + try { + const [, usageResult] = await Promise.allSettled([ + accounts.refetch(), + quota.refresh(), + ...(surface === "chat" ? [capabilities.refetch()] : []), + ]); + if (usageResult?.status === "rejected") + setRefreshError( + errorMessage( + usageResult.reason, + t({ message: "Could not refresh usage" }), + ), + ); + } finally { + setRefreshing(false); + } + }} + onCancel={onClose} + onLaunch={async (account) => { + setLaunching(true); + try { + await onLaunch({ configId: selectedConfigId, account }); + onClose(); + } finally { + setLaunching(false); + } + }} + /> + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/AccountTerminalDialogFrame.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/AccountTerminalDialogFrame.test.tsx new file mode 100644 index 00000000000..7c860846e35 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/AccountTerminalDialogFrame.test.tsx @@ -0,0 +1,83 @@ +import { afterEach, beforeEach, expect, jest, mock, test } from "bun:test"; +import { act, cleanup, fireEvent, render } from "@testing-library/react"; +import { AccountTerminalDialogFrame } from "./AccountTerminalDialogFrame"; + +beforeEach(() => jest.useFakeTimers()); +afterEach(() => { + cleanup(); + jest.runAllTimers(); + jest.useRealTimers(); +}); + +function fixture(launching = false, surface: "terminal" | "chat" = "terminal") { + const trigger = document.createElement("button"); + trigger.textContent = "Add tab"; + document.body.append(trigger); + const onClose = mock(() => {}); + const view = render( + + + , + ); + return { trigger, onClose, view }; +} + +test("traps account-picker focus and restores the Add Tab trigger after cancellation", () => { + const { trigger, onClose, view } = fixture(); + try { + const dialog = view.getByRole("dialog"); + expect(trigger.getAttribute("aria-hidden")).toBe("true"); + act(() => { + trigger.focus(); + }); + expect(dialog.contains(document.activeElement)).toBe(true); + fireEvent.keyDown(dialog, { key: "Escape" }); + expect(onClose).toHaveBeenCalledTimes(1); + view.unmount(); + act(() => { + jest.runAllTimers(); + }); + expect(document.activeElement).toBe(trigger); + } finally { + trigger.remove(); + } +}); + +test("keeps a pending launch modal and does not steal focus from its new terminal", () => { + const { trigger, onClose, view } = fixture(true); + const terminal = document.createElement("textarea"); + document.body.append(terminal); + try { + fireEvent.keyDown(view.getByRole("dialog"), { key: "Escape" }); + expect(onClose).not.toHaveBeenCalled(); + expect(view.queryByRole("button", { name: "Close" })).toBeNull(); + view.unmount(); + terminal.focus(); + act(() => { + jest.runAllTimers(); + }); + expect(document.activeElement).toBe(terminal); + } finally { + trigger.remove(); + terminal.remove(); + } +}); + +test("native chat account picker retains its title and cancel focus", () => { + const { trigger, onClose, view } = fixture(false, "chat"); + try { + const dialog = view.getByRole("dialog", { name: "Chat with account" }); + fireEvent.keyDown(dialog, { key: "Escape" }); + expect(onClose).toHaveBeenCalledTimes(1); + view.unmount(); + act(() => jest.runAllTimers()); + expect(document.activeElement).toBe(trigger); + } finally { + trigger.remove(); + } +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/AccountTerminalDialogFrame.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/AccountTerminalDialogFrame.tsx new file mode 100644 index 00000000000..64a963a8b4c --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/AccountTerminalDialogFrame.tsx @@ -0,0 +1,64 @@ +import { Trans } from "@lingui/react/macro"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@superset/ui/dialog"; +import type { ReactNode } from "react"; + +export function AccountTerminalDialogFrame({ + launching, + surface = "terminal", + onClose, + returnFocus, + children, +}: { + launching: boolean; + surface?: "terminal" | "chat"; + onClose: () => void; + returnFocus: HTMLElement | null; + children: ReactNode; +}) { + return ( + !open && !launching && onClose()} + > + { + event.preventDefault(); + if (!launching && returnFocus?.isConnected) returnFocus.focus(); + }} + > + + + {surface === "chat" ? ( + Chat with account + ) : ( + Agent terminal with account + )} + + + {surface === "chat" ? ( + + Start a native chat using an existing login. Recovery keeps this + account and working folder. + + ) : ( + + Start a new terminal using an existing login. Other chats and + your default account stay unchanged. + + )} + + + {children} + + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/index.ts new file mode 100644 index 00000000000..472d0256be0 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalDialogFrame/index.ts @@ -0,0 +1 @@ +export { AccountTerminalDialogFrame } from "./AccountTerminalDialogFrame"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.stories.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.stories.tsx new file mode 100644 index 00000000000..8f8416e720b --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.stories.tsx @@ -0,0 +1,118 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@superset/ui/dialog"; +import { expect, fn, userEvent, within } from "storybook/test"; +import { AccountTerminalForm } from "./AccountTerminalForm"; + +const meta = { + component: AccountTerminalForm, + decorators: [ + (Story, context) => ( + + + + + {context.args.mode === "resume" + ? "Resume with another account" + : "Agent terminal with account"} + + + {context.args.mode === "resume" + ? "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." + : "Start a new terminal using an existing login. Other chats and your default account stay unchanged."} + + + + + + ), + ], + args: { + configs: [ + { id: "review-claude", label: "Claude" }, + { id: "review-codex", label: "Codex" }, + ], + configId: "review-claude", + onConfigChange: fn(), + accounts: [ + { + selection: null, + identity: "a".repeat(64), + email: "review@example.test", + label: "System account", + }, + { + selection: "/review/profiles/claude-work", + identity: "b".repeat(64), + email: "work@example.test", + label: "/review/profiles/claude-work", + }, + ], + loading: false, + refreshing: false, + error: null, + launching: false, + onRefresh: fn(async () => {}), + onCancel: fn(), + onLaunch: fn(async () => {}), + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = {}; + +export const Resume: Story = { + args: { mode: "resume", configs: [{ id: "review-claude", label: "Claude" }] }, + play: async ({ canvasElement }) => { + const dialog = within(canvasElement.ownerDocument.body); + await userEvent.click( + dialog.getByRole("radio", { name: /work@example.test/ }), + ); + await expect( + dialog.getByRole("button", { name: "Resume conversation" }), + ).toBeEnabled(); + await expect(dialog.getByRole("combobox")).toBeDisabled(); + }, +}; + +export const ResumeUnavailable: Story = { + args: { + mode: "resume", + error: + "The selected account cannot access this saved conversation. Nothing was restarted.", + }, +}; + +export const Selected: Story = { + play: async ({ canvasElement }) => { + const dialog = within(canvasElement.ownerDocument.body); + await userEvent.click( + dialog.getByRole("radio", { name: /review@example.test/ }), + ); + await expect( + dialog.getByRole("button", { name: "Start terminal" }), + ).toBeEnabled(); + }, +}; + +export const Loading: Story = { + args: { accounts: [], loading: true, refreshing: true }, +}; + +export const Empty: Story = { + args: { accounts: [] }, +}; + +export const UnsupportedHost: Story = { + args: { + accounts: [], + error: "Update this host to choose an account for a new terminal.", + }, +}; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.test.tsx new file mode 100644 index 00000000000..1fccc579b27 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.test.tsx @@ -0,0 +1,366 @@ +import { afterEach, expect, mock, spyOn, test } from "bun:test"; +import { act, cleanup, fireEvent, render } from "@testing-library/react"; +import type { ComponentProps } from "react"; +import { AccountTerminalForm } from "./AccountTerminalForm"; + +afterEach(cleanup); + +test("resume keeps the provider fixed and requires explicit account selection", async () => { + const input = props(); + const view = render(); + expect((view.getByRole("combobox") as HTMLButtonElement).disabled).toBe(true); + const submit = view.getByRole("button", { + name: "Resume conversation", + }) as HTMLButtonElement; + expect(submit.disabled).toBe(true); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.click(submit); + }); + expect(input.onLaunch).toHaveBeenCalledWith({ + selection: null, + identity: "alice", + }); + expect(input.onConfigChange).not.toHaveBeenCalled(); +}); + +test("resume rejection retains the selection and never retries automatically", async () => { + const input = props(); + input.onLaunch = mock(async () => { + throw new Error("Saved history is unavailable to this account"); + }); + const view = render(); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.click(view.getByRole("button", { name: "Resume conversation" })); + }); + expect(view.getByRole("alert").textContent).toBe( + "Saved history is unavailable to this account", + ); + expect((view.getByRole("radio") as HTMLInputElement).checked).toBe(true); + expect(input.onLaunch).toHaveBeenCalledTimes(1); + expect(input.onCancel).not.toHaveBeenCalled(); +}); + +function props(): ComponentProps { + return { + configs: [{ id: "claude-config", label: "Claude" }], + configId: "claude-config", + onConfigChange: mock(() => {}), + accounts: [ + { + selection: null, + identity: "alice", + email: "alice@example.test", + label: "System login", + }, + ], + loading: false, + refreshing: false, + error: null, + launching: false, + onRefresh: mock(async () => {}), + onCancel: mock(() => {}), + onLaunch: mock(async () => {}), + }; +} + +test("requires an explicit account and preserves the selected system login", async () => { + const input = props(); + const view = render(); + const submit = view.getByRole("button", { + name: "Start terminal", + }) as HTMLButtonElement; + expect(submit.disabled).toBe(true); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.click(submit); + }); + expect(input.onLaunch).toHaveBeenCalledWith({ + selection: null, + identity: "alice", + }); +}); + +test("invalidates a selection when the profile signs into another identity", () => { + const input = props(); + const view = render(); + fireEvent.click(view.getByRole("radio")); + view.rerender( + , + ); + expect( + (view.getByRole("button", { name: "Start terminal" }) as HTMLButtonElement) + .disabled, + ).toBe(true); + expect(view.getByRole("alert").textContent).toContain( + "selected login changed", + ); + fireEvent.submit(view.container.querySelector("form") as HTMLFormElement); + expect(input.onLaunch).not.toHaveBeenCalled(); +}); + +test("a discovery failure blocks a previously selected account", () => { + const input = props(); + const view = render(); + fireEvent.click(view.getByRole("radio")); + view.rerender(); + fireEvent.submit(view.container.querySelector("form") as HTMLFormElement); + expect(view.getByRole("alert").textContent).toBe("Update this host"); + expect(input.onLaunch).not.toHaveBeenCalled(); +}); + +test("shows rejected launches in place without retrying a default account", async () => { + const input = props(); + input.onLaunch = mock(async () => { + throw new Error("The selected account changed"); + }); + const view = render(); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.submit(view.container.querySelector("form") as HTMLFormElement); + }); + expect(view.getByRole("alert").textContent).toBe( + "The selected account changed", + ); + expect(input.onLaunch).toHaveBeenCalledTimes(1); + expect(input.onCancel).not.toHaveBeenCalled(); +}); + +test("deduplicates submission before the launching prop updates", async () => { + const input = props(); + let finish!: () => void; + input.onLaunch = mock( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const view = render(); + fireEvent.click(view.getByRole("radio")); + const form = view.container.querySelector("form") as HTMLFormElement; + fireEvent.submit(form); + fireEvent.submit(form); + expect(input.onLaunch).toHaveBeenCalledTimes(1); + await act(async () => { + finish(); + }); +}); + +test("refresh preserves a manual account choice when the login is unchanged", async () => { + const input = props(); + const view = render(); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.click(view.getByRole("button", { name: "Refresh" })); + }); + expect(input.onRefresh).toHaveBeenCalledTimes(1); + expect( + (view.getByRole("button", { name: "Start terminal" }) as HTMLButtonElement) + .disabled, + ).toBe(false); +}); + +function quotas( + used: number, + selection: string | null = null, + email = "alice@example.test", +) { + return [ + { + agent: "claude", + selection, + email, + credentialKind: "subscription", + status: "ok", + fetchedAt: new Date(), + windows: [ + { id: "seven_day", label: "Weekly", usedPercent: used, resetsAt: null }, + ], + }, + ]; +} + +test("defaults to the most confirmed remaining quota and shows the readable account", () => { + const input = props(); + input.accounts.push({ + selection: "/second", + identity: "second", + email: "second@example.test", + label: "/a/long/profile/folder", + }); + const view = render( + , + ); + const radios = view.getAllByRole("radio") as HTMLInputElement[]; + expect(radios[0]?.checked).toBe(false); + expect(radios[1]?.checked).toBe(true); + expect(view.getByText("second@example.test").className).not.toContain( + "truncate", + ); + expect(view.getByText("80% remaining")).toBeTruthy(); +}); + +test("late quota or a refresh never replaces a manual selection", () => { + const input = props(); + input.accounts.push({ + selection: "/second", + identity: "second", + email: "second@example.test", + label: "Second", + }); + const view = render(); + fireEvent.click(view.getAllByRole("radio")[0] as HTMLElement); + view.rerender( + , + ); + expect((view.getAllByRole("radio")[0] as HTMLInputElement).checked).toBe( + true, + ); +}); + +test("quota-unavailable hosts still allow a deliberate manual choice", async () => { + const input = props(); + const view = render( + , + ); + expect((view.getByRole("radio") as HTMLInputElement).checked).toBe(false); + expect(view.getByText("Usage unavailable")).toBeTruthy(); + fireEvent.click(view.getByRole("radio")); + await act(async () => + fireEvent.submit(view.container.querySelector("form") as HTMLFormElement), + ); + expect(input.onLaunch).toHaveBeenCalledWith({ + selection: null, + identity: "alice", + }); +}); + +test("automatic selection is not replaced after its profile changes login", () => { + const input = props(); + const view = render( + , + ); + view.rerender( + , + ); + expect( + (view.getByRole("button", { name: "Start terminal" }) as HTMLButtonElement) + .disabled, + ).toBe(true); + expect(view.getByRole("alert").textContent).toContain( + "selected login changed", + ); +}); + +test("native chat mode submits the selected login once and keeps failure visible", async () => { + const input = props(); + input.onLaunch = mock(async () => { + throw new Error("Account chat unavailable on this host"); + }); + const view = render(); + const submit = view.getByRole("button", { + name: "Start chat", + }) as HTMLButtonElement; + expect(submit.disabled).toBe(true); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.click(submit); + }); + expect(input.onLaunch).toHaveBeenCalledTimes(1); + expect(input.onLaunch).toHaveBeenCalledWith({ + selection: null, + identity: "alice", + }); + expect(view.getByRole("alert").textContent).toBe( + "Account chat unavailable on this host", + ); + expect(input.onCancel).not.toHaveBeenCalled(); +}); + +test("a response received after mount stays visible immediately without waiting for the age timer", () => { + const input = props(); + let time = Date.now(); + const clock = spyOn(Date, "now").mockImplementation(() => time); + try { + const readings = quotas(20); + readings[0].fetchedAt = new Date(time); + const view = render( + , + ); + expect(view.getByText("80% remaining")).toBeTruthy(); + time += 1_000; + const refreshed = quotas(10); + refreshed[0].fetchedAt = new Date(time); + view.rerender( + , + ); + expect(view.getByText("90% remaining")).toBeTruthy(); + expect(view.queryByText("Usage unavailable")).toBeNull(); + } finally { + clock.mockRestore(); + } +}); + +test("a usage refresh notice keeps manual account selection available", async () => { + const input = props(); + const view = render( + , + ); + expect(view.getByRole("status").textContent).toBe("Could not refresh usage"); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.submit(view.container.querySelector("form") as HTMLFormElement); + }); + expect(input.onLaunch).toHaveBeenCalledTimes(1); +}); + +test("an unknown launch failure uses the caller-specific account-switch message", async () => { + const input = props(); + input.onLaunch = mock(async () => { + throw null; + }); + const view = render( + , + ); + fireEvent.click(view.getByRole("radio")); + await act(async () => { + fireEvent.submit(view.container.querySelector("form") as HTMLFormElement); + }); + expect(view.getByRole("alert").textContent).toBe("Could not switch account"); + expect(input.onLaunch).toHaveBeenCalledTimes(1); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.tsx new file mode 100644 index 00000000000..5f6583b1008 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/AccountTerminalForm.tsx @@ -0,0 +1,283 @@ +import { Trans, useLingui } from "@lingui/react/macro"; +import { errorMessage } from "@superset/i18n/errors"; +import { useFormat } from "@superset/i18n/react"; +import { Button } from "@superset/ui/button"; +import { Label } from "@superset/ui/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@superset/ui/select"; +import { Loader2 } from "lucide-react"; +import { useEffect, useId, useRef, useState } from "react"; + +import { + accountKey, + bestRemainingAccount, + type LaunchAccount, + type LaunchQuota, + launchAccountQuota, +} from "./launchAccountQuota"; + +interface AccountTerminalFormProps { + mode?: "start" | "resume" | "chat"; + configs: Array<{ id: string; label: string }>; + configId: string; + onConfigChange: (id: string) => void; + accounts: LaunchAccount[]; + provider?: string; + quotas?: readonly LaunchQuota[]; + loading: boolean; + refreshing: boolean; + error: string | null; + notice?: string | null; + launching: boolean; + submitLabel?: string; + launchFailureMessage?: string; + launchDisabled?: boolean; + onRefresh: () => Promise; + onCancel: () => void; + onLaunch: ( + account: Pick, + ) => Promise; +} + +export function AccountTerminalForm({ + mode = "start", + configs, + configId, + onConfigChange, + accounts, + provider = "", + quotas = [], + loading, + refreshing, + error, + notice, + launching, + submitLabel, + launchFailureMessage, + launchDisabled = false, + onRefresh, + onCancel, + onLaunch, +}: AccountTerminalFormProps) { + const { t } = useLingui(); + const { formatPercent } = useFormat(); + const agentId = useId(); + const radioName = useId(); + const [selected, setSelected] = useState(null); + const [launchError, setLaunchError] = useState(null); + const inFlight = useRef(false); + const [, setAgeTick] = useState(0); + const now = Date.now(); + useEffect(() => { + const timer = setInterval(() => setAgeTick((tick) => tick + 1), 30_000); + return () => clearInterval(timer); + }, []); + const recommendation = + !error && !notice && !loading && !refreshing + ? bestRemainingAccount(accounts, provider, quotas, now) + : undefined; + const recommendedKey = recommendation ? accountKey(recommendation) : null; + useEffect(() => { + // Choose once. Refreshes never replace a manual choice or another login. + if (selected === null && recommendedKey !== null) + setSelected(recommendedKey); + }, [selected, recommendedKey]); + const account = accounts.find((entry) => accountKey(entry) === selected); + const selectionChanged = selected !== null && !account; + const canLaunch = Boolean( + account && + !error && + !loading && + !refreshing && + !launching && + !launchDisabled && + configs.some((config) => config.id === configId), + ); + const failure = + error ?? + launchError ?? + (selectionChanged + ? t({ message: "The selected login changed. Choose an account again." }) + : null); + return ( +
{ + event.preventDefault(); + if (!canLaunch || !account || inFlight.current) return; + inFlight.current = true; + setLaunchError(null); + try { + await onLaunch({ + selection: account.selection, + identity: account.identity, + }); + } catch (cause) { + setLaunchError( + errorMessage( + cause, + launchFailureMessage ?? + (mode === "resume" + ? t({ message: "Could not resume this conversation" }) + : mode === "chat" + ? t({ message: "Could not start chat" }) + : t({ message: "Could not start agent terminal" })), + ), + ); + } finally { + inFlight.current = false; + } + }} + > +
+ + +
+
+ + Account + + {loading ? ( + + Loading accounts… + + ) : null} + {!loading && !error && accounts.length === 0 ? ( +

+ + No available subscription accounts. Add or sign in to an account + in Usage, then refresh. + +

+ ) : null} +
+ {accounts.map((entry) => { + const key = accountKey(entry); + const quota = launchAccountQuota(entry, provider, quotas, now); + return ( + + ); + })} +
+
+ {notice && ( + {notice} + )} + {failure && ( +

+ {failure} +

+ )} +
+ +
+ + +
+
+
+ ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/index.ts new file mode 100644 index 00000000000..f331f640044 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/index.ts @@ -0,0 +1 @@ +export { AccountTerminalForm } from "./AccountTerminalForm"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/launchAccountQuota.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/launchAccountQuota.test.ts new file mode 100644 index 00000000000..2ce1617dbce --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/launchAccountQuota.test.ts @@ -0,0 +1,256 @@ +import { expect, test } from "bun:test"; +import { + bestRemainingAccount, + type LaunchAccount, + type LaunchQuota, + launchAccountQuota, +} from "./launchAccountQuota"; + +const now = Date.parse("2026-10-25T12:00:00Z"); +const account: LaunchAccount = { + selection: null, + identity: "identity-a", + email: "a@example.test", + label: "System", +}; +const second = { ...account, selection: "/second", identity: "identity-b" }; +function quota(overrides: Partial = {}): LaunchQuota { + return { + agent: "claude", + selection: null, + email: account.email, + credentialKind: "subscription", + status: "ok", + fetchedAt: new Date(now), + windows: [ + { id: "five_hour", label: "Session", usedPercent: 20, resetsAt: null }, + { id: "seven_day", label: "Weekly", usedPercent: 40, resetsAt: null }, + ], + ...overrides, + }; +} + +function fixtureWindow(reading: LaunchQuota, index: number) { + const window = reading.windows[index]; + if (!window) throw new Error("Missing fixture quota window"); + return window; +} + +test("uses the tightest reported basic limit and ignores model-only caps", () => { + const reading = quota(); + reading.windows.push({ + id: "seven_day_sonnet", + label: "Sonnet", + usedPercent: 100, + resetsAt: null, + }); + expect(launchAccountQuota(account, "claude", [reading], now)?.remaining).toBe( + 60, + ); +}); + +test("recognizes a reported weekly-only plan without inventing a session", () => { + const reading = quota({ agent: "codex" }); + reading.windows = [fixtureWindow(reading, 1)]; + expect( + launchAccountQuota(account, "codex", [reading], now)?.windows, + ).toHaveLength(1); + expect(bestRemainingAccount([account], "codex", [reading], now)).toBe( + account, + ); +}); + +test("refuses unknown, stale, exhausted, future or mismatched readings", () => { + const invalid = [ + quota({ status: "unavailable" }), + quota({ identityChanged: true }), + quota({ fetchedAt: new Date(now - 16 * 60_000 - 1) }), + quota({ fetchedAt: new Date(now + 1) }), + quota({ agent: "codex" }), + quota({ selection: "/other" }), + quota({ email: "other@example.test" }), + quota({ credentialKind: "api_key" }), + quota({ windows: [] }), + quota({ + windows: [ + { id: "five_hour", label: "Session", usedPercent: 100, resetsAt: null }, + ], + }), + ]; + for (const reading of invalid) + expect( + bestRemainingAccount([account], "claude", [reading], now), + ).toBeUndefined(); +}); + +test("per-window age and reset expiry override a fresh outer collection", () => { + for (const extra of [ + { observedAt: new Date(now - 17 * 60_000) }, + { observedAt: "invalid" }, + { resetsAt: new Date(now) }, + { resetsAt: "invalid" }, + { usedPercent: Number.NaN }, + ]) { + const reading = quota(); + Object.assign(fixtureWindow(reading, 0), extra); + expect( + bestRemainingAccount([account], "claude", [reading], now), + ).toBeUndefined(); + } +}); + +test("ambiguous duplicate profiles and partial passive Claude data are not recommended", () => { + expect( + bestRemainingAccount([account], "claude", [quota(), quota()], now), + ).toBeUndefined(); + const partial = quota({ + windows: [ + { + id: "five_hour", + label: "Session", + usedPercent: 1, + resetsAt: null, + source: "claude_statusline", + }, + ], + }); + expect(launchAccountQuota(account, "claude", [partial], now)?.remaining).toBe( + 99, + ); + expect( + bestRemainingAccount([account], "claude", [partial], now), + ).toBeUndefined(); +}); + +test("ranks only listed immutable choices and uses the default as a tie breaker", () => { + const firstQuota = quota(); + const secondQuota = quota({ selection: second.selection, isDefault: true }); + expect( + bestRemainingAccount( + [account, second], + "claude", + [firstQuota, secondQuota], + now, + ), + ).toBe(second); + fixtureWindow(secondQuota, 1).usedPercent = 80; + expect( + bestRemainingAccount( + [account, second], + "claude", + [firstQuota, secondQuota], + now, + ), + ).toBe(account); + expect( + bestRemainingAccount([account], "claude", [secondQuota], now), + ).toBeUndefined(); +}); + +test("best remaining stays available throughout the provider's fifteen-minute cadence", () => { + for (const minutes of [6, 9, 14, 15, 16]) { + const reading = quota({ fetchedAt: new Date(now - minutes * 60_000) }); + for (const window of reading.windows) window.source = "provider"; + expect(bestRemainingAccount([account], "claude", [reading], now)).toBe( + account, + ); + } + expect( + bestRemainingAccount( + [account], + "claude", + [quota({ fetchedAt: new Date(now - 16 * 60_000 - 1) })], + now, + ), + ).toBeUndefined(); +}); + +test("fresh complete native limits can be recommended despite an old HTTP account date", () => { + const reading = quota({ fetchedAt: new Date(now - 90 * 60_000) }); + for (const window of reading.windows) { + window.source = "claude_statusline"; + window.observedAt = new Date(now - 60_000); + } + expect(bestRemainingAccount([account], "claude", [reading], now)).toBe( + account, + ); + expect(reading.fetchedAt).toEqual(new Date(now - 90 * 60_000)); + expect(reading.windows.map((window) => window.observedAt)).toEqual([ + new Date(now - 60_000), + new Date(now - 60_000), + ]); +}); + +test("mixed native and provider limits keep separate ages and never freshen a sibling", () => { + const reading = quota({ fetchedAt: new Date(now - 60 * 60_000) }); + Object.assign(fixtureWindow(reading, 0), { + source: "claude_sdk", + observedAt: new Date(now - 2 * 60_000), + }); + Object.assign(fixtureWindow(reading, 1), { + source: "provider", + observedAt: new Date(now - 15 * 60_000), + }); + expect(bestRemainingAccount([account], "claude", [reading], now)).toBe( + account, + ); + fixtureWindow(reading, 1).observedAt = new Date(now - 16 * 60_000 - 1); + expect( + bestRemainingAccount([account], "claude", [reading], now), + ).toBeUndefined(); + fixtureWindow(reading, 1).observedAt = new Date(now - 60_000); + fixtureWindow(reading, 0).observedAt = new Date(now - 6 * 60_000 - 1); + expect( + bestRemainingAccount([account], "claude", [reading], now), + ).toBeUndefined(); +}); + +test("current global fetch time cannot hide stale, future or unknown native observations", () => { + for (const extra of [ + { source: "claude_sdk", observedAt: new Date(now - 6 * 60_000 - 1) }, + { source: "claude_statusline", observedAt: new Date(now + 1) }, + { source: "unknown", observedAt: new Date(now) }, + ]) { + const reading = quota(); + Object.assign(fixtureWindow(reading, 0), extra); + expect( + bestRemainingAccount([account], "claude", [reading], now), + ).toBeUndefined(); + } +}); + +test("retained, changed-login and unavailable rows cannot recommend fresh-looking windows", () => { + for (const extra of [ + { historical: true }, + { retained: true }, + { identityChanged: true }, + { status: "unavailable" }, + ]) { + const reading = quota(extra); + for (const window of reading.windows) { + window.source = "claude_statusline"; + window.observedAt = new Date(now); + } + expect( + bestRemainingAccount([account], "claude", [reading], now), + ).toBeUndefined(); + } +}); + +test("duplicate partial native session observations do not prove weekly capacity", () => { + const reading = quota(); + reading.windows = [0, 1].map(() => ({ + id: "five_hour", + label: "Session", + usedPercent: 1, + resetsAt: null, + source: "claude_sdk", + observedAt: new Date(now), + })); + expect(launchAccountQuota(account, "claude", [reading], now)?.remaining).toBe( + 99, + ); + expect( + bestRemainingAccount([account], "claude", [reading], now), + ).toBeUndefined(); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/launchAccountQuota.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/launchAccountQuota.ts new file mode 100644 index 00000000000..69205a132fd --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm/launchAccountQuota.ts @@ -0,0 +1,128 @@ +import { quotaObservationFresh } from "shared/quota-freshness"; + +export interface LaunchAccount { + selection: string | null; + identity: string; + email: string; + label: string; +} + +export interface LaunchQuotaWindow { + id: string; + label: string; + usedPercent: number; + resetsAt: Date | string | null; + observedAt?: Date | string; + windowSeconds?: number | null; + source?: string; +} + +/** Optional existing quota response. No private account registry is required. */ +export interface LaunchQuota { + agent: string; + selection: string | null; + email: string | null; + credentialKind: string; + status: string; + fetchedAt: Date | string; + isDefault?: boolean; + identityChanged?: boolean; + /** Retained display history is never a recommendation. */ + historical?: boolean; + retained?: boolean; + windows: LaunchQuotaWindow[]; +} + +export function accountKey( + account: Pick, +) { + return JSON.stringify([account.selection, account.identity]); +} + +function basicWindow(window: LaunchQuotaWindow) { + return ( + ["five_hour", "session", "seven_day", "weekly"].includes(window.id) || + (["primary", "secondary"].includes(window.id) && + typeof window.windowSeconds === "number" && + (window.windowSeconds === 604800 || + (window.windowSeconds > 0 && window.windowSeconds <= 18000))) + ); +} + +/** Never join a quota row by email alone or carry a stale login's reading forward. */ +export function launchAccountQuota( + account: LaunchAccount, + provider: string, + quotas: readonly LaunchQuota[], + now = Date.now(), +) { + const matches = quotas.filter( + (quota) => + quota.agent === provider && + quota.selection === account.selection && + quota.email === account.email, + ); + const quota = matches.length === 1 ? matches[0] : undefined; + if ( + !quota || + quota.credentialKind !== "subscription" || + quota.status !== "ok" || + quota.identityChanged || + quota.historical || + quota.retained + ) + return undefined; + const windows = quota.windows.filter(basicWindow); + if ( + !windows.length || + windows.some((window) => { + const reset = window.resetsAt + ? new Date(window.resetsAt).getTime() + : null; + return ( + !Number.isFinite(window.usedPercent) || + window.usedPercent < 0 || + window.usedPercent > 100 || + !quotaObservationFresh(window, quota.fetchedAt, now) || + (reset !== null && (!Number.isFinite(reset) || reset <= now)) + ); + }) + ) + return undefined; + return { + windows, + remaining: Math.min(...windows.map((window) => 100 - window.usedPercent)), + isDefault: quota.isDefault === true, + // A partial passive Claude observation cannot prove unknown weekly quota. + recommendable: + !windows.some((window) => window.source?.startsWith("claude_")) || + (windows.some((window) => ["five_hour", "session"].includes(window.id)) && + windows.some((window) => ["seven_day", "weekly"].includes(window.id))), + }; +} + +export function bestRemainingAccount( + accounts: readonly LaunchAccount[], + provider: string, + quotas: readonly LaunchQuota[], + now = Date.now(), +): LaunchAccount | undefined { + let best: + | { account: LaunchAccount; remaining: number; isDefault: boolean } + | undefined; + for (const account of accounts) { + const quota = launchAccountQuota(account, provider, quotas, now); + if (!quota || !quota.recommendable || quota.remaining <= 0) continue; + if ( + !best || + quota.remaining > best.remaining || + (quota.remaining === best.remaining && quota.isDefault && !best.isDefault) + ) + best = { + account, + remaining: quota.remaining, + isDefault: quota.isDefault, + }; + } + return best?.account; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/index.ts new file mode 100644 index 00000000000..713b9c1c52b --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/index.ts @@ -0,0 +1 @@ +export { AccountTerminalDialog } from "./AccountTerminalDialog"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AddTabMenu/AddTabMenu.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AddTabMenu/AddTabMenu.test.tsx new file mode 100644 index 00000000000..bfecd048389 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AddTabMenu/AddTabMenu.test.tsx @@ -0,0 +1,43 @@ +import { afterEach, expect, mock, test } from "bun:test"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from "@superset/ui/dropdown-menu"; +import { cleanup, fireEvent, render } from "@testing-library/react"; +import { AddTabMenu } from "./AddTabMenu"; + +afterEach(cleanup); + +test("keeps upstream chat actions and defers the account dialog until the menu closes", () => { + let afterClose: (() => void) | undefined; + const onAddAccountTerminal = mock((_returnFocus: HTMLElement | null) => {}); + const onAddChat = mock(() => {}); + const view = render( + + Add + + {}} + onAddAccountTerminal={onAddAccountTerminal} + onAddChat={onAddChat} + runAfterClose={(action) => { + afterClose = action; + }} + showPresetsBar + onToggleShowPresetsBar={() => {}} + /> + + , + ); + expect(view.getByRole("menuitem", { name: /Chat/ })).toBeTruthy(); + fireEvent.click( + view.getByRole("menuitem", { name: "Agent terminal with account…" }), + ); + expect(onAddAccountTerminal).not.toHaveBeenCalled(); + expect(afterClose).toBeDefined(); + afterClose?.(); + expect(onAddAccountTerminal.mock.calls).toHaveLength(1); + expect(onAddAccountTerminal.mock.calls[0]?.[0]).toBe(view.getByText("Add")); + expect(onAddChat).not.toHaveBeenCalled(); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AddTabMenu/AddTabMenu.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AddTabMenu/AddTabMenu.tsx index 8c771ee70c6..0a149cbbc9f 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AddTabMenu/AddTabMenu.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AddTabMenu/AddTabMenu.tsx @@ -11,6 +11,7 @@ import { HotkeyMenuShortcut } from "renderer/components/HotkeyMenuShortcut"; interface AddTabMenuProps { onAddTerminal: () => void; + onAddAccountTerminal?: (returnFocus: HTMLElement | null) => void; runAfterClose: (action: () => void) => void; onAddChat?: (() => void) | undefined; onAddBrowser?: (() => void) | undefined; @@ -22,6 +23,7 @@ interface AddTabMenuProps { export function AddTabMenu({ onAddTerminal, + onAddAccountTerminal, runAfterClose, onAddChat, onAddBrowser, @@ -42,6 +44,23 @@ export function AddTabMenu({ + {onAddAccountTerminal && ( + { + const triggerId = event.currentTarget + .closest('[role="menu"]') + ?.getAttribute("aria-labelledby"); + const returnFocus = triggerId + ? document.getElementById(triggerId) + : null; + runAfterClose(() => onAddAccountTerminal(returnFocus)); + }} + > + + Agent terminal with account… + + )} {onAddChat && ( diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/index.ts index c64344b8972..95f5f031cf6 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/index.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/index.ts @@ -1,4 +1,5 @@ export type { + CreateAccountTerminal, CreateNewAgentSession, CreateNewAgentSessionInput, OpenAgentChat, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts index 3f0a435e671..8c021bcc156 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useAgentSessionLauncher/useAgentSessionLauncher.ts @@ -38,6 +38,11 @@ export type CreateNewAgentSession = ( type OpenNewChat = () => Promise<{ terminalId: string } | null>; +export type CreateAccountTerminal = (input: { + configId: string; + account: { selection: string | null; identity: string }; +}) => Promise; + export type OpenAgentChat = ( input: Omit & { prompt?: string; @@ -55,17 +60,47 @@ export function useAgentSessionLauncher({ store, }: UseAgentSessionLauncherOptions): { createNewAgentSession: CreateNewAgentSession; + createAccountTerminal: CreateAccountTerminal; openAgentChat: OpenAgentChat; openNewChat: OpenNewChat; focusAgentTerminal: (terminalId: string) => void; } { const { t } = useLingui(); const { mutateAsync: runAgent } = workspaceTrpc.agents.run.useMutation(); + const { mutateAsync: runWithAccount } = + workspaceTrpc.agents.runWithAccount.useMutation(); const appearance = useTerminalAppearance(); const awaitAcpChatEnabled = useAwaitAcpChatEnabled(); const { hostUrl } = useWorkspaceClient(); const { data: agentConfigs } = useV2AgentConfigs(hostUrl); const queryClient = useQueryClient(); + const createAccountTerminal = useCallback( + async ({ configId, account }) => { + const result = await runWithAccount({ + workspaceId, + agent: configId, + account, + prompt: "", + surface: "terminal", + colors: terminalQueryColors(appearance.theme), + }); + if (result.kind !== "terminal") { + throw new Error( + t({ message: "Selected agent isn't a terminal agent" }), + ); + } + store.getState().addTab({ + panes: [ + { + kind: "terminal", + titleOverride: result.label, + data: { terminalId: result.sessionId } satisfies TerminalPaneData, + }, + ], + }); + }, + [runWithAccount, workspaceId, appearance.theme, store, t], + ); const openAgentChat = useCallback( async (input) => { @@ -201,6 +236,7 @@ export function useAgentSessionLauncher({ return { createNewAgentSession, + createAccountTerminal, openAgentChat, openNewChat, focusAgentTerminal, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useConsumeAutomationRunLink/chatSessionTarget.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useConsumeAutomationRunLink/chatSessionTarget.test.ts index 2da1a91d169..6b2bd7ad1c6 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useConsumeAutomationRunLink/chatSessionTarget.test.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/useConsumeAutomationRunLink/chatSessionTarget.test.ts @@ -8,6 +8,9 @@ const session: NonNullable = { scopeId: "workspace-1", harness: "claude-acp", harnessSessionId: "native-1", + createCommandId: null, + launchContextJson: null, + predecessorSessionId: null, epoch: "epoch-1", status: "idle", title: "Automation run", diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/ChatPane.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/ChatPane.tsx index 8dfdb119b5a..996a32166bc 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/ChatPane.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/ChatPane.tsx @@ -9,6 +9,7 @@ import type { } from "renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/types"; import { useLinkClickHint } from "../../hooks/useLinkClickHint"; import { AcpChatPane } from "./components/AcpChatPane"; +import { adoptAccountChatSession } from "./components/AcpChatPane/utils/accountPaneState"; import { useOpenChatLink } from "./hooks/useOpenChatLink"; import { useOpenChatPage } from "./hooks/useOpenChatPage"; import { openChatHistory } from "./utils/chatHistoryOpen"; @@ -61,6 +62,17 @@ export function ChatPane({ { + if (!latest.current.accountBound) + ctx.actions.updateData({ ...latest.current, accountBound: true }); + }} + onAccountSessionCreated={(result) => { + latest.current = adoptAccountChatSession(latest.current, result); + ctx.actions.updateData(latest.current); + }} isActive={ctx.isActive} onPendingPromptsSent={() => { const { @@ -86,7 +98,7 @@ export function ChatPane({ const retitled = title !== undefined && title !== data.chatTitle; if (!rebound && !retitled) return; ctx.actions.updateData({ - ...data, + ...latest.current, ...(rebound ? { agent: { ...rebound, sessionId: harnessSessionId } } : {}), @@ -94,6 +106,7 @@ export function ChatPane({ }); }} onSwitchAgent={({ presetId, label, model, modeId, handoffPrompt }) => { + if (latest.current.accountBound) return; ctx.actions.setTitle(label); ctx.actions.updateData({ terminalId: data.terminalId, @@ -161,7 +174,7 @@ export function ChatPane({ }} onModeChange={(chatModeId) => { if (data.agent) saveChatMode(data.agent.id, chatModeId); - ctx.actions.updateData({ ...data, chatModeId }); + ctx.actions.updateData({ ...latest.current, chatModeId }); }} onSessionCreated={(sessionId, pendingPrompt) => ctx.actions.updateData({ diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx index 8fdd9d407ab..dfa3a50a06b 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/AcpChatPane.tsx @@ -17,7 +17,8 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useTerminalAgentBindings } from "renderer/hooks/host-service/useTerminalAgentBindings"; import { useWorkspaceEvent } from "renderer/hooks/host-service/useWorkspaceEvent"; import { useV2AgentConfigs } from "renderer/hooks/useV2AgentConfigs"; -import type { OpenFile } from "../../../../../../types"; +import { useCollections } from "renderer/routes/_authenticated/providers/CollectionsProvider"; +import type { ChatPaneData, OpenFile } from "../../../../../../types"; import { saveLastChatAgent } from "../../../../../../utils/lastChatAgent"; import { SessionView } from "../../../ChatSession/components/SessionView"; import { useSessionClient } from "../../../ChatSession/hooks/useSessionClient"; @@ -32,8 +33,17 @@ import type { import { isUnrestrictedMode } from "../../../ChatSession/utils/isUnrestrictedMode"; import { useForkChat } from "../../hooks/useForkChat"; import { readSavedChatMode } from "../../utils/savedChatMode"; +import { AccountChatSwitch } from "./components/AccountChatSwitch/AccountChatSwitch"; import { AcpRecovery } from "./components/AcpRecovery"; import { DraftChat } from "./components/DraftChat"; +import { StopAccountAgent } from "./components/StopAccountAgent"; +import { StoppedAccountQueue } from "./components/StoppedAccountQueue"; +import { useRecoveryRetries } from "./hooks/useRecoveryRetries"; +import { accountChatDraftKey } from "./utils/accountPaneState"; +import { + AccountChatPersistenceError, + createPersistedAccountChat, +} from "./utils/createPersistedAccountChat"; import { createWhenReachable } from "./utils/createWhenReachable"; import { isChatCreateWatched, @@ -58,6 +68,11 @@ export interface AgentSwitchTarget { export function AcpChatPane({ agent, + accountBound, + accountDraftId, + accountLaunch, + onAccountBound, + onAccountSessionCreated, isActive, onSessionInfo, onPendingPromptsSent, @@ -80,6 +95,14 @@ export function AcpChatPane({ modelLabel, modeId, }: { + accountBound?: true; + accountDraftId?: string; + accountLaunch?: ChatPaneData["accountLaunch"]; + onAccountBound: () => void; + onAccountSessionCreated: (result: { + sessionId: string; + terminalId: string; + }) => void; workspaceId: string; terminalId: string; /** `sessionId` is absent until the agent has run a turn to report one. */ @@ -109,32 +132,44 @@ export function AcpChatPane({ const { client, wiring } = useSessionClient(sessionId); const { forkToWorktree, canForkToWorktree } = useForkChat(workspaceId); const { hostUrl } = useWorkspaceClient(); + const { activeOrganizationId } = useCollections(); const { data: agentConfigs } = useV2AgentConfigs(hostUrl); const agentLabel = agentConfigs?.find( (config) => config.id === agent?.id, )?.label; const harness = acpHarnessForPreset(agent?.id); const [failure, setFailure] = useState(null); + const [completedRecoveries, setCompletedRecoveries] = useState(0); + const [accountRecoveryPaused, setAccountRecoveryPaused] = useState(false); + const [accountStopRequested, setAccountStopRequested] = useState(false); const [replacement, setReplacement] = useState(null); // The stored session outlives its process — after a host restart the row // still reads "idle" and only the send fails. Ask who is actually running. const { data: stored } = useQuery({ enabled: sessionId !== null, - queryKey: ["acp-chat-session", sessionId], + queryKey: ["acp-chat-session", hostUrl, sessionId], queryFn: () => sessionId ? wiring.transport.getSession({ sessionId }) : Promise.resolve(null), staleTime: 5_000, }); + const bound = useRef(Boolean(accountBound || accountLaunch)); + bound.current ||= Boolean( + accountBound || accountLaunch || stored?.accountBound, + ); + const isAccountBound = bound.current; + useEffect(() => { + if (isAccountBound && !accountBound) onAccountBound(); + }, [isAccountBound, accountBound, onAccountBound]); const queryClient = useQueryClient(); useWorkspaceEvent( "chat:sessions-changed", workspaceId, () => { void queryClient.invalidateQueries({ - queryKey: ["acp-chat-session", sessionId], + queryKey: ["acp-chat-session", hostUrl, sessionId], }); void queryClient.invalidateQueries({ queryKey: ["acp-chat-replacement"], @@ -156,8 +191,55 @@ export function AcpChatPane({ mounted.current = false; }; }, []); + const startAccount = useCallback(async () => { + if ( + !accountLaunch || + (harness !== "claude-acp" && harness !== "codex-acp") || + attaching.current + ) + return; + attaching.current = true; + setFailure(null); + try { + const created = await createPersistedAccountChat({ + storage: window.localStorage, + organizationId: activeOrganizationId, + hostUrl: hostUrl ?? "", + workspaceId, + terminalId, + launch: accountLaunch, + create: (request) => wiring.transport.createAccountSession(request), + }); + if (mounted.current) onAccountSessionCreated(created); + } catch (error) { + if (mounted.current) { + attaching.current = false; + setFailure( + error instanceof AccountChatPersistenceError + ? t({ + message: + "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails.", + }) + : error instanceof Error + ? error.message + : String(error), + ); + } + } + }, [ + t, + accountLaunch, + harness, + wiring.transport, + workspaceId, + terminalId, + hostUrl, + activeOrganizationId, + onAccountSessionCreated, + ]); const start = useCallback( async (resumeHarness: string, resume?: string, replacing = false) => { + if (bound.current) return; attaching.current = true; setFailure(null); try { @@ -196,7 +278,10 @@ export function AcpChatPane({ else onSessionCreated(createdId); } catch (error) { attaching.current = false; - if (replacing) recoveryInFlight.current = false; + if (replacing) { + recoveryInFlight.current = false; + if (mounted.current) setCompletedRecoveries((count) => count + 1); + } setFailure(error instanceof Error ? error.message : String(error)); } }, @@ -220,13 +305,25 @@ export function AcpChatPane({ // pane was opened straight onto the chat and no agent has run yet. useEffect(() => { if (sessionId || attaching.current || !harness) return; + if (isAccountBound) { + if (!failure) void startAccount(); + return; + } void start(harness, agentSessionId); - }, [sessionId, harness, agentSessionId, start]); + }, [ + sessionId, + harness, + agentSessionId, + start, + isAccountBound, + startAccount, + failure, + ]); // The agent copies the session whole — `session/fork` takes no truncation // point — so where it was clicked from makes no difference to the branch. const forkHere = useCallback(() => { - if (!sessionId) return; + if (!sessionId || bound.current) return; const terminalId = crypto.randomUUID(); void wiring.transport .forkSession({ @@ -267,7 +364,7 @@ export function AcpChatPane({ forkHere(); return; } - if (!agent) return; + if (!agent || bound.current) return; void forkToWorktree({ agentId: agent.id, agentLabel: agentLabel ?? agent.id, @@ -284,7 +381,13 @@ export function AcpChatPane({ }, [harness, start]); const agentSwitch = useMemo(() => { - if (!agent || !onSwitchAgent) return undefined; + if ( + !agent || + !onSwitchAgent || + isAccountBound || + (sessionId && stored === undefined) + ) + return undefined; const presetIds = [ ...new Set((agentConfigs ?? []).map((config) => config.presetId)), ].filter((presetId) => acpHarnessForPreset(presetId)); @@ -306,6 +409,7 @@ export function AcpChatPane({ transcript: string, currentModeId: string | undefined, ) => { + if (bound.current) return; const label = agentConfigs?.find((config) => config.presetId === presetId)?.label ?? presetId; @@ -375,6 +479,8 @@ export function AcpChatPane({ sessionId, t, wiring.transport, + isAccountBound, + stored, ]); const sessionDead = stored?.session?.status === "dead"; @@ -401,11 +507,34 @@ export function AcpChatPane({ const recover = useCallback(() => { if (!harness || !sessionId || recoveryInFlight.current) return; recoveryInFlight.current = true; + if (bound.current) { + void wiring.transport + .recoverAccountSession({ commandId: crypto.randomUUID(), sessionId }) + .then((result) => { + if (mounted.current) onAccountSessionCreated(result); + }) + .catch((error: unknown) => { + if (mounted.current) + setFailure(error instanceof Error ? error.message : String(error)); + }) + .finally(() => { + recoveryInFlight.current = false; + if (mounted.current) setCompletedRecoveries((count) => count + 1); + }); + return; + } void wiring.transport .closeSession({ sessionId }) .catch(() => undefined) .then(() => start(harness, agentSessionId, true)); - }, [harness, agentSessionId, sessionId, start, wiring.transport]); + }, [ + harness, + agentSessionId, + sessionId, + start, + wiring.transport, + onAccountSessionCreated, + ]); const { data: replacementState } = useQuery({ enabled: replacement !== null, queryKey: ["acp-chat-replacement", replacement], @@ -440,32 +569,29 @@ export function AcpChatPane({ const timer = setTimeout(commit, REPLACEMENT_TIMEOUT_MS); return () => clearTimeout(timer); }, [replacement, replacementState, onSessionCreated, t]); - const recovering = - replacement !== null || - (recoverable && recoveries.current < MAX_RECOVERIES); - useEffect(() => { - if (!recovering || recoveryInFlight.current) return; - const delayMs = - recoveries.current === 0 && failure === null - ? 0 - : 1_000 * 2 ** Math.max(recoveries.current - 1, 0); - const timer = setTimeout(() => { - recoveries.current += 1; - recover(); - }, delayMs); - return () => clearTimeout(timer); - }, [recovering, recover, failure]); + const recovering = useRecoveryRetries({ + recoverable: recoverable && !accountRecoveryPaused, + replacementPending: replacement !== null, + attempts: recoveries, + inFlight: recoveryInFlight, + completion: completedRecoveries, + failure, + recover, + limit: MAX_RECOVERIES, + }); const retryRecovery = useCallback(() => { - recoveries.current = 0; + if (recoveryInFlight.current) return; + setAccountRecoveryPaused(false); + recoveries.current = 1; setFailure(null); recover(); }, [recover]); - const draftKey = `chat-v3-draft:${terminalId}`; + const draftKey = accountChatDraftKey({ accountDraftId, terminalId }); const editMessage = useCallback( async (request: ChatEditRequest) => { - if (!sessionId || !onRewound) return; + if (!sessionId || !onRewound || bound.current) return; const handoffPrompt = request.transcript.trim() ? buildChatRewindPrompt({ transcript: request.transcript, @@ -551,10 +677,43 @@ export function AcpChatPane({ return ( + reason={ + continuedInTerminal + ? "in-terminal" + : isAccountBound + ? "account" + : "stopped" + } + > + {isAccountBound && + hostUrl && + ((stored?.live && sessionDead) || accountStopRequested) ? ( + + wiring.transport.closeStoppedAccountSession(input) + } + onConfirmed={() => { + setAccountRecoveryPaused(true); + setAccountStopRequested(true); + setFailure(null); + }} + onStopped={() => setAccountStopRequested(false)} + /> + ) : null} + {isAccountBound && hostUrl ? ( + + ) : null} + ); } @@ -563,8 +722,15 @@ export function AcpChatPane({ return ( { + void startAccount(); + } + : undefined + } + reason={isAccountBound ? "account" : "no-transcript"} /> ); } @@ -586,6 +752,7 @@ export function AcpChatPane({ return ( 0 || recovering} + onSwitched={onAccountSessionCreated} + /> + ) : undefined + } agentLabel={agentLabel} agentSwitch={agentSwitch} onModeChange={onModeChange} - canForkToWorktree={canForkToWorktree} + canForkToWorktree={ + canForkToWorktree && !isAccountBound && stored !== undefined + } isActive={isActive} - onFork={fork} - onEditMessage={onRewound ? onEditMessage : undefined} + onFork={isAccountBound || stored === undefined ? undefined : fork} + onEditMessage={!isAccountBound && onRewound ? onEditMessage : undefined} onUserPrompt={agent ? () => saveLastChatAgent(agent.id) : undefined} openFile={onOpenFile} openPage={onOpenPage} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/AccountChatSwitch.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/AccountChatSwitch.test.tsx new file mode 100644 index 00000000000..42290d9e5f7 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/AccountChatSwitch.test.tsx @@ -0,0 +1,54 @@ +import { afterEach, expect, mock, test } from "bun:test"; +import { cleanup, fireEvent, render } from "@testing-library/react"; +import { + AccountSwitchConfirmation, + supportsAccountSwitch, +} from "./AccountChatSwitch"; + +afterEach(cleanup); + +test("old hosts and unsupported harnesses do not expose a switch control", () => { + expect(supportsAccountSwitch(undefined, "claude")).toBe(false); + expect(supportsAccountSwitch({ harnesses: ["claude-acp"] }, "claude")).toBe( + false, + ); + expect( + supportsAccountSwitch( + { accountSwitch: false, harnesses: ["claude-acp"] }, + "claude", + ), + ).toBe(false); + expect( + supportsAccountSwitch( + { accountSwitch: true, harnesses: ["codex-acp"] }, + "claude", + ), + ).toBe(false); + expect( + supportsAccountSwitch( + { accountSwitch: true, harnesses: ["claude-acp"] }, + "claude", + ), + ).toBe(true); +}); + +test("closing the idle source requires an explicit accessible consent", () => { + const onChange = mock((_checked: boolean) => {}); + const view = render( + , + ); + const checkbox = view.getByRole("checkbox", { + name: /Close only this idle agent/, + }) as HTMLInputElement; + expect(checkbox.checked).toBe(false); + fireEvent.click(checkbox); + expect(onChange).toHaveBeenCalledWith(true); + view.rerender( + , + ); + expect((view.getByRole("checkbox") as HTMLInputElement).disabled).toBe(true); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/AccountChatSwitch.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/AccountChatSwitch.tsx new file mode 100644 index 00000000000..28dc125792a --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/AccountChatSwitch.tsx @@ -0,0 +1,212 @@ +import { Trans, useLingui } from "@lingui/react/macro"; +import type { ChatTransport } from "@superset/chat/client"; +import type { ChatAccountSelection } from "@superset/chat/protocol"; +import { errorMessage } from "@superset/i18n/errors"; +import { Button } from "@superset/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@superset/ui/dialog"; +import { useQuery } from "@tanstack/react-query"; +import { useState } from "react"; +import { HOST_USAGE_QUOTA_QUERY_KEY } from "renderer/hooks/host-service/useHostUsageQuota"; +import { useV2AgentConfigs } from "renderer/hooks/useV2AgentConfigs"; +import { getHostServiceClientByUrl } from "renderer/lib/host-service-client"; +import { AccountTerminalForm } from "../../../../../../../../components/AccountTerminalDialog/components/AccountTerminalForm"; +import { switchAccountConversation } from "./switchAccountConversation"; + +export function supportsAccountSwitch( + capabilities: { accountSwitch?: boolean; harnesses: string[] } | undefined, + provider: string, +) { + return ( + capabilities?.accountSwitch === true && + capabilities.harnesses.includes(`${provider}-acp`) + ); +} + +export function AccountSwitchConfirmation({ + confirmed, + switching, + onChange, +}: { + confirmed: boolean; + switching: boolean; + onChange(value: boolean): void; +}) { + return ( + + ); +} + +export function AccountChatSwitch({ + hostUrl, + provider, + current, + sessionId, + transport, + disabled, + onSwitched, +}: { + hostUrl: string | null; + provider: "claude" | "codex"; + current: ChatAccountSelection; + sessionId: string; + transport: ChatTransport; + disabled: boolean; + onSwitched(result: { sessionId: string; terminalId: string }): void; +}) { + const { t } = useLingui(); + const [open, setOpen] = useState(false); + const [confirmed, setConfirmed] = useState(false); + const [switching, setSwitching] = useState(false); + const capabilities = useQuery({ + queryKey: ["chat-account-capabilities", hostUrl], + queryFn: () => transport.accountCapabilities(undefined), + retry: false, + staleTime: 30_000, + }); + const configs = useV2AgentConfigs(hostUrl); + const config = configs.data?.find((entry) => entry.presetId === provider); + const accounts = useQuery({ + queryKey: ["agent-launch-accounts", hostUrl, config?.id], + enabled: Boolean(open && hostUrl && config), + queryFn: () => + getHostServiceClientByUrl(hostUrl as string).agents.launchAccounts.query({ + agent: config?.id as string, + }), + retry: false, + staleTime: 0, + }); + const quota = useQuery({ + queryKey: [...HOST_USAGE_QUOTA_QUERY_KEY, hostUrl], + enabled: Boolean(open && hostUrl && accounts.data?.supported), + queryFn: () => + getHostServiceClientByUrl(hostUrl as string).usage.quota.query(), + retry: false, + staleTime: 5 * 60_000, + }); + // An old host or an unqualified harness keeps the original chat controls. + if (!supportsAccountSwitch(capabilities.data, provider)) return null; + const failure = configs.error ?? accounts.error; + return ( + <> + + { + if (!switching) setOpen(value); + }} + > + + + + Switch account + + + + Reopen this exact saved conversation with another account. Other + chats stay running. No message is sent. + + + + + {}} + accounts={ + accounts.data?.supported + ? accounts.data.accounts.filter( + (account) => + account.selection !== current.selection || + account.identity !== current.identity, + ) + : [] + } + provider={provider} + quotas={quota.isError ? [] : (quota.data ?? [])} + loading={configs.isPending || Boolean(config && accounts.isPending)} + refreshing={accounts.isFetching} + error={ + failure + ? errorMessage( + failure, + t({ message: "Could not load accounts" }), + ) + : !configs.isPending && !config + ? t({ message: "No agent is configured on this host" }) + : accounts.data?.supported === false + ? t({ + message: + "This agent configuration does not support account selection.", + }) + : null + } + launching={switching} + launchDisabled={!confirmed || disabled} + submitLabel={t({ message: "Switch account" })} + launchFailureMessage={t({ message: "Could not switch account" })} + onRefresh={async () => { + await accounts.refetch(); + }} + onCancel={() => setOpen(false)} + onLaunch={async (account) => { + if (!confirmed || disabled) + throw new Error( + t({ + message: + "Confirm that this agent can close safely before switching.", + }), + ); + setSwitching(true); + try { + const result = await switchAccountConversation(transport, { + commandId: crypto.randomUUID(), + sessionId, + account, + }); + onSwitched(result); + setOpen(false); + } finally { + setSwitching(false); + } + }} + /> + + + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/switchAccountConversation.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/switchAccountConversation.test.ts new file mode 100644 index 00000000000..c7292a744d6 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/switchAccountConversation.test.ts @@ -0,0 +1,75 @@ +import { expect, mock, test } from "bun:test"; +import type { ChatTransport } from "@superset/chat/client"; +import { switchAccountConversation } from "./switchAccountConversation"; + +const input = { + commandId: "00000000-0000-4000-8000-000000000001", + sessionId: "source", + account: { selection: "/fixture/b", identity: "b".repeat(64) }, +}; +const result = { sessionId: "successor", epoch: "epoch", terminalId: "pane" }; +function fixture() { + return { + switchAccountSession: mock(async () => result), + accountSessionByCommand: mock(async () => result), + getSession: mock(async () => ({ + session: { predecessorSessionId: "source" }, + account: { ...input.account, agent: "claude" }, + })), + }; +} +type Transport = Pick< + ChatTransport, + "switchAccountSession" | "accountSessionByCommand" | "getSession" +>; + +test("sends the immutable choice once and does not send a continuation prompt", async () => { + const f = fixture(); + expect( + await switchAccountConversation(f as unknown as Transport, input), + ).toEqual(result); + expect(f.switchAccountSession).toHaveBeenCalledTimes(1); + expect(f.switchAccountSession).toHaveBeenCalledWith(input); + expect(f.accountSessionByCommand).not.toHaveBeenCalled(); +}); + +test("a lost reply resolves only the recorded successor and exact destination identity", async () => { + const f = fixture(); + f.switchAccountSession = mock(async () => { + throw new Error("lost reply"); + }); + expect( + await switchAccountConversation(f as unknown as Transport, input), + ).toEqual(result); + expect(f.switchAccountSession).toHaveBeenCalledTimes(1); + expect(f.accountSessionByCommand).toHaveBeenCalledWith({ + commandId: input.commandId, + }); +}); + +test("a different receipt, unavailable host or missing procedure never retries a default launch", async () => { + for (const failure of ["principal", "predecessor", "unavailable"] as const) { + const f = fixture(); + f.switchAccountSession = mock(async () => { + throw new Error("No procedure switchAccountSession"); + }); + if (failure === "principal") + f.getSession = mock(async () => ({ + session: { predecessorSessionId: "source" }, + account: { ...input.account, agent: "claude", identity: "other" }, + })); + if (failure === "predecessor") + f.getSession = mock(async () => ({ + session: { predecessorSessionId: "different" }, + account: { ...input.account, agent: "claude" }, + })); + if (failure === "unavailable") + f.accountSessionByCommand = mock(async () => { + throw new Error("offline"); + }); + await expect( + switchAccountConversation(f as unknown as Transport, input), + ).rejects.toThrow("No procedure"); + expect(f.switchAccountSession).toHaveBeenCalledTimes(1); + } +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/switchAccountConversation.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/switchAccountConversation.ts new file mode 100644 index 00000000000..9dc7bb19f80 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AccountChatSwitch/switchAccountConversation.ts @@ -0,0 +1,31 @@ +import type { ChatTransport } from "@superset/chat/client"; +import type { SwitchAccountSessionInput } from "@superset/chat/protocol"; + +/** A lost mutation reply must not duplicate the switch or fall back to a default login. */ +export async function switchAccountConversation( + transport: Pick< + ChatTransport, + "switchAccountSession" | "accountSessionByCommand" | "getSession" + >, + input: SwitchAccountSessionInput, +) { + try { + return await transport.switchAccountSession(input); + } catch (error) { + const receipt = await transport + .accountSessionByCommand({ commandId: input.commandId }) + .catch(() => null); + if (receipt) { + const saved = await transport + .getSession({ sessionId: receipt.sessionId }) + .catch(() => null); + if ( + saved?.session?.predecessorSessionId === input.sessionId && + saved.account?.selection === input.account.selection && + saved.account.identity === input.account.identity + ) + return receipt; + } + throw error; + } +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AcpRecovery/AcpRecovery.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AcpRecovery/AcpRecovery.tsx index 8055eb3c539..8213513ca26 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AcpRecovery/AcpRecovery.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/AcpRecovery/AcpRecovery.tsx @@ -1,5 +1,6 @@ import { Trans } from "@lingui/react/macro"; import { Button } from "@superset/ui/button"; +import type { ReactNode } from "react"; /** * Shown when the chat cannot be used: the agent session had no transcript to @@ -12,21 +13,25 @@ import { Button } from "@superset/ui/button"; */ export function AcpRecovery({ detail, + children, onResume, onStartNew, reason, }: { - reason: "no-transcript" | "stopped" | "in-terminal"; + reason: "no-transcript" | "stopped" | "in-terminal" | "account"; detail?: string | undefined; + children?: ReactNode; onResume?: () => void; - onStartNew: () => void; + onStartNew?: () => void; }) { return ( // w-full because the pane lays its children out in a row: without it this // sizes to its content and hugs the left edge.

- {reason === "in-terminal" ? ( + {reason === "account" ? ( + This chat could not be opened with its saved account. + ) : reason === "in-terminal" ? ( This chat stopped because the conversation continued in a terminal. @@ -44,15 +49,18 @@ export function AcpRecovery({ {detail}

)} + {children}
{onResume && ( )} - + {onStartNew && ( + + )}
); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/StopAccountAgent.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/StopAccountAgent.test.tsx new file mode 100644 index 00000000000..3a72986b3fb --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/StopAccountAgent.test.tsx @@ -0,0 +1,149 @@ +import { afterEach, expect, mock, test } from "bun:test"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + act, + cleanup, + fireEvent, + render, + waitFor, + within, +} from "@testing-library/react"; +import type { ComponentProps } from "react"; +import { StopAccountAgent } from "./StopAccountAgent"; + +const clients: QueryClient[] = []; +afterEach(() => { + cleanup(); + for (const client of clients.splice(0)) client.clear(); +}); + +function mount( + closeStoppedAccountSession: ComponentProps< + typeof StopAccountAgent + >["closeStoppedAccountSession"], +) { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); + clients.push(client); + const onConfirmed = mock(() => {}); + const onStopped = mock(() => {}); + const component = (sessionId = "session-a") => ( + + + + ); + return { ...render(component()), client, onConfirmed, onStopped, component }; +} + +test("opening then canceling stop confirmation does not stop or resume anything", async () => { + const close = mock(async () => {}); + const view = mount(close); + fireEvent.click(view.getByRole("button", { name: "Stop agent" })); + const dialog = await view.findByRole("alertdialog"); + expect(within(dialog).getByText(/any background work it owns/)).toBeTruthy(); + expect(close).not.toHaveBeenCalled(); + fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + await waitFor(() => expect(view.queryByRole("alertdialog")).toBeNull()); + expect(close).not.toHaveBeenCalled(); + expect(view.onConfirmed).not.toHaveBeenCalled(); + expect(view.onStopped).not.toHaveBeenCalled(); +}); + +test("confirmation stops only the exact session once and invalidates only its host-scoped queries", async () => { + let finish: (() => void) | undefined; + const close = mock( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + const view = mount(close); + const target = ["acp-chat-session", "http://host.test", "session-a"]; + const queue = ["stopped-account-queue", "http://host.test", "session-a"]; + const otherSession = ["acp-chat-session", "http://host.test", "session-b"]; + const otherHost = ["acp-chat-session", "http://other.test", "session-a"]; + for (const key of [target, queue, otherSession, otherHost]) + view.client.setQueryData(key, { live: true }); + fireEvent.click(view.getByRole("button", { name: "Stop agent" })); + const dialog = await view.findByRole("alertdialog"); + const confirm = within(dialog).getByRole("button", { + name: "Stop agent and background work", + }); + fireEvent.click(confirm); + fireEvent.click(confirm); + await waitFor(() => expect(close).toHaveBeenCalledTimes(1)); + expect(close).toHaveBeenCalledWith({ sessionId: "session-a" }); + expect(view.onConfirmed).toHaveBeenCalledTimes(1); + expect(view.client.getQueryState(target)?.isInvalidated).toBe(false); + await act(async () => finish?.()); + await waitFor(() => expect(view.queryByRole("alertdialog")).toBeNull()); + expect(view.client.getQueryState(target)?.isInvalidated).toBe(true); + expect(view.client.getQueryState(queue)?.isInvalidated).toBe(true); + expect(view.client.getQueryState(otherSession)?.isInvalidated).toBe(false); + expect(view.client.getQueryState(otherHost)?.isInvalidated).toBe(false); + expect(view.onStopped).toHaveBeenCalledTimes(1); +}); + +test("a refused stop keeps confirmation and retry controls without automatic retries", async () => { + const close = mock(async () => { + throw new Error("Unsent queue remains"); + }); + const view = mount(close); + fireEvent.click(view.getByRole("button", { name: "Stop agent" })); + const dialog = await view.findByRole("alertdialog"); + fireEvent.click( + within(dialog).getByRole("button", { + name: "Stop agent and background work", + }), + ); + await view.findByRole("alert"); + expect(view.getByRole("alertdialog")).toBeTruthy(); + expect(view.onStopped).not.toHaveBeenCalled(); + await waitFor(() => + expect( + within(dialog) + .getByRole("button", { name: "Stop agent and background work" }) + .hasAttribute("disabled"), + ).toBe(false), + ); + expect(close).toHaveBeenCalledTimes(1); + fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + await waitFor(() => expect(view.queryByRole("alertdialog")).toBeNull()); + expect(close).toHaveBeenCalledTimes(1); +}); + +test("an older host missing the strict endpoint fails visibly without another action", async () => { + const close = mock(async () => { + throw new Error("NOT_FOUND: closeStoppedAccountSession"); + }); + const view = mount(close); + fireEvent.click(view.getByRole("button", { name: "Stop agent" })); + const dialog = await view.findByRole("alertdialog"); + fireEvent.click( + within(dialog).getByRole("button", { + name: "Stop agent and background work", + }), + ); + await view.findByRole("alert"); + expect(close).toHaveBeenCalledTimes(1); + expect(view.getByText(/update this host/)).toBeTruthy(); +}); + +test("changing the pane session dismisses the old confirmation instead of stopping a different chat", async () => { + const close = mock(async () => {}); + const view = mount(close); + fireEvent.click(view.getByRole("button", { name: "Stop agent" })); + await view.findByRole("alertdialog"); + view.rerender(view.component("session-b")); + await waitFor(() => expect(view.queryByRole("alertdialog")).toBeNull()); + expect(close).not.toHaveBeenCalled(); + expect(view.onConfirmed).not.toHaveBeenCalled(); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/StopAccountAgent.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/StopAccountAgent.tsx new file mode 100644 index 00000000000..2fd63de2213 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/StopAccountAgent.tsx @@ -0,0 +1,114 @@ +import { Trans } from "@lingui/react/macro"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@superset/ui/alert-dialog"; +import { Button } from "@superset/ui/button"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useRef, useState } from "react"; + +export function StopAccountAgent({ + hostUrl, + sessionId, + closeStoppedAccountSession, + onConfirmed, + onStopped, +}: { + hostUrl: string; + sessionId: string; + closeStoppedAccountSession: (input: { + sessionId: string; + }) => Promise; + /** Pauses automatic recovery before the explicit stop request is issued. */ + onConfirmed: () => void; + onStopped: () => void; +}) { + const queryClient = useQueryClient(); + const [open, setOpen] = useState(false); + const inFlight = useRef(false); + const stop = useMutation({ + mutationFn: () => closeStoppedAccountSession({ sessionId }), + onSuccess: async () => { + setOpen(false); + onStopped(); + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ["acp-chat-session", hostUrl, sessionId], + exact: true, + }), + queryClient.invalidateQueries({ + queryKey: ["stopped-account-queue", hostUrl, sessionId], + exact: true, + }), + ]); + }, + onSettled: () => { + inFlight.current = false; + }, + }); + return ( + <> + + { + if (!inFlight.current) setOpen(next); + }} + > + + + + Stop this agent and its background work? + + + + This stops the agent process and any background work it owns. + Your saved conversation stays available. Review and discard any + queued messages first. You can then choose Resume. + + + + {stop.isError && ( +

+ + Could not stop the agent. Review queued messages or update this + host, then try again. + +

+ )} + + + Cancel + + { + event.preventDefault(); + if (inFlight.current || stop.isSuccess) return; + inFlight.current = true; + onConfirmed(); + stop.mutate(); + }} + > + Stop agent and background work + + +
+
+ + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/index.ts new file mode 100644 index 00000000000..b24b8daa2cd --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StopAccountAgent/index.ts @@ -0,0 +1 @@ +export { StopAccountAgent } from "./StopAccountAgent"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/StoppedAccountQueue.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/StoppedAccountQueue.test.tsx new file mode 100644 index 00000000000..fa8a871278b --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/StoppedAccountQueue.test.tsx @@ -0,0 +1,102 @@ +import { afterEach, expect, mock, test } from "bun:test"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import type { ComponentProps } from "react"; +import { StoppedAccountQueue } from "./StoppedAccountQueue"; + +const clients: QueryClient[] = []; +afterEach(() => { + cleanup(); + for (const client of clients.splice(0)) client.clear(); +}); + +function mount( + transport: ComponentProps["transport"], + allowRegisteredDead = false, +) { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); + clients.push(client); + return render( + + + , + ); +} + +const prompt = { + itemId: "item-a", + clientId: "client-a", + queuedAtMs: 1, + content: [{ type: "text" as const, text: "Unsent review request" }], +}; + +test("stopped queue is retained until explicit discard and re-read afterward", async () => { + let prompts = [prompt]; + const removeQueuedPrompt = mock(async () => { + prompts = []; + }); + const view = mount({ + getQueue: async () => ({ live: false, paused: true, prompts }), + removeQueuedPrompt, + }); + await view.findByText("Unsent review request"); + expect(removeQueuedPrompt).not.toHaveBeenCalled(); + fireEvent.click(view.getByRole("button", { name: "Discard queued message" })); + await waitFor(() => + expect(view.queryByText("Unsent review request")).toBeNull(), + ); + expect(removeQueuedPrompt).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: "session-a", itemId: "item-a" }), + ); +}); + +test("a failed discard keeps the unsent content visible", async () => { + const view = mount({ + getQueue: async () => ({ live: false, paused: true, prompts: [prompt] }), + removeQueuedPrompt: async () => { + throw new Error("Host disconnected"); + }, + }); + await view.findByText("Unsent review request"); + fireEvent.click(view.getByRole("button", { name: "Discard queued message" })); + await view.findByRole("alert"); + expect(view.getByText("Unsent review request")).toBeTruthy(); +}); + +test("a session that is already live exposes no offline discard controls", async () => { + const getQueue = mock(async () => ({ + live: true, + paused: false, + prompts: [prompt], + })); + const view = mount({ getQueue, removeQueuedPrompt: async () => {} }); + await waitFor(() => expect(getQueue).toHaveBeenCalledTimes(1)); + expect( + view.queryByRole("button", { name: "Discard queued message" }), + ).toBeNull(); +}); + +test("a registered dead session permits explicit queue review without discarding on mount", async () => { + const removeQueuedPrompt = mock(async () => {}); + const view = mount( + { + getQueue: async () => ({ live: true, paused: false, prompts: [prompt] }), + removeQueuedPrompt, + }, + true, + ); + await view.findByText("Unsent review request"); + expect(removeQueuedPrompt).not.toHaveBeenCalled(); + fireEvent.click(view.getByRole("button", { name: "Discard queued message" })); + await waitFor(() => expect(removeQueuedPrompt).toHaveBeenCalledTimes(1)); + expect(removeQueuedPrompt).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: "session-a", itemId: "item-a" }), + ); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/StoppedAccountQueue.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/StoppedAccountQueue.tsx new file mode 100644 index 00000000000..cc30697c5a6 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/StoppedAccountQueue.tsx @@ -0,0 +1,92 @@ +import { Trans } from "@lingui/react/macro"; +import type { ChatTransport } from "@superset/chat/client"; +import { Button } from "@superset/ui/button"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +export function StoppedAccountQueue({ + hostUrl, + sessionId, + transport, + allowRegisteredDead = false, +}: { + hostUrl: string; + sessionId: string; + allowRegisteredDead?: boolean; + transport: { + getQueue: ChatTransport["getQueue"]; + removeQueuedPrompt: ( + input: Parameters[0], + ) => Promise; + }; +}) { + const queryClient = useQueryClient(); + const queryKey = ["stopped-account-queue", hostUrl, sessionId]; + const queue = useQuery({ + queryKey, + queryFn: () => transport.getQueue({ sessionId }), + retry: false, + }); + const discard = useMutation({ + mutationFn: (itemId: string) => + transport.removeQueuedPrompt({ + sessionId, + itemId, + commandId: crypto.randomUUID(), + }), + onSuccess: () => queryClient.invalidateQueries({ queryKey }), + }); + if (queue.isPending) + return ( +

+ Loading… +

+ ); + if (queue.isError) + return ( +

+ Could not read queued messages. +

+ ); + if ( + (queue.data.live && !allowRegisteredDead) || + queue.data.prompts.length === 0 + ) + return null; + return ( +
+

+ + These messages were not sent. Copy anything you need, then discard the + queue before resuming. + +

+
    + {queue.data.prompts.map((prompt) => ( +
  • + {prompt.content.map((content, index) => ( +

    + {content.type === "text" ? content.text : content.name} +

    + ))} + +
  • + ))} +
+ {discard.isError && ( +

+ Could not discard the queued message. +

+ )} +
+ ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/index.ts new file mode 100644 index 00000000000..e67c79cc830 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/components/StoppedAccountQueue/index.ts @@ -0,0 +1 @@ +export { StoppedAccountQueue } from "./StoppedAccountQueue"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/index.ts new file mode 100644 index 00000000000..d961960911c --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/index.ts @@ -0,0 +1 @@ +export { useRecoveryRetries } from "./useRecoveryRetries"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/useRecoveryRetries.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/useRecoveryRetries.test.tsx new file mode 100644 index 00000000000..34aee9cce7f --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/useRecoveryRetries.test.tsx @@ -0,0 +1,124 @@ +import { afterEach, expect, mock, test } from "bun:test"; +import { useCallback, useRef, useState } from "react"; +import { useRecoveryRetries } from "./useRecoveryRetries"; + +const { act, cleanup, renderHook } = await import("@testing-library/react"); +afterEach(cleanup); + +function scheduler() { + const pending = new Map<() => void, number>(); + return { + pending, + schedule: (run: () => void, delayMs: number) => { + pending.set(run, delayMs); + return () => pending.delete(run); + }, + async next() { + const [next] = pending.keys(); + if (!next) throw new Error("No recovery attempt is scheduled"); + pending.delete(next); + await act(async () => next()); + }, + }; +} + +function useFixture( + run: () => Promise, + schedule: ReturnType["schedule"], + enabled: boolean, +) { + const attempts = useRef(0); + const inFlight = useRef(false); + const [failure, setFailure] = useState(null); + const [completion, setCompletion] = useState(0); + const recover = useCallback(() => { + if (inFlight.current) return; + inFlight.current = true; + void run() + .catch((error: unknown) => { + setFailure(error instanceof Error ? error.message : String(error)); + }) + .finally(() => { + inFlight.current = false; + setCompletion((count) => count + 1); + }); + }, [run]); + const recovering = useRecoveryRetries({ + recoverable: enabled, + replacementPending: false, + attempts, + inFlight, + completion, + failure, + recover, + limit: 3, + schedule, + }); + return { recovering, failure, completion, attempts: attempts.current }; +} + +test("three identical recovery failures exhaust the budget and reveal recovery actions", async () => { + const timers = scheduler(); + const recover = mock(async () => { + throw new Error("Review the unsent queue before resuming"); + }); + const view = renderHook(() => useFixture(recover, timers.schedule, true)); + expect([...timers.pending.values()]).toEqual([0]); + await timers.next(); + expect(view.result.current.failure).toBe( + "Review the unsent queue before resuming", + ); + expect([...timers.pending.values()]).toEqual([1_000]); + await timers.next(); + expect([...timers.pending.values()]).toEqual([2_000]); + await timers.next(); + expect(recover).toHaveBeenCalledTimes(3); + expect(view.result.current).toEqual({ + recovering: false, + failure: "Review the unsent queue before resuming", + completion: 3, + attempts: 3, + }); + expect(timers.pending.size).toBe(0); +}); + +test("an unresolved recovery cannot overlap even if the component rerenders", async () => { + const timers = scheduler(); + let rejectAttempt: ((reason: Error) => void) | undefined; + const recover = mock( + () => + new Promise((_resolve, reject) => { + rejectAttempt = reject; + }), + ); + const view = renderHook(() => useFixture(recover, timers.schedule, true)); + await timers.next(); + view.rerender(); + expect(recover).toHaveBeenCalledTimes(1); + expect(timers.pending.size).toBe(0); + expect(view.result.current.recovering).toBe(true); + await act(async () => rejectAttempt?.(new Error("same failure"))); + expect([...timers.pending.values()]).toEqual([1_000]); +}); + +test("disabling or unmounting cancels a scheduled retry without launching", async () => { + const timers = scheduler(); + const recover = mock(async () => { + throw new Error("same failure"); + }); + const view = renderHook( + ({ enabled }) => useFixture(recover, timers.schedule, enabled), + { + initialProps: { enabled: true }, + }, + ); + await timers.next(); + view.rerender({ enabled: false }); + expect(timers.pending.size).toBe(0); + expect(view.result.current.recovering).toBe(false); + view.rerender({ enabled: true }); + expect(timers.pending.size).toBe(1); + view.unmount(); + expect(timers.pending.size).toBe(0); + expect(recover).toHaveBeenCalledTimes(1); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/useRecoveryRetries.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/useRecoveryRetries.ts new file mode 100644 index 00000000000..a068d6c26fc --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/hooks/useRecoveryRetries/useRecoveryRetries.ts @@ -0,0 +1,49 @@ +import { type RefObject, useEffect, useRef } from "react"; + +type Schedule = (run: () => void, delayMs: number) => () => void; +const scheduleTimeout: Schedule = (run, delayMs) => { + const timer = setTimeout(run, delayMs); + return () => clearTimeout(timer); +}; + +export function useRecoveryRetries({ + recoverable, + replacementPending, + attempts, + inFlight, + completion, + failure, + recover, + limit, + schedule = scheduleTimeout, +}: { + recoverable: boolean; + replacementPending: boolean; + attempts: RefObject; + inFlight: RefObject; + /** Changes whenever an attempt settles, even when its error text repeats. */ + completion: number; + failure: string | null; + recover: () => void; + limit: number; + schedule?: Schedule; +}): boolean { + const recovering = + replacementPending || + (recoverable && (inFlight.current || attempts.current < limit)); + const latestCompletion = useRef(completion); + latestCompletion.current = completion; + useEffect(() => { + if (!recovering || inFlight.current) return; + const delayMs = + attempts.current === 0 && failure === null + ? 0 + : 1_000 * 2 ** Math.max(attempts.current - 1, 0); + return schedule(() => { + if (latestCompletion.current !== completion || inFlight.current) return; + attempts.current += 1; + recover(); + }, delayMs); + }, [recovering, recover, failure, completion, attempts, inFlight, schedule]); + return recovering; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/accountPaneState.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/accountPaneState.test.tsx new file mode 100644 index 00000000000..423178a7097 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/accountPaneState.test.tsx @@ -0,0 +1,128 @@ +import { afterEach, expect, test } from "bun:test"; +import type { ChatPaneData } from "renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/types"; +import { + accountChatDraftKey, + adoptAccountChatSession, +} from "./accountPaneState"; + +const { act, cleanup, renderHook } = await import("@testing-library/react"); +const { discardComposerDraft, useComposerDraft } = await import( + "../../../../../ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft" +); + +const ownedDraftKeys = new Set(); +afterEach(() => { + cleanup(); + for (const key of ownedDraftKeys) window.localStorage.removeItem(key); + ownedDraftKeys.clear(); +}); + +function draftKey(data: ChatPaneData) { + const key = accountChatDraftKey(data); + ownedDraftKeys.add(key); + return key; +} + +function data(): ChatPaneData { + const commandId = crypto.randomUUID(); + return { + terminalId: crypto.randomUUID(), + sessionId: null, + agent: { id: "claude" }, + accountBound: true, + accountDraftId: commandId, + accountLaunch: { + hostUrl: "http://fixture.invalid", + request: { + commandId, + workspaceId: "fixture-workspace", + harness: "claude-acp", + account: { selection: null, identity: "a".repeat(64) }, + }, + }, + pendingPrompt: "saved first prompt", + pendingAttachments: [ + { + attachmentId: "fixture-file", + name: "file.txt", + mimeType: "text/plain", + }, + ], + queuedPrompts: [[{ type: "text", text: "second prompt" }]], + chatModelId: "model", + chatModeId: "mode", + chatTitle: "title", + }; +} + +test("adopting the receipt consumes only launch intent and preserves queued work and identity", () => { + const pending = data(); + const before = structuredClone(pending); + const adopted = adoptAccountChatSession(pending, { + sessionId: "server-session", + terminalId: "server-terminal", + }); + expect(pending).toEqual(before); + expect(adopted.accountLaunch).toBeUndefined(); + expect(adopted.accountBound).toBe(true); + expect(adopted.accountDraftId).toBe(pending.accountDraftId); + expect(adopted.pendingPrompt).toBe(pending.pendingPrompt); + expect(adopted.pendingAttachments).toEqual(pending.pendingAttachments); + expect(adopted.queuedPrompts).toEqual(pending.queuedPrompts); + expect(adopted.agent).toEqual(pending.agent); + expect(adopted.chatModelId).toBe("model"); + expect(adopted.chatModeId).toBe("mode"); + expect(adopted.chatTitle).toBe("title"); +}); + +test("text typed before create completes survives the actual composer remount and receipt retry", () => { + const pending = data(); + const starting = renderHook(() => useComposerDraft(draftKey(pending))); + act(() => starting.result.current.onChange("typed during connection")); + const adopted = adoptAccountChatSession(pending, { + sessionId: "server-session", + terminalId: "server-terminal", + }); + // React may mount the new keyed subtree before the old draft's debounce runs. + const running = renderHook(() => useComposerDraft(draftKey(adopted))); + starting.unmount(); + expect(running.result.current.storedDraft).toBe("typed during connection"); + expect(adopted.terminalId).not.toBe(pending.terminalId); + expect(draftKey(adopted)).toBe(draftKey(pending)); + expect(window.localStorage.getItem(draftKey(adopted))).toBe( + "typed during connection", + ); + const retried = adoptAccountChatSession(adopted, { + sessionId: "server-session", + terminalId: "server-terminal", + }); + expect(retried).toEqual(adopted); +}); + +test("recovery preserves the draft key of an older account pane without a draft marker", () => { + const pending = data(); + delete pending.accountDraftId; + delete pending.accountLaunch; + pending.sessionId = "ended-session"; + const stopped = renderHook(() => useComposerDraft(draftKey(pending))); + act(() => stopped.result.current.onChange("keep this recovery draft")); + stopped.unmount(); + const recovered = adoptAccountChatSession(pending, { + sessionId: "recovered-session", + terminalId: "authoritative-terminal", + }); + const resumed = renderHook(() => useComposerDraft(draftKey(recovered))); + expect(resumed.result.current.storedDraft).toBe("keep this recovery draft"); + expect(draftKey(recovered)).toBe(draftKey(pending)); + expect(recovered.accountBound).toBe(true); +}); + +test("discarding a closed account draft prevents a pending debounce from recreating its key", () => { + const pending = data(); + const key = draftKey(pending); + const composer = renderHook(() => useComposerDraft(key)); + act(() => composer.result.current.onChange("closed draft")); + act(() => discardComposerDraft(key)); + composer.unmount(); + expect(window.localStorage.getItem(key)).toBeNull(); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/accountPaneState.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/accountPaneState.ts new file mode 100644 index 00000000000..23a2c3bc429 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/accountPaneState.ts @@ -0,0 +1,23 @@ +import type { ChatPaneData } from "renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/types"; + +export function accountChatDraftKey( + data: Pick, +): string { + return `chat-v3-draft:${data.accountDraftId ?? data.terminalId}`; +} + +export function adoptAccountChatSession( + data: ChatPaneData, + result: { sessionId: string; terminalId: string }, +): ChatPaneData { + const { accountLaunch: _consumed, ...rest } = data; + return { + ...rest, + accountBound: true, + // An existing pane may predate the stable draft marker. Preserve its old + // key before replacing the terminal ID with the host's authoritative one. + accountDraftId: data.accountDraftId ?? data.terminalId, + sessionId: result.sessionId, + terminalId: result.terminalId, + }; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/index.ts new file mode 100644 index 00000000000..c0f63f43419 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/accountPaneState/index.ts @@ -0,0 +1,4 @@ +export { + accountChatDraftKey, + adoptAccountChatSession, +} from "./accountPaneState"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/createPersistedAccountChat.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/createPersistedAccountChat.test.ts new file mode 100644 index 00000000000..09e121dc480 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/createPersistedAccountChat.test.ts @@ -0,0 +1,320 @@ +import { afterEach, describe, expect, it, mock } from "bun:test"; +import { + createCollection, + localStorageCollectionOptions, +} from "@tanstack/react-db"; +import { withQuotaGuard } from "renderer/routes/_authenticated/providers/CollectionsProvider/withQuotaGuard"; +import { z } from "zod"; +import { + type AccountChatLaunch, + createPersistedAccountChat, +} from "./createPersistedAccountChat"; + +const commandId = "853b773c-5e5b-47a2-a239-7e4304ae3367"; +const hostUrl = "http://test-host.invalid"; +const workspaceId = "workspace-test"; +const organizationId = "organization-test"; +const terminalId = "placeholder-terminal"; +const storageKey = `v2-workspace-local-state-${organizationId}`; +const launch: AccountChatLaunch = { + hostUrl, + request: { + commandId, + workspaceId, + harness: "claude-acp", + account: { selection: "fixture", identity: "a".repeat(64) }, + modeId: "default", + modelId: "fixture-model", + }, +}; +const result = { sessionId: "saved-session", terminalId: "server-terminal" }; +const cleanups: Array<() => Promise> = []; +afterEach(async () => { + for (const cleanup of cleanups.splice(0)) await cleanup(); +}); + +function paneData() { + return { + terminalId, + sessionId: null as string | null, + agent: { id: "claude" }, + accountBound: true, + accountDraftId: commandId, + accountLaunch: structuredClone(launch), + }; +} + +function fixture() { + const values = new Map(); + let full = false; + const storage = { + getItem: (key: string) => values.get(key) ?? null, + setItem: (key: string, value: string) => { + if (full) { + const error = new Error("quota reached"); + error.name = "QuotaExceededError"; + throw error; + } + values.set(key, value); + }, + removeItem: (key: string) => values.delete(key), + }; + const row = { + workspaceId, + paneLayout: { + version: 1, + tabs: [ + { + id: "tab", + createdAt: 1, + activePaneId: "pane", + layout: { type: "pane", paneId: "pane" }, + panes: { pane: { id: "pane", kind: "chat-v3", data: paneData() } }, + }, + ], + activeTabId: "tab", + }, + }; + const collection = createCollection( + localStorageCollectionOptions( + withQuotaGuard( + { + id: crypto.randomUUID(), + storageKey, + storage, + schema: z.object({ + workspaceId: z.string(), + paneLayout: z.unknown(), + }), + getKey: (item: { workspaceId: string }) => item.workspaceId, + storageEventApi: { addEventListener() {}, removeEventListener() {} }, + startSync: true, + gcTime: 0, + }, + { storage, reclaim: () => 0, onPersistFailed() {} }, + ), + ), + ); + cleanups.push(() => collection.cleanup()); + const tab = row.paneLayout.tabs[0]; + if (!tab) throw new Error("Missing test tab"); + return { + storage, + values, + row, + tab, + collection, + fill: () => { + full = true; + }, + free: () => { + full = false; + }, + }; +} + +function run( + storage: Pick, + create: ( + request: AccountChatLaunch["request"], + ) => Promise = mock(async () => result), + options: Partial[0]> = {}, +) { + return createPersistedAccountChat({ + storage, + organizationId, + hostUrl, + workspaceId, + terminalId, + launch, + create, + ...options, + }); +} + +describe("account chat durable create boundary", () => { + it("accepts the actual TanStack persisted pane format and exact request", async () => { + const f = fixture(); + f.collection.insert(f.row); + const create = mock(async () => result); + expect(await run(f.storage, create)).toEqual(result); + expect(create).toHaveBeenCalledTimes(1); + expect(create).toHaveBeenCalledWith(launch.request); + }); + + it("refuses a quota-dropped optimistic pane before any provider request", async () => { + const f = fixture(); + f.fill(); + f.collection.insert(f.row); + expect(f.collection.get(workspaceId)).toBeDefined(); + expect(f.storage.getItem(storageKey)).toBeNull(); + const create = mock(async () => result); + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + expect(create).not.toHaveBeenCalled(); + }); + + it("refuses an old persisted selection when only the optimistic row changed", async () => { + const f = fixture(); + f.tab.panes.pane.data.accountLaunch.request.account.identity = "b".repeat( + 64, + ); + f.collection.insert(f.row); + f.fill(); + f.collection.update(workspaceId, (draft) => { + draft.paneLayout = { + ...f.row.paneLayout, + tabs: [ + { + ...f.tab, + panes: { pane: { id: "pane", kind: "chat-v3", data: paneData() } }, + }, + ], + }; + }); + const create = mock(async () => result); + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + expect(create).not.toHaveBeenCalled(); + }); + + it("allows the same command after space is freed and a tab rename saves the layout", async () => { + const f = fixture(); + f.fill(); + f.collection.insert(f.row); + const create = mock(async () => result); + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + f.free(); + // Freeing space alone does not rewrite the optimistic collection. + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + f.collection.update(workspaceId, (draft) => { + draft.paneLayout = { + ...f.row.paneLayout, + tabs: [{ ...f.tab, titleOverride: "Saved account chat" }], + }; + }); + expect(await run(f.storage, create)).toEqual(result); + expect(create).toHaveBeenCalledTimes(1); + expect(create).toHaveBeenCalledWith(launch.request); + }); + + it.each([ + "host", + "workspace", + "account", + "command", + "model", + "mode", + "harness", + ])("refuses changed %s context without calling create", async (field) => { + const f = fixture(); + const saved = f.tab.panes.pane.data.accountLaunch; + if (field === "host") saved.hostUrl = "http://other-host.invalid"; + if (field === "workspace") saved.request.workspaceId = "other-workspace"; + if (field === "account") saved.request.account.selection = "other"; + if (field === "command") saved.request.commandId = crypto.randomUUID(); + if (field === "model") saved.request.modelId = "other-model"; + if (field === "mode") saved.request.modeId = "other-mode"; + if (field === "harness") saved.request.harness = "codex-acp"; + f.collection.insert(f.row); + const create = mock(async () => result); + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + expect(create).not.toHaveBeenCalled(); + }); + + it("rejects a request routed to a different current host or workspace", async () => { + const f = fixture(); + f.collection.insert(f.row); + const create = mock(async () => result); + await expect( + run(f.storage, create, { hostUrl: "other-host" }), + ).rejects.toThrow(); + await expect( + run(f.storage, create, { workspaceId: "other-workspace" }), + ).rejects.toThrow(); + expect(create).not.toHaveBeenCalled(); + }); + + it("does not launch on read errors, malformed data or missing rows", async () => { + const f = fixture(); + const create = mock(async () => result); + await expect( + run( + { + getItem() { + throw new Error("unrelated private data"); + }, + }, + create, + ), + ).rejects.toThrow("persistence could not be verified"); + f.values.set(storageKey, "broken json"); + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + f.values.set(storageKey, "{}"); + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + expect(create).not.toHaveBeenCalled(); + }); + + it.each([ + "bound", + "draft", + "adopted", + "unreachable", + "duplicate", + ])("refuses a %s pane that cannot safely own this create", async (field) => { + const f = fixture(); + const tab = f.tab; + if (field === "bound") tab.panes.pane.data.accountBound = false; + if (field === "draft") + tab.panes.pane.data.accountDraftId = "different-draft"; + if (field === "adopted") tab.panes.pane.data.sessionId = "existing-session"; + if (field === "unreachable") tab.layout.paneId = "different-pane"; + if (field === "duplicate") f.row.paneLayout.tabs.push(structuredClone(tab)); + f.collection.insert(f.row); + const create = mock(async () => result); + await expect(run(f.storage, create)).rejects.toThrow( + "persistence could not be verified", + ); + expect(create).not.toHaveBeenCalled(); + }); + + it("retries a lost response with the same durable command and immutable payload", async () => { + const f = fixture(); + f.collection.insert(f.row); + const receipts = new Map(); + const payloads: unknown[] = []; + let launches = 0; + let loseResponse = true; + const create = mock(async (request: AccountChatLaunch["request"]) => { + payloads.push(request); + if (!receipts.has(request.commandId)) { + launches++; + receipts.set(request.commandId, result); + } + if (loseResponse) { + loseResponse = false; + throw new Error("response lost"); + } + const receipt = receipts.get(request.commandId); + if (!receipt) throw new Error("Missing test receipt"); + return receipt; + }); + await expect(run(f.storage, create)).rejects.toThrow("response lost"); + expect(await run(f.storage, create)).toEqual(result); + expect(payloads).toEqual([launch.request, launch.request]); + expect(payloads[0]).not.toBe(launch.request); + expect(launches).toBe(1); + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/createPersistedAccountChat.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/createPersistedAccountChat.ts new file mode 100644 index 00000000000..ae2215c56d8 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/createPersistedAccountChat.ts @@ -0,0 +1,139 @@ +import { + type CreateAccountSessionInput, + createAccountSessionInputSchema, +} from "@superset/chat/protocol"; +import { z } from "zod"; + +const launchSchema = z.strictObject({ + hostUrl: z.string().min(1), + request: createAccountSessionInputSchema, +}); + +export type AccountChatLaunch = z.infer; + +// The existing org collection shares Chromium's bounded localStorage quota. +const MAX_LAYOUT_CHARACTERS = 16 * 1024 * 1024; +export class AccountChatPersistenceError extends Error { + constructor() { + super("Account chat persistence could not be verified"); + this.name = "AccountChatPersistenceError"; + } +} + +function record(value: unknown): Record | null { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : null; +} + +function containsPane(node: unknown, paneId: string, depth = 0): boolean { + if (depth > 64) return false; + const value = record(node); + if (value?.type === "pane") return value.paneId === paneId; + return ( + value?.type === "split" && + (containsPane(value.first, paneId, depth + 1) || + containsPane(value.second, paneId, depth + 1)) + ); +} + +function sameLaunch( + left: AccountChatLaunch, + right: AccountChatLaunch, +): boolean { + return ( + left.hostUrl === right.hostUrl && + left.request.commandId === right.request.commandId && + left.request.workspaceId === right.request.workspaceId && + left.request.harness === right.request.harness && + left.request.account.selection === right.request.account.selection && + left.request.account.identity === right.request.account.identity && + left.request.modeId === right.request.modeId && + left.request.modelId === right.request.modelId + ); +} + +/** + * Read the real backing storage, not the optimistic collection: its quota guard + * intentionally permits in-memory writes after a failed localStorage write. + * No new key or retry command is created, and no provider is closed on failure. + */ +export async function createPersistedAccountChat({ + storage, + organizationId, + hostUrl, + workspaceId, + terminalId, + launch, + create, +}: { + storage: Pick; + organizationId: string; + hostUrl: string; + workspaceId: string; + terminalId: string; + launch: AccountChatLaunch; + create: (request: CreateAccountSessionInput) => Promise; +}): Promise { + let captured: AccountChatLaunch; + try { + captured = launchSchema.parse(launch); + if ( + !organizationId || + !terminalId || + captured.hostUrl !== hostUrl || + captured.request.workspaceId !== workspaceId + ) + throw new AccountChatPersistenceError(); + const serialized = storage.getItem( + `v2-workspace-local-state-${organizationId}`, + ); + if (!serialized || serialized.length > MAX_LAYOUT_CHARACTERS) + throw new AccountChatPersistenceError(); + const collection = record(JSON.parse(serialized)); + if (!collection) throw new AccountChatPersistenceError(); + // TanStack's localStorage adapter stores encoded-key -> {versionKey,data}. + const rows = Object.values(collection) + .map((entry) => record(record(entry)?.data)) + .filter((row) => row?.workspaceId === workspaceId); + if (rows.length !== 1) throw new AccountChatPersistenceError(); + let matches = 0; + for (const slot of ["paneLayout", "rightPaneLayout"]) { + const layout = record(rows[0]?.[slot]); + if (layout?.version !== 1 || !Array.isArray(layout.tabs)) continue; + for (const rawTab of layout.tabs) { + const tab = record(rawTab); + const panes = record(tab?.panes); + if (!panes) continue; + for (const rawPane of Object.values(panes)) { + const pane = record(rawPane); + const data = record(pane?.data); + if ( + pane?.kind !== "chat-v3" || + typeof pane.id !== "string" || + !containsPane(tab?.layout, pane.id) || + data?.terminalId !== terminalId + ) + continue; + const saved = launchSchema.safeParse(data.accountLaunch); + if ( + data.sessionId !== null || + data.accountBound !== true || + data.accountDraftId !== captured.request.commandId || + record(data.agent)?.id !== + captured.request.harness.replace(/-acp$/, "") || + !saved.success || + !sameLaunch(captured, saved.data) + ) + throw new AccountChatPersistenceError(); + matches++; + } + } + } + if (matches !== 1) throw new AccountChatPersistenceError(); + } catch { + // Storage exceptions can contain unrelated persisted data. Do not surface it. + throw new AccountChatPersistenceError(); + } + return create(captured.request); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/index.ts new file mode 100644 index 00000000000..2164d2d4678 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/AcpChatPane/utils/createPersistedAccountChat/index.ts @@ -0,0 +1,5 @@ +export { + type AccountChatLaunch, + AccountChatPersistenceError, + createPersistedAccountChat, +} from "./createPersistedAccountChat"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/ChatHistoryPicker/utils/historyEntries.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/ChatHistoryPicker/utils/historyEntries.test.ts index 0ef4d97a18d..43fceee5789 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/ChatHistoryPicker/utils/historyEntries.test.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/components/ChatHistoryPicker/utils/historyEntries.test.ts @@ -9,6 +9,9 @@ function saved(overrides: Partial = {}): SavedSession { scopeId: "workspace", harness: "claude-acp", harnessSessionId: "native-1", + createCommandId: null, + launchContextJson: null, + predecessorSessionId: null, epoch: "epoch", status: "idle", title: "Saved chat", diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/Composer.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/Composer.tsx index b231c7f0f2e..bdf418b70c6 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/Composer.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/Composer.tsx @@ -6,7 +6,6 @@ import type { UserContent, } from "@superset/chat/protocol"; import type { - ComposerChip, ComposerMentionEntry, ComposerMentionProvider, PromptInputCommand, @@ -38,7 +37,6 @@ import { useChatComposerStore } from "../../../../stores/chatComposerStore"; import { CHAT_COLUMN_CLASSNAME, CHAT_GUTTER_CLASSNAME } from "../../constants"; import { commandChip, LEADING_COMMAND } from "../../utils/commandChip"; import { mcpContextLine } from "../../utils/mcpServerChips"; -import { elementsForChips } from "../../utils/messageElements"; import { type AgentSwitcher, ModelPicker } from "./components/ModelPicker"; import { ModePicker, type SessionMode } from "./components/ModePicker"; import { useAttachmentPreview } from "./hooks/useAttachmentPreview"; @@ -50,6 +48,7 @@ import { useDrawerEntry } from "./hooks/useDrawerEntry"; import { useFooterTier } from "./hooks/useFooterTier"; import { useMcpServerPicker } from "./hooks/useMcpServerPicker"; import { useUploadAttachments } from "./hooks/useUploadAttachments"; +import { submitMessage } from "./utils/submitMessage"; export type ComposerTarget = { name: string; @@ -151,7 +150,7 @@ export const Composer = memo(function Composer({ const cloudUtils = cloudTrpc.useUtils(); const uploadAttachments = useUploadAttachments(workspaceId); const attachmentPreview = useAttachmentPreview(); - const { storedDraft, onChange, clearDraft } = useComposerDraft( + const { storedDraft, onChange, beginSubmission } = useComposerDraft( draftKey, draftPersisted, ); @@ -352,58 +351,20 @@ export const Composer = memo(function Composer({ return [...local, ...agentCommands]; }, [availableCommands, mcpCommand, resumeCommand, t]); - const send = useCallback( - async ( - text: string, - files: File[], - mentions: ComposerChip[], - pastedTexts: string[], - steer: boolean, - ) => { - const tags = await uploadAttachments(files); - if (!tags) { - promptInputRef.current?.appendText(appendPastedText(text, pastedTexts)); - return; - } - const message = text.trim(); - const elements = elementsForChips(message, mentions); - const mcpContext = mcpContextLine( - mentions.flatMap((chip) => mcpPicker.serverNameOf(chip) ?? []), - ); - onSend( - [ - { - type: "text", - text: appendPastedText( - [message, ...tags].filter(Boolean).join("\n"), - pastedTexts, - ), - ...(elements.length > 0 ? { elements } : {}), - }, - ...(mcpContext - ? [{ type: "text" as const, text: mcpContext, hidden: true }] - : []), - ], - { steer }, - ); - clearDraft(); - }, - [onSend, uploadAttachments, clearDraft, mcpPicker.serverNameOf], - ); - const handleSubmit = useCallback( - ({ + async ({ text, files, mentions, pastedTexts, steer, + isDraftUnchanged, }: PromptInputSubmitPayload) => { if ( blocked || (text.trim() === "" && files.length === 0 && pastedTexts.length === 0) ) - return; + return false; const name = LEADING_COMMAND.exec(text.trim())?.[1]; const input = promptInputRef.current; if (text.trim() === "/mcp" && mcpPicker.command && input) { @@ -438,9 +399,40 @@ export const Composer = memo(function Composer({ toast.error(t({ message: `Unknown command /${name}` })); return false; } - return send(text, files, mentions, pastedTexts, steer); + const finishSubmission = beginSubmission( + appendPastedText(text, pastedTexts), + isDraftUnchanged, + ); + if (!finishSubmission) return false; + try { + const result = await submitMessage( + { text, files, mentions, pastedTexts, steer }, + { + uploadAttachments, + onSend, + mcpContext: mcpContextLine( + mentions.flatMap((chip) => mcpPicker.serverNameOf(chip) ?? []), + ), + }, + ); + finishSubmission(result !== false); + return result; + } catch (error) { + finishSubmission(false); + throw error; + } }, - [availableCommands, blocked, send, t, target, mcpPicker, onOpenHistory], + [ + availableCommands, + blocked, + onSend, + uploadAttachments, + t, + beginSubmission, + target, + mcpPicker, + onOpenHistory, + ], ); return ( diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.test.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.test.tsx index 23fdb48b2ff..516bab3d446 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.test.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.test.tsx @@ -1,10 +1,65 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { appendPastedText, parsePastedText } from "@superset/chat/core"; -const { act, cleanup, renderHook } = await import("@testing-library/react"); +const { act, cleanup, fireEvent, render, renderHook } = await import( + "@testing-library/react" +); const { prependToDraft, takeRecoveredDraftText, useComposerDraft } = await import("./useComposerDraft"); +function requireSubmission( + submission: ReturnType< + ReturnType["beginSubmission"] + >, +) { + if (!submission) throw new Error("Expected the submission to start"); + return submission; +} + +const { PromptInput } = await import("@superset/chat-ui/PromptInput"); +type PromptProps = import("@superset/chat-ui/PromptInput").PromptInputProps; + +function PendingDraftComposer({ + draftKey, + findChips, + collapseLargePastes, + inputRef, + onSend, +}: Pick & { + inputRef?: PromptProps["ref"]; + draftKey: string; + onSend: () => Promise; +}) { + const { storedDraft, onChange, beginSubmission } = useComposerDraft(draftKey); + return ( + { + const finish = beginSubmission( + appendPastedText(payload.text, payload.pastedTexts), + payload.isDraftUnchanged, + ); + if (!finish) return false; + try { + const result = await onSend(); + finish(result); + return result === false ? false : undefined; + } catch (error) { + finish(false); + throw error; + } + }} + /> + ); +} + beforeEach(() => window.localStorage.clear()); afterEach(cleanup); test("a composer mounted before the save delay reads text typed into the one it replaces", () => { @@ -121,3 +176,544 @@ test("text restored to a subagent's draft stays in memory and reaches its compos ); expect(reopened.result.current.storedDraft).toBe("for the subagent"); }); + +test("an accepted upload/send after unmount clears the submitted persisted draft", async () => { + const { submitMessage } = await import("../../utils/submitMessage"); + const key = "chat-v3-draft:accepted-after-unmount"; + const composer = renderHook(() => useComposerDraft(key)); + act(() => composer.result.current.onChange(" submitted text ")); + const upload = Promise.withResolvers(); + const finishSubmission = requireSubmission( + composer.result.current.beginSubmission("submitted text"), + ); + const pending = submitMessage( + { + text: "submitted text", + files: [], + mentions: [], + pastedTexts: [], + steer: false, + }, + { uploadAttachments: () => upload.promise, onSend: async () => true }, + ); + composer.unmount(); + upload.resolve([]); + finishSubmission((await pending) !== false); + expect(window.localStorage.getItem(key)).toBeNull(); + const remounted = renderHook(() => useComposerDraft(key)); + expect(remounted.result.current.storedDraft).toBeUndefined(); +}); + +test("rejected or thrown submissions preserve the unmounted draft", async () => { + const { submitMessage } = await import("../../utils/submitMessage"); + for (const rejection of [false, new Error("not accepted")]) { + const key = `chat-v3-draft:rejected-${String(rejection)}`; + const composer = renderHook(() => useComposerDraft(key)); + act(() => composer.result.current.onChange("keep this")); + const finish = requireSubmission( + composer.result.current.beginSubmission("keep this"), + ); + composer.unmount(); + try { + const result = await submitMessage( + { + text: "keep this", + files: [], + mentions: [], + pastedTexts: [], + steer: false, + }, + { + uploadAttachments: async () => [], + onSend: async () => { + if (rejection instanceof Error) throw rejection; + return rejection; + }, + }, + ); + finish(result !== false); + } catch { + finish(false); + } + expect(window.localStorage.getItem(key)).toBe("keep this"); + } +}); + +test("a raw edit and undo invalidate a pending submission", () => { + const key = "chat-v3-draft:submission-aba"; + const composer = renderHook(() => useComposerDraft(key)); + act(() => composer.result.current.onChange(" same text ")); + const finish = requireSubmission( + composer.result.current.beginSubmission("same text"), + ); + act(() => composer.result.current.onChange("same text")); + act(() => composer.result.current.onChange(" same text ")); + composer.unmount(); + finish(true); + expect(window.localStorage.getItem(key)).toBe(" same text "); +}); + +test("recovered text invalidates a pending submission", () => { + const key = "chat-v3-draft:submission-recovery"; + const composer = renderHook(() => useComposerDraft(key)); + act(() => composer.result.current.onChange("submitted")); + const finish = requireSubmission( + composer.result.current.beginSubmission("submitted"), + ); + prependToDraft(key, ["recovered queued message"]); + composer.unmount(); + finish(true); + expect(window.localStorage.getItem(key)).toBe( + "recovered queued message\n\nsubmitted", + ); +}); + +test("a different mount of the same draft can edit while a submission settles", () => { + const key = "chat-v3-draft:submission-other-mount"; + const first = renderHook(() => useComposerDraft(key)); + act(() => first.result.current.onChange("submitted")); + const finish = requireSubmission( + first.result.current.beginSubmission("submitted"), + ); + const second = renderHook(() => useComposerDraft(key)); + act(() => second.result.current.onChange("newer draft")); + first.unmount(); + finish(true); + second.unmount(); + expect(window.localStorage.getItem(key)).toBe("newer draft"); +}); + +test("a same-key remount cannot replace an in-flight submission", () => { + const key = "chat-v3-draft:submission-newer"; + const first = renderHook(() => useComposerDraft(key)); + act(() => first.result.current.onChange("submitted")); + const finish = requireSubmission( + first.result.current.beginSubmission("submitted"), + ); + first.unmount(); + const replacement = renderHook(() => useComposerDraft(key)); + try { + expect(replacement.result.current.beginSubmission("submitted")).toBeNull(); + } finally { + act(() => finish(true)); + } + expect(window.localStorage.getItem(key)).toBeNull(); + expect(replacement.result.current.storedDraft).toBeUndefined(); +}); + +test("acceptance retains an empty memory fallback when storage removal fails", () => { + const key = "chat-v3-draft:submission-remove-failure"; + const composer = renderHook(() => useComposerDraft(key)); + act(() => composer.result.current.onChange("submitted")); + const finish = requireSubmission( + composer.result.current.beginSubmission("submitted"), + ); + composer.unmount(); + const removeItem = spyOn( + window.localStorage, + "removeItem", + ).mockImplementation(() => { + throw new Error("SecurityError"); + }); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + finish(true); + const next = renderHook(() => useComposerDraft(key)); + expect(next.result.current.storedDraft).toBe(""); + act(() => next.result.current.onChange("newer draft")); + next.unmount(); + expect(window.localStorage.getItem(key)).toBe("newer draft"); + } finally { + removeItem.mockRestore(); + warn.mockRestore(); + } +}); + +test("a submission keeps its original draft key across navigation", () => { + const firstKey = "chat-v3-draft:submission-navigation-a"; + const secondKey = "chat-v3-draft:submission-navigation-b"; + const composer = renderHook(({ key }) => useComposerDraft(key), { + initialProps: { key: firstKey }, + }); + act(() => composer.result.current.onChange("submitted")); + const finish = requireSubmission( + composer.result.current.beginSubmission("submitted"), + ); + composer.rerender({ key: secondKey }); + act(() => composer.result.current.onChange("next chat draft")); + finish(true); + composer.unmount(); + expect(window.localStorage.getItem(firstKey)).toBeNull(); + expect(window.localStorage.getItem(secondKey)).toBe("next chat draft"); +}); + +test("acceptance clears the mounted seed before navigating back to the same draft", () => { + const key = "chat-v3-draft:submission-seeded-navigation"; + window.localStorage.setItem(key, "submitted"); + const composer = renderHook(({ key }) => useComposerDraft(key), { + initialProps: { key }, + }); + const finish = requireSubmission( + composer.result.current.beginSubmission("submitted"), + ); + act(() => finish(true)); + composer.rerender({ + key: "chat-v3-draft:submission-seeded-navigation-other", + }); + composer.rerender({ key }); + expect(composer.result.current.storedDraft).toBeUndefined(); +}); + +test("acceptance cannot restore the seed of a replacement mount", () => { + const key = "chat-v3-draft:submission-replacement-seed"; + window.localStorage.setItem(key, "submitted"); + const first = renderHook(() => useComposerDraft(key)); + const finish = requireSubmission( + first.result.current.beginSubmission("submitted"), + ); + const replacement = renderHook(({ key }) => useComposerDraft(key), { + initialProps: { key }, + }); + first.unmount(); + act(() => finish(true)); + replacement.rerender({ key: "chat-v3-draft:submission-replacement-other" }); + replacement.rerender({ key }); + expect(replacement.result.current.storedDraft).toBeUndefined(); +}); + +test("a temporary storage read failure keeps the mounted draft seed", () => { + const key = "chat-v3-draft:seed-read-failure"; + window.localStorage.setItem(key, "keep this draft"); + const composer = renderHook(() => useComposerDraft(key)); + const getItem = spyOn(window.localStorage, "getItem").mockImplementation( + () => { + throw new Error("SecurityError"); + }, + ); + try { + composer.rerender(); + expect(composer.result.current.storedDraft).toBe("keep this draft"); + } finally { + getItem.mockRestore(); + } +}); + +test("acceptance while navigated away clears the original cached seed", () => { + const key = "chat-v3-draft:submission-away-seed"; + window.localStorage.setItem(key, "submitted"); + const composer = renderHook(({ key }) => useComposerDraft(key), { + initialProps: { key }, + }); + const finish = requireSubmission( + composer.result.current.beginSubmission("submitted"), + ); + composer.rerender({ key: "chat-v3-draft:submission-away-other" }); + finish(true); + composer.rerender({ key }); + expect(composer.result.current.storedDraft).toBeUndefined(); +}); + +test("a late plugin chip stays saved when a send is accepted after close", async () => { + const key = "chat-v3-draft:late-plugin-hydration"; + const text = "Review @example.ts"; + window.localStorage.setItem(key, text); + const accepted = Promise.withResolvers(); + const onSend = () => accepted.promise; + const composer = render( + , + ); + await act(async () => {}); + fireEvent.click(composer.getByRole("button", { name: "Send message" })); + composer.rerender( + [ + { + start: 7, + end: text.length, + chip: { label: "Example file", serialized: "@example.ts" }, + }, + ]} + />, + ); + await act(async () => {}); + + expect(composer.getByText("Example file")).toBeTruthy(); + expect(composer.getByRole("textbox").textContent).toBe("Review Example file"); + composer.unmount(); + await act(async () => accepted.resolve(true)); + expect(window.localStorage.getItem(key)).toBe(text); + const reopened = render( + , + ); + await act(async () => {}); + + expect(reopened.getByRole("textbox").textContent).toBe(text); +}); + +test("draft edits, clearing and recovery do not release an in-flight send", () => { + for (const change of ["edit", "clear", "recover"]) { + const key = `chat-v3-draft:pending-${change}`; + const first = renderHook(() => useComposerDraft(key)); + act(() => first.result.current.onChange("submitted")); + const finish = requireSubmission( + first.result.current.beginSubmission("submitted"), + ); + act(() => { + if (change === "edit") first.result.current.onChange("newer draft"); + if (change === "clear") first.result.current.clearDraft(); + if (change === "recover") prependToDraft(key, ["recovered"]); + }); + first.unmount(); + const replacement = renderHook(() => useComposerDraft(key)); + try { + expect( + replacement.result.current.beginSubmission("next send"), + ).toBeNull(); + } finally { + finish(false); + } + const retry = replacement.result.current.beginSubmission("next send"); + expect(retry).toBeFunction(); + retry?.(false); + replacement.unmount(); + } +}); + +test("in-flight guards stay with their draft key across navigation", () => { + const key = "chat-v3-draft:pending-navigation"; + const composer = renderHook(({ draftKey }) => useComposerDraft(draftKey), { + initialProps: { draftKey: key }, + }); + act(() => composer.result.current.onChange("first draft")); + const finishFirst = requireSubmission( + composer.result.current.beginSubmission("first draft"), + ); + composer.rerender({ draftKey: `${key}-other` }); + act(() => composer.result.current.onChange("second draft")); + const finishOther = requireSubmission( + composer.result.current.beginSubmission("second draft"), + ); + expect(finishOther).toBeFunction(); + composer.rerender({ draftKey: key }); + try { + expect(composer.result.current.beginSubmission("first draft")).toBeNull(); + } finally { + act(() => finishFirst(true)); + act(() => finishOther?.(false)); + } + const retry = composer.result.current.beginSubmission("another message"); + expect(retry).toBeFunction(); + retry?.(false); + composer.unmount(); + expect(window.localStorage.getItem(key)).toBeNull(); + expect(window.localStorage.getItem(`${key}-other`)).toBe("second draft"); +}); + +test("a remounted chip-edited composer declines duplicate sends until acceptance", async () => { + const key = "chat-v3-draft:pending-remount-chip"; + const text = "Review @example.ts"; + window.localStorage.setItem(key, text); + const accepted = Promise.withResolvers(); + let sendCount = 0; + const onSend = () => { + sendCount += 1; + return accepted.promise; + }; + const original = render( + , + ); + await act(async () => {}); + fireEvent.click(original.getByRole("button", { name: "Send message" })); + original.rerender( + [ + { + start: 7, + end: text.length, + chip: { label: "Example file", serialized: "@example.ts" }, + }, + ]} + />, + ); + await act(async () => {}); + expect(original.getByText("Example file")).toBeTruthy(); + original.unmount(); + const replacement = render( + , + ); + await act(async () => {}); + try { + await act(async () => + fireEvent.click( + replacement.getByRole("button", { name: "Send message" }), + ), + ); + expect(sendCount).toBe(1); + } finally { + await act(async () => accepted.resolve(true)); + } + expect(window.localStorage.getItem(key)).toBe(text); + expect(replacement.getByRole("textbox").textContent).toBe(text); + await act(async () => + fireEvent.click(replacement.getByRole("button", { name: "Send message" })), + ); + expect(sendCount).toBe(2); + replacement.unmount(); + expect(window.localStorage.getItem(key)).toBeNull(); +}); + +test.each([ + false, + new Error("not accepted"), +])("a remounted composer can retry after a pending send settles with %s", async (rejection) => { + const key = `chat-v3-draft:pending-remount-rejected-${String(rejection)}`; + window.localStorage.setItem(key, "retry this draft"); + const pending = Promise.withResolvers(); + let sendCount = 0; + const onSend = () => { + sendCount += 1; + return pending.promise; + }; + const original = render( + , + ); + await act(async () => {}); + fireEvent.click(original.getByRole("button", { name: "Send message" })); + original.unmount(); + const replacement = render( + , + ); + await act(async () => {}); + try { + await act(async () => + fireEvent.click( + replacement.getByRole("button", { name: "Send message" }), + ), + ); + expect(sendCount).toBe(1); + } finally { + await act(async () => { + if (rejection instanceof Error) pending.reject(rejection); + else pending.resolve(false); + }); + } + expect(replacement.getByRole("textbox").textContent).toBe("retry this draft"); + await act(async () => + fireEvent.click(replacement.getByRole("button", { name: "Send message" })), + ); + expect(sendCount).toBe(2); + replacement.unmount(); + expect(window.localStorage.getItem(key)).toBe("retry this draft"); +}); + +test("an accepted non-persisted subagent draft clears in memory without writing storage", () => { + const key = "chat-v3-draft:accepted-subagent:child"; + const storageWrite = spyOn(window.localStorage, "setItem"); + const storageRemove = spyOn(window.localStorage, "removeItem"); + try { + const composer = renderHook(() => useComposerDraft(key, false)); + act(() => composer.result.current.onChange("subagent message")); + const finish = requireSubmission( + composer.result.current.beginSubmission("subagent message"), + ); + composer.unmount(); + finish(true); + const reopened = renderHook(() => useComposerDraft(key, false)); + expect(reopened.result.current.storedDraft).toBeUndefined(); + expect(storageWrite).not.toHaveBeenCalled(); + expect(storageRemove).not.toHaveBeenCalled(); + } finally { + storageWrite.mockRestore(); + storageRemove.mockRestore(); + } +}); + +test("a declined non-persisted subagent draft survives remount and can retry", () => { + const key = "chat-v3-draft:declined-subagent:child"; + const composer = renderHook(() => useComposerDraft(key, false)); + act(() => composer.result.current.onChange("retry subagent message")); + const finish = requireSubmission( + composer.result.current.beginSubmission("retry subagent message"), + ); + composer.unmount(); + finish(false); + const reopened = renderHook(() => useComposerDraft(key, false)); + expect(reopened.result.current.storedDraft).toBe("retry subagent message"); + const retry = requireSubmission( + reopened.result.current.beginSubmission("retry subagent message"), + ); + act(() => retry(true)); + expect(window.localStorage.getItem(key)).toBeNull(); +}); + +test("clearing an ephemeral target does not discard a parent draft waiting to save", () => { + const key = "chat-v3-draft:parent-before-subagent"; + const composer = renderHook( + ({ draftKey, persisted }) => useComposerDraft(draftKey, persisted), + { initialProps: { draftKey: key, persisted: true } }, + ); + act(() => composer.result.current.onChange("parent draft")); + composer.rerender({ draftKey: `${key}:child`, persisted: false }); + act(() => composer.result.current.clearDraft()); + composer.unmount(); + expect(window.localStorage.getItem(key)).toBe("parent draft"); + expect(window.localStorage.getItem(`${key}:child`)).toBeNull(); +}); + +test("acceptance clears the serialized pasted-card draft only after sending finishes", async () => { + const key = "chat-v3-draft:accepted-pasted-card"; + const text = appendPastedText("Review the log", ["original pasted log"]); + window.localStorage.setItem(key, text); + const accepted = Promise.withResolvers(); + const composer = render( + accepted.promise} + />, + ); + await act(async () => {}); + expect(composer.getByText("original pasted log")).toBeTruthy(); + fireEvent.click(composer.getByRole("button", { name: "Send message" })); + await act(async () => {}); + expect(window.localStorage.getItem(key)).toBe(text); + expect(composer.getByText("original pasted log")).toBeTruthy(); + await act(async () => accepted.resolve(true)); + expect(composer.queryByText("original pasted log")).toBeNull(); + expect(composer.getByRole("textbox").textContent).toBe(""); + expect(window.localStorage.getItem(key)).toBeNull(); +}); + +test("a pasted card recovered while acceptance is pending keeps the newer draft", async () => { + const key = "chat-v3-draft:pending-pasted-recovery"; + window.localStorage.setItem(key, "Review the log"); + const accepted = Promise.withResolvers(); + const inputRef: { + current: import("@superset/chat-ui/PromptInput").PromptInputHandle | null; + } = { current: null }; + const composer = render( + accepted.promise} + />, + ); + await act(async () => {}); + fireEvent.click(composer.getByRole("button", { name: "Send message" })); + await act(async () => { + inputRef.current?.appendText(appendPastedText("", ["new recovered log"])); + }); + await act(async () => accepted.resolve(true)); + expect(composer.getByText("new recovered log")).toBeTruthy(); + expect(composer.getByRole("textbox").textContent).toBe("Review the log"); + composer.unmount(); + expect(parsePastedText(window.localStorage.getItem(key) ?? "")).toEqual({ + text: "Review the log", + pastes: ["new recovered log"], + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.ts index cc16790e743..58caf9ef415 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft.ts @@ -5,6 +5,9 @@ const DRAFT_DEBOUNCE_MS = 300; const unsavedDrafts = new Map(); const recoveredAfterRead = new Map(); +const pendingSubmissions = new Map(); +const inFlightSubmissions = new Map(); +const clearedDraftListeners = new Map void>>(); function persistDraft(draftKey: string, text: string): boolean { try { @@ -17,13 +20,26 @@ function persistDraft(draftKey: string, text: string): boolean { } } -function readDraft(draftKey: string): string | undefined { +function clearStoredDraft(draftKey: string, persisted: boolean) { + unsavedDrafts.set(draftKey, ""); + if (!persisted || persistDraft(draftKey, "")) unsavedDrafts.delete(draftKey); + for (const notify of clearedDraftListeners.get(draftKey) ?? []) notify(); +} + +export function discardComposerDraft(draftKey: string, persisted = true) { + pendingSubmissions.delete(draftKey); + recoveredAfterRead.delete(draftKey); + inFlightSubmissions.delete(draftKey); + clearStoredDraft(draftKey, persisted); +} + +function readDraft(draftKey: string, fallback?: string): string | undefined { const unsaved = unsavedDrafts.get(draftKey); if (unsaved !== undefined) return unsaved; try { return window.localStorage.getItem(draftKey) ?? undefined; } catch { - return undefined; + return fallback; } } @@ -43,6 +59,7 @@ export function prependToDraft( texts: readonly string[], persisted = true, ) { + pendingSubmissions.delete(draftKey); const merged = joinDrafts([...texts, readDraft(draftKey) ?? ""]); unsavedDrafts.set(draftKey, merged); if (persisted) persistDraft(draftKey, merged); @@ -74,6 +91,9 @@ export function useComposerDraft(draftKey: string, persisted = true) { }, []); const onChange = useCallback( (text: string) => { + const submission = pendingSubmissions.get(draftKey); + if (submission && submission.text !== text) + pendingSubmissions.delete(draftKey); if (!persisted) { if (text === "") unsavedDrafts.delete(draftKey); else unsavedDrafts.set(draftKey, text); @@ -93,15 +113,60 @@ export function useComposerDraft(draftKey: string, persisted = true) { return { draftKey, text: readDraft(draftKey) }; }); + useEffect(() => { + setSeed((current) => { + const text = readDraft( + draftKey, + current.draftKey === draftKey ? current.text : undefined, + ); + return current.draftKey === draftKey && current.text === text + ? current + : { draftKey, text }; + }); + const listeners = + clearedDraftListeners.get(draftKey) ?? new Set<() => void>(); + const clearSeed = () => setSeed({ draftKey, text: undefined }); + listeners.add(clearSeed); + clearedDraftListeners.set(draftKey, listeners); + return () => { + listeners.delete(clearSeed); + if (listeners.size === 0) clearedDraftListeners.delete(draftKey); + }; + }, [draftKey]); + + const beginSubmission = useCallback( + (text: string, isDraftUnchanged?: () => boolean) => { + if (inFlightSubmissions.has(draftKey)) return null; + pendingSubmissions.delete(draftKey); + const submitted = { text: readDraft(draftKey) ?? "" }; + inFlightSubmissions.set(draftKey, submitted); + if (submitted.text.trim() === text.trim()) + pendingSubmissions.set(draftKey, submitted); + return (accepted: boolean) => { + if (inFlightSubmissions.get(draftKey) !== submitted) return; + inFlightSubmissions.delete(draftKey); + if (pendingSubmissions.get(draftKey) !== submitted) return; + pendingSubmissions.delete(draftKey); + if ( + !accepted || + isDraftUnchanged?.() === false || + (readDraft(draftKey) ?? "") !== submitted.text + ) + return; + clearStoredDraft(draftKey, persisted); + }; + }, + [draftKey, persisted], + ); + const clearDraft = useCallback(() => { - unsavedDrafts.delete(draftKey); - if (persisted) { + pendingSubmissions.delete(draftKey); + if (pendingDraftKey.current === draftKey) { if (draftTimer.current) clearTimeout(draftTimer.current); draftTimer.current = null; pendingDraftKey.current = null; - persistDraft(draftKey, ""); } - setSeed({ draftKey, text: undefined }); + clearStoredDraft(draftKey, persisted); }, [draftKey, persisted]); if (seed.draftKey !== draftKey) { @@ -109,9 +174,8 @@ export function useComposerDraft(draftKey: string, persisted = true) { setSeed({ draftKey, text: readDraft(draftKey) }); } - return { - storedDraft: seed.draftKey === draftKey ? seed.text : readDraft(draftKey), - onChange, - clearDraft, - }; + const storedDraft = + seed.draftKey === draftKey ? seed.text : readDraft(draftKey); + + return { storedDraft, onChange, clearDraft, beginSubmission }; } diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/index.ts new file mode 100644 index 00000000000..ee2ccccce76 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/index.ts @@ -0,0 +1 @@ +export { submitMessage } from "./submitMessage"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/submitMessage.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/submitMessage.test.ts new file mode 100644 index 00000000000..bf75e7569f3 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/submitMessage.test.ts @@ -0,0 +1,155 @@ +import { expect, mock, test } from "bun:test"; +import { parsePastedText } from "@superset/chat/core"; +import type { UserContent } from "@superset/chat/protocol"; +import type { PromptInputSubmitPayload } from "@superset/chat-ui/PromptInput"; +import { submitMessage } from "./submitMessage"; + +const draft: PromptInputSubmitPayload = { + text: "Review the file", + files: [], + mentions: [], + pastedTexts: [], + steer: false, +}; + +test("failed attachment upload declines submission without sending", async () => { + const onSend = mock(); + const result = await submitMessage(draft, { + uploadAttachments: async () => null, + onSend, + }); + expect(result).toBe(false); + expect(onSend).not.toHaveBeenCalled(); +}); + +test("submission remains pending until the send callback accepts", async () => { + let accept!: () => void; + const pending = new Promise((resolve) => { + accept = resolve; + }); + let settled = false; + const result = submitMessage(draft, { + uploadAttachments: async () => [], + onSend: () => pending, + }).then(() => { + settled = true; + }); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + accept(); + await result; + expect(settled).toBe(true); +}); + +test("a declined send propagates false so the composer retains its draft", async () => { + expect( + await submitMessage(draft, { + uploadAttachments: async () => [], + onSend: async () => false, + }), + ).toBe(false); +}); + +test("rejected sends remain rejected so the composer does not clear its draft", async () => { + const failure = new Error("Transport unavailable"); + await expect( + submitMessage(draft, { + uploadAttachments: async () => [], + onSend: async () => { + throw failure; + }, + }), + ).rejects.toBe(failure); +}); + +test("accepted sends retain attachment tags, chip metadata and steering", async () => { + const onSend = mock(() => ({ clientId: "accepted-outbox-entry" })); + await submitMessage( + { + ...draft, + text: "Read example.ts", + mentions: [ + { + label: "Example", + serialized: "example.ts", + data: { elementKind: "file_mention" }, + }, + ], + steer: true, + }, + { + uploadAttachments: async () => ["[attachment: review.txt]"], + onSend, + }, + ); + expect(onSend).toHaveBeenCalledWith( + [ + { + type: "text", + text: "Read example.ts\n[attachment: review.txt]", + elements: [ + { + byteRange: { start: 5, end: 15 }, + elementKind: "file_mention", + label: "Example", + }, + ], + }, + ], + { steer: true }, + ); +}); + +test("accepted sends keep pasted-card contents and hidden MCP context", async () => { + const onSend = mock< + (content: UserContent[], options: { steer: boolean }) => Promise + >(async () => undefined); + const mcpContext = + 'MCP context: Use the configured MCP server "Fixture MCP" when relevant to this request.'; + await submitMessage( + { + ...draft, + text: " Review the log ", + pastedTexts: ["first pasted log", "second pasted log"], + }, + { + uploadAttachments: async () => ["[attachment: review.txt]"], + onSend, + mcpContext, + }, + ); + expect(onSend).toHaveBeenCalledTimes(1); + const [content, options] = onSend.mock.calls[0] ?? []; + expect(content).toHaveLength(2); + const first = content?.[0]; + if (first?.type !== "text") throw new Error("Expected text content"); + expect(parsePastedText(first.text)).toEqual({ + text: "Review the log\n[attachment: review.txt]", + pastes: ["first pasted log", "second pasted log"], + }); + expect(content?.[1]).toEqual({ + type: "text", + text: mcpContext, + hidden: true, + }); + expect(options).toEqual({ steer: false }); +}); + +test("a pasted-card-only message sends its content without a fabricated visible prompt", async () => { + const onSend = mock< + (content: UserContent[], options: { steer: boolean }) => Promise + >(async () => undefined); + await submitMessage( + { ...draft, text: "", pastedTexts: ["complete pasted message"] }, + { uploadAttachments: async () => [], onSend, mcpContext: null }, + ); + const [content] = onSend.mock.calls[0] ?? []; + expect(content).toHaveLength(1); + const first = content?.[0]; + if (first?.type !== "text") throw new Error("Expected text content"); + expect(parsePastedText(first.text)).toEqual({ + text: "", + pastes: ["complete pasted message"], + }); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/submitMessage.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/submitMessage.ts new file mode 100644 index 00000000000..054b88cb9ea --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Composer/utils/submitMessage/submitMessage.ts @@ -0,0 +1,39 @@ +import { appendPastedText } from "@superset/chat/core"; +import type { UserContent } from "@superset/chat/protocol"; +import type { PromptInputSubmitPayload } from "@superset/chat-ui/PromptInput"; +import { elementsForChips } from "../../../../utils/messageElements"; + +export async function submitMessage( + { text, files, mentions, pastedTexts, steer }: PromptInputSubmitPayload, + { + uploadAttachments, + onSend, + mcpContext, + }: { + uploadAttachments: (files: File[]) => Promise; + onSend: (content: UserContent[], options: { steer: boolean }) => unknown; + mcpContext?: string | null; + }, +) { + const tags = await uploadAttachments(files); + if (!tags) return false; + const message = text.trim(); + const elements = elementsForChips(message, mentions); + const result = await onSend( + [ + { + type: "text", + text: appendPastedText( + [message, ...tags].filter(Boolean).join("\n"), + pastedTexts, + ), + ...(elements.length > 0 ? { elements } : {}), + }, + ...(mcpContext + ? [{ type: "text" as const, text: mcpContext, hidden: true }] + : []), + ], + { steer }, + ); + if (result === false) return false; +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalAgentAutoResume/TerminalAgentAutoResume.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalAgentAutoResume/TerminalAgentAutoResume.tsx index e3ae71ca410..5f2f3163331 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalAgentAutoResume/TerminalAgentAutoResume.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalAgentAutoResume/TerminalAgentAutoResume.tsx @@ -8,6 +8,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useTerminalResumeCandidate } from "renderer/hooks/host-service/useTerminalResumeCandidate"; import { useTerminalResumedSuccessor } from "renderer/hooks/host-service/useTerminalResumedSuccessor"; import { useWorkspaceEvent } from "renderer/hooks/host-service/useWorkspaceEvent"; +import { resumeWithBackgroundReconnect } from "renderer/lib/terminal/resume-with-background-reconnect"; import type { ConnectionState } from "renderer/lib/terminal/terminal-runtime-registry"; import { terminalRuntimeRegistry } from "renderer/lib/terminal/terminal-runtime-registry"; import type { @@ -74,6 +75,7 @@ export function TerminalAgentAutoResume({ invalidate(); }, [connectionState, invalidate]); + const host = workspaceTrpc.useUtils().client; const { mutateAsync: resumeAsync } = workspaceTrpc.terminalAgents.resume.useMutation(); @@ -132,7 +134,19 @@ export function TerminalAgentAutoResume({ void (async () => { try { - const result = await resumeAsync({ workspaceId, terminalId }); + const result = await resumeWithBackgroundReconnect( + { workspaceId, terminalId }, + candidate?.agentId ?? "", + { + capabilities: () => + host.terminalAgents.backgroundRecoveryCapabilities.query(), + source: (input) => + host.terminalAgents.backgroundRecoverySource.query(input), + reconnect: (input) => + host.terminalAgents.reconnectBackground.mutate(input), + }, + resumeAsync, + ); if (!result.resumed) { // Another caller consumed the candidate (or it vanished). // Lifecycle events are fire-and-forget, so refetch explicitly @@ -162,6 +176,8 @@ export function TerminalAgentAutoResume({ })(); }, [ shouldResume, + host, + candidate?.agentId, candidateSessionId, resumeAsync, invalidate, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/TerminalPaneHeaderExtras.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/TerminalPaneHeaderExtras.tsx index 00ab9fb34f3..06ae689ddd1 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/TerminalPaneHeaderExtras.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/TerminalPaneHeaderExtras.tsx @@ -9,6 +9,8 @@ import { terminalRichInputOpenStore, useTerminalRichInputOpen, } from "../../richInputOpenStore"; +import { ContinueBackgroundButton } from "./components/ContinueBackgroundButton"; +import { ResumeAccountButton } from "./components/ResumeAccountButton"; import { TerminalConnectionIndicator } from "./components/TerminalConnectionIndicator"; import { TerminalIdCopyMenu } from "./components/TerminalIdCopyMenu"; import { TerminalPageWatchChip } from "./components/TerminalPageWatchChip"; @@ -58,6 +60,16 @@ export function TerminalPaneHeaderExtras({ return (
+ + + hostUrl + ? getHostServiceClientByUrl(hostUrl) + .terminalAgents.backgroundRecoveryCapabilities.query() + .catch(() => null) + : null, + }); + const source = useQuery({ + queryKey: ["background-recovery-source", hostUrl, workspaceId, terminalId], + enabled: Boolean( + hostUrl && + !binding && + capability.data?.version === 1 && + capability.data.claudeLiveAttach, + ), + retry: false, + staleTime: 15_000, + queryFn: () => + hostUrl + ? getHostServiceClientByUrl( + hostUrl, + ).terminalAgents.backgroundRecoverySource.query({ + workspaceId, + terminalId, + }) + : null, + }); + if (binding || source.data?.provider !== "claude" || !hostUrl) return null; + return ( + + + + + + Continue + + + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ContinueBackgroundButton/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ContinueBackgroundButton/index.ts new file mode 100644 index 00000000000..cd20929f5ce --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ContinueBackgroundButton/index.ts @@ -0,0 +1 @@ +export { ContinueBackgroundButton } from "./ContinueBackgroundButton"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/ResumeAccountButton.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/ResumeAccountButton.tsx new file mode 100644 index 00000000000..ec7a0ef1910 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/ResumeAccountButton.tsx @@ -0,0 +1,227 @@ +import { Trans, useLingui } from "@lingui/react/macro"; +import { errorMessage } from "@superset/i18n/errors"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@superset/ui/dialog"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@superset/ui/tooltip"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { UsersRound } from "lucide-react"; +import { useState } from "react"; +import { useTerminalAgentBinding } from "renderer/hooks/host-service/useTerminalAgentBindings"; +import { getTerminalResumedSuccessorQueryKey } from "renderer/hooks/host-service/useTerminalResumedSuccessor/useTerminalResumedSuccessor"; +import { useWorkspaceEvent } from "renderer/hooks/host-service/useWorkspaceEvent"; +import { useWorkspaceHostUrl } from "renderer/hooks/host-service/useWorkspaceHostUrl"; +import { getHostServiceClientByUrl } from "renderer/lib/host-service-client"; +import { AccountTerminalForm } from "renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/components/AccountTerminalDialog/components/AccountTerminalForm"; + +import { resumeWithSuccessorRecovery } from "./resumeWithSuccessorRecovery"; + +export function ResumeAccountButton({ + workspaceId, + terminalId, +}: { + workspaceId: string; + terminalId: string; +}) { + const { t } = useLingui(); + const hostUrl = useWorkspaceHostUrl(workspaceId); + const binding = useTerminalAgentBinding(workspaceId, terminalId); + const queryClient = useQueryClient(); + const [open, setOpen] = useState(false); + const [resuming, setResuming] = useState(false); + const capability = useQuery({ + queryKey: ["account-recovery-capability", hostUrl], + enabled: Boolean(hostUrl && !binding), + retry: false, + staleTime: 60_000, + queryFn: () => + hostUrl + ? getHostServiceClientByUrl(hostUrl) + .terminalAgents.accountRecoveryCapabilities.query() + .catch(() => null) + : null, + }); + const supported = + capability.data?.version === 1 && + capability.data.exactAccountResume === true; + const sourceKey = ["account-resume-source", hostUrl, workspaceId, terminalId]; + const source = useQuery({ + queryKey: sourceKey, + enabled: Boolean(hostUrl && !binding && supported), + queryFn: ({ signal }) => { + if (!hostUrl) return null; + return getHostServiceClientByUrl( + hostUrl, + ).terminalAgents.accountResumeSource.query( + { workspaceId, terminalId }, + { signal }, + ); + }, + retry: false, + staleTime: 15_000, + }); + const invalidateSource = (event: { terminalId: string }) => { + if (event.terminalId === terminalId) { + void queryClient.invalidateQueries({ queryKey: sourceKey }); + } + }; + useWorkspaceEvent("agent:lifecycle", workspaceId, invalidateSource); + useWorkspaceEvent("terminal:lifecycle", workspaceId, invalidateSource); + const candidate = source.data; + const accounts = useQuery({ + queryKey: ["agent-launch-accounts", hostUrl, candidate?.agent], + enabled: Boolean( + open && hostUrl && candidate?.ready && !binding && supported, + ), + queryFn: ({ signal }) => { + if (!hostUrl || !candidate) throw new Error("Host unavailable"); + return getHostServiceClientByUrl(hostUrl).agents.launchAccounts.query( + { agent: candidate.agent }, + { signal }, + ); + }, + retry: false, + staleTime: 0, + }); + // Older hosts do not expose this capability. Never fall back to a default-account resume. + if (!supported && !open) return null; + if (!candidate && !open) return null; + if (binding && !open) return null; + const error = + binding || !supported || !candidate || source.isError + ? t({ message: "This conversation is no longer available to resume." }) + : !candidate.ready + ? (candidate.reason ?? + t({ + message: + "This conversation cannot be resumed with another account.", + })) + : accounts.isError + ? errorMessage( + accounts.error, + t({ message: "Could not load accounts" }), + ) + : accounts.data?.supported === false + ? t({ + message: + "This agent configuration does not support account selection.", + }) + : null; + return ( + <> + + + + + + Resume with another account + + + !resuming && setOpen(value)}> + + + + Resume with another account + + + + Reopen the saved conversation in the same workspace. No message + is sent. Background work is not transferred. + + + + {candidate && ( +

+ {candidate.sessionId} +

+ )} + {}} + accounts={accounts.data?.supported ? accounts.data.accounts : []} + loading={ + source.isPending || + (Boolean(candidate?.ready) && accounts.isPending) + } + refreshing={source.isFetching || accounts.isFetching} + error={error} + launching={resuming} + onCancel={() => setOpen(false)} + onRefresh={async () => { + await source.refetch(); + await accounts.refetch(); + }} + onLaunch={async (account) => { + if (!supported || !candidate?.ready || !hostUrl || binding) + return; + setResuming(true); + try { + const client = getHostServiceClientByUrl(hostUrl); + await resumeWithSuccessorRecovery( + queryClient, + getTerminalResumedSuccessorQueryKey(workspaceId, terminalId), + async () => { + const result = + await client.terminalAgents.resumeWithAccount.mutate({ + workspaceId, + terminalId, + expectedRevision: candidate.revision, + account, + }); + if (!result.resumed) + throw new Error( + t({ + message: + "This conversation is no longer available to resume.", + }), + ); + return { + terminalId: result.terminalId, + label: result.label, + }; + }, + () => + client.terminalAgents.resumedSuccessor.query({ + workspaceId, + terminalId, + }), + ); + setOpen(false); + } finally { + setResuming(false); + void source.refetch(); + } + }} + /> +
+
+ + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/cacheResumedSuccessor.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/cacheResumedSuccessor.test.ts new file mode 100644 index 00000000000..41ee7280334 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/cacheResumedSuccessor.test.ts @@ -0,0 +1,41 @@ +import { expect, test } from "bun:test"; +import { QueryClient } from "@tanstack/react-query"; +import { cacheResumedSuccessor } from "./cacheResumedSuccessor"; + +test("late pre-resume null cannot erase the confirmed successor", async () => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const key = ["terminal-resumed-successor", "workspace", "old-terminal"]; + const pending = Promise.withResolvers(); + const oldLookup = client + .fetchQuery({ queryKey: key, queryFn: () => pending.promise }) + .catch(() => undefined); + const successor = { terminalId: "new-terminal", label: "Claude" }; + await cacheResumedSuccessor(client, key, successor); + pending.resolve(null); + await oldLookup; + expect(client.getQueryData(key)).toEqual(successor); + client.clear(); +}); + +test("cancels only the resumed terminal lookup", async () => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const pending = Promise.withResolvers(); + const key = ["terminal-resumed-successor", "workspace", "other-terminal"]; + const otherLookup = client.fetchQuery({ + queryKey: key, + queryFn: () => pending.promise, + }); + await cacheResumedSuccessor( + client, + ["terminal-resumed-successor", "workspace", "old-terminal"], + { terminalId: "new-terminal", label: "Claude" }, + ); + expect(client.getQueryState(key)?.fetchStatus).toBe("fetching"); + pending.resolve(null); + expect(await otherLookup).toBeNull(); + client.clear(); +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/cacheResumedSuccessor.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/cacheResumedSuccessor.ts new file mode 100644 index 00000000000..1f897f99d8a --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/cacheResumedSuccessor.ts @@ -0,0 +1,11 @@ +import type { QueryClient, QueryKey } from "@tanstack/react-query"; + +export async function cacheResumedSuccessor( + queryClient: QueryClient, + queryKey: QueryKey, + successor: { terminalId: string; label: string }, +): Promise { + // A pre-resume lookup can still return null after the mutation succeeds. + await queryClient.cancelQueries({ queryKey, exact: true }); + queryClient.setQueryData(queryKey, successor); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/index.ts new file mode 100644 index 00000000000..433a2112825 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/index.ts @@ -0,0 +1 @@ +export { ResumeAccountButton } from "./ResumeAccountButton"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/resumeWithSuccessorRecovery.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/resumeWithSuccessorRecovery.test.ts new file mode 100644 index 00000000000..403c1ff5410 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/resumeWithSuccessorRecovery.test.ts @@ -0,0 +1,87 @@ +import { expect, test } from "bun:test"; +import { QueryClient } from "@tanstack/react-query"; +import { TRPCClientError } from "@trpc/client"; +import { resumeWithSuccessorRecovery } from "./resumeWithSuccessorRecovery"; + +test("a lost response follows the durable successor without retrying the resume", async () => { + const client = new QueryClient(); + const key = ["terminal-resumed-successor", "workspace", "connected-source"]; + const successor = { terminalId: "durable-target", label: "Claude" }; + let attempts = 0; + let lookups = 0; + try { + await resumeWithSuccessorRecovery( + client, + key, + async () => { + attempts++; + throw TRPCClientError.from(new TypeError("Failed to fetch")); + }, + async () => { + lookups++; + return successor; + }, + ); + expect(client.getQueryData(key)).toEqual(successor); + expect(attempts).toBe(1); + expect(lookups).toBe(1); + } finally { + client.clear(); + } +}); + +test("a failed resume without an authoritative successor keeps its original error", async () => { + const client = new QueryClient(); + const key = ["terminal-resumed-successor", "workspace", "source"]; + const failure = new Error("history changed"); + try { + await expect( + resumeWithSuccessorRecovery( + client, + key, + async () => { + throw failure; + }, + async () => null, + ), + ).rejects.toBe(failure); + expect(client.getQueryData(key)).toBeUndefined(); + } finally { + client.clear(); + } +}); + +test("a definitive account rejection cannot recover another account's successor", async () => { + const client = new QueryClient(); + const key = ["terminal-resumed-successor", "workspace", "source"]; + const failure = TRPCClientError.from({ + error: { + message: "Source revision changed while selecting account B", + code: -32009, + data: { code: "CONFLICT" }, + }, + }); + let lookups = 0; + try { + await expect( + resumeWithSuccessorRecovery( + client, + key, + async () => { + throw failure; + }, + async () => { + lookups++; + return { + terminalId: "account-A-successor", + label: "Claude — account A", + }; + }, + ), + ).rejects.toBe(failure); + expect(lookups).toBe(0); + expect(client.getQueryData(key)).toBeUndefined(); + } finally { + client.clear(); + } +}); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/resumeWithSuccessorRecovery.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/resumeWithSuccessorRecovery.ts new file mode 100644 index 00000000000..1ca79834bb6 --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/components/TerminalPaneHeaderExtras/components/ResumeAccountButton/resumeWithSuccessorRecovery.ts @@ -0,0 +1,26 @@ +import type { QueryClient, QueryKey } from "@tanstack/react-query"; +import { TRPCClientError } from "@trpc/client"; +import { cacheResumedSuccessor } from "./cacheResumedSuccessor"; + +interface Successor { + terminalId: string; + label: string; +} + +export async function resumeWithSuccessorRecovery( + queryClient: QueryClient, + queryKey: QueryKey, + resume: () => Promise, + lookupSuccessor: () => Promise, +): Promise { + let successor: Successor; + try { + successor = await resume(); + } catch (error) { + if (!(error instanceof TRPCClientError) || error.shape != null) throw error; + const saved = await lookupSuccessor().catch(() => null); + if (!saved) throw error; + successor = saved; + } + await cacheResumedSuccessor(queryClient, queryKey, successor); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/hooks/useUndoableChatClose/useUndoableChatClose.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/hooks/useUndoableChatClose/useUndoableChatClose.tsx index ec5790c5e8a..b99e187a209 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/hooks/useUndoableChatClose/useUndoableChatClose.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/hooks/usePaneRegistry/hooks/useUndoableChatClose/useUndoableChatClose.tsx @@ -14,6 +14,8 @@ import { readPendingChatStops, removePendingChatStop, } from "../../../../utils/pendingChatStops"; +import { accountChatDraftKey } from "../../components/ChatPane/components/AcpChatPane/utils/accountPaneState"; +import { discardComposerDraft } from "../../components/ChatSession/components/Composer/hooks/useComposerDraft/useComposerDraft"; import { useChatWiring } from "../../components/ChatSession/hooks/useSessionClient"; import { useChatSubagentStore } from "../../stores/chatSubagentStore"; import { ChatClosedToast } from "./components/ChatClosedToast"; @@ -117,6 +119,9 @@ export function useUndoableChatClose({ else state.addTab({ panes: [chat.pane] }); }, stop: (chat) => { + const data = chat.pane.data as ChatPaneData; + if (data.accountBound || data.accountLaunch) + discardComposerDraft(accountChatDraftKey(data)); stopSession(chat.sessionId); useChatSubagentStore .getState() @@ -138,7 +143,12 @@ export function useUndoableChatClose({ (pane) => { const data = pane.data as ChatPaneData; const { sessionId } = data; - if (!sessionId || isChatSessionClosed(sessionId)) return; + if (!sessionId) { + if (data.accountBound || data.accountLaunch) + discardComposerDraft(accountChatDraftKey(data)); + return; + } + if (isChatSessionClosed(sessionId)) return; const index = previousTabs.current.findIndex( (tab) => tab.panes[pane.id] !== undefined, ); diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/page.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/page.tsx index ed74522fa6c..636abe4fecc 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/page.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/page.tsx @@ -4,7 +4,7 @@ import { cn } from "@superset/ui/utils"; import { workspaceTrpc } from "@superset/workspace-client"; import { createFileRoute } from "@tanstack/react-router"; import { useFeatureFlagEnabled } from "posthog-js/react"; -import { useCallback, useMemo, useRef } from "react"; +import { useCallback, useMemo, useRef, useState } from "react"; import { useQuickOpenStore } from "renderer/commandPalette/ui/QuickOpen/quickOpenStore"; import { useWorkspaceHostTarget } from "renderer/hooks/host-service/useWorkspaceHostUrl"; import { useAcpChatEnabled } from "renderer/hooks/useAcpChatEnabled"; @@ -25,6 +25,7 @@ import { useRightPaneAreaEnabled } from "renderer/stores/right-pane-area"; import { getV2NotificationSourcesForTab } from "renderer/stores/v2-notifications"; import { useStore } from "zustand"; import { useWorkspace } from "../providers/WorkspaceProvider"; +import { AccountTerminalDialog } from "./components/AccountTerminalDialog"; import { AddTabMenu } from "./components/AddTabMenu"; import { ChangesControl } from "./components/ChangesControl"; import { CloudWorkspaceTabBarControls } from "./components/CloudWorkspaceTabBarControls"; @@ -273,8 +274,11 @@ function V2WorkspaceContent() { close: closeRightSidebar, }); const launcher = useV2TerminalLauncher(); + const [accountTerminalOpen, setAccountTerminalOpen] = useState(false); + const accountTerminalReturnFocus = useRef(null); const { createNewAgentSession, + createAccountTerminal, openAgentChat, openNewChat, focusAgentTerminal, @@ -697,6 +701,14 @@ function V2WorkspaceContent() { { + accountTerminalReturnFocus.current = returnFocus; + setAccountTerminalOpen(true); + } + } onAddChat={onAddChat} onAddBrowser={ isRightPaneAreaEnabled ? undefined : addBrowserTab @@ -776,6 +788,14 @@ function V2WorkspaceContent() { recentlyViewedFiles={recentFiles} openFilePaths={openFilePaths} /> + {accountTerminalOpen && ( + setAccountTerminalOpen(false)} + onLaunch={createAccountTerminal} + returnFocus={accountTerminalReturnFocus.current} + /> + )} ); } diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/types.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/types.ts index 4ca6fc915c5..05921ff4d41 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/types.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/v2-workspace/$workspaceId/types.ts @@ -1,4 +1,7 @@ -import type { UserContent } from "@superset/chat/protocol"; +import type { + CreateAccountSessionInput, + UserContent, +} from "@superset/chat/protocol"; import type { WorkspaceStore } from "@superset/panes"; import type { AgentIdentityId } from "@superset/shared/agent-catalog"; import type { StoreApi } from "zustand/vanilla"; @@ -80,6 +83,12 @@ export interface PagePaneData { } export interface ChatPaneData { + accountBound?: true; + accountDraftId?: string; + accountLaunch?: { + hostUrl: string; + request: CreateAccountSessionInput; + }; terminalId: string; sessionId: string | null; agent?: { diff --git a/apps/desktop/src/shared/quota-freshness.test.ts b/apps/desktop/src/shared/quota-freshness.test.ts new file mode 100644 index 00000000000..5ce98ef306c --- /dev/null +++ b/apps/desktop/src/shared/quota-freshness.test.ts @@ -0,0 +1,92 @@ +import { expect, test } from "bun:test"; +import { + QUOTA_NATIVE_FRESHNESS_MS, + QUOTA_PROVIDER_FRESHNESS_MS, + quotaObservationFresh, + quotaObservationFreshnessMs, +} from "./quota-freshness"; + +const now = Date.parse("2026-10-25T12:00:00Z"); + +test("provider observations remain current across a fifteen-minute collection interval", () => { + for (const source of [undefined, "provider"]) { + expect(quotaObservationFreshnessMs(source)).toBe( + QUOTA_PROVIDER_FRESHNESS_MS, + ); + for (const minutes of [0, 6, 9, 14, 15, 16]) + expect( + quotaObservationFresh( + { source }, + new Date(now - minutes * 60_000), + now, + ), + ).toBe(true); + expect( + quotaObservationFresh( + { source }, + new Date(now - QUOTA_PROVIDER_FRESHNESS_MS - 1), + now, + ), + ).toBe(false); + } +}); + +test("each native observation has its own six-minute lifetime", () => { + for (const source of ["claude_statusline", "claude_sdk"]) { + expect(quotaObservationFreshnessMs(source)).toBe(QUOTA_NATIVE_FRESHNESS_MS); + expect( + quotaObservationFresh( + { source, observedAt: new Date(now - QUOTA_NATIVE_FRESHNESS_MS) }, + new Date(now - 60 * 60_000), + now, + ), + ).toBe(true); + expect( + quotaObservationFresh( + { source, observedAt: new Date(now - QUOTA_NATIVE_FRESHNESS_MS - 1) }, + new Date(now), + now, + ), + ).toBe(false); + } +}); + +test("explicit dates take precedence without changing either independent observation", () => { + const http = new Date(now - 60 * 60_000); + const native = { + source: "claude_statusline", + observedAt: new Date(now - 60_000), + }; + const oldProvider = { + source: "provider", + observedAt: new Date(now - 17 * 60_000), + }; + expect(quotaObservationFresh(native, http, now)).toBe(true); + expect(quotaObservationFresh(oldProvider, native.observedAt, now)).toBe( + false, + ); + expect(http.getTime()).toBe(now - 60 * 60_000); + expect(native.observedAt.getTime()).toBe(now - 60_000); +}); + +test("unknown sources, invalid timestamps and future dates never become current", () => { + for (const source of [null, "unknown", "claude_future"]) + expect( + quotaObservationFresh( + { source, observedAt: new Date(now) }, + new Date(now), + now, + ), + ).toBe(false); + for (const observedAt of ["invalid", new Date(Number.NaN), new Date(now + 1)]) + expect( + quotaObservationFresh( + { source: "provider", observedAt }, + new Date(now), + now, + ), + ).toBe(false); + expect(quotaObservationFresh({}, undefined, now)).toBe(false); + expect(quotaObservationFresh({}, null, now)).toBe(false); + expect(quotaObservationFresh({}, new Date(now), Number.NaN)).toBe(false); +}); diff --git a/apps/desktop/src/shared/quota-freshness.ts b/apps/desktop/src/shared/quota-freshness.ts new file mode 100644 index 00000000000..6e9a91c448b --- /dev/null +++ b/apps/desktop/src/shared/quota-freshness.ts @@ -0,0 +1,32 @@ +export const QUOTA_PROVIDER_FRESHNESS_MS = 16 * 60_000; +export const QUOTA_NATIVE_FRESHNESS_MS = 6 * 60_000; + +/** Missing source is a legacy provider response; an unknown explicit source is not proof. */ +export function quotaObservationFreshnessMs( + source?: string | null, +): number | null { + if (source === undefined || source === "provider") + return QUOTA_PROVIDER_FRESHNESS_MS; + if (source === "claude_statusline" || source === "claude_sdk") + return QUOTA_NATIVE_FRESHNESS_MS; + return null; +} + +/** Each observation keeps its own age. An unrelated HTTP/native sample cannot renew it. */ +export function quotaObservationFresh( + window: { source?: string | null; observedAt?: Date | string | null }, + fallbackFetchedAt: Date | string | null | undefined, + now = Date.now(), +): boolean { + const limit = quotaObservationFreshnessMs(window.source); + const observedAt = window.observedAt ?? fallbackFetchedAt; + if ( + limit === null || + observedAt === null || + observedAt === undefined || + !(typeof observedAt === "string" || observedAt instanceof Date) + ) + return false; + const age = now - new Date(observedAt).getTime(); + return Number.isFinite(age) && age >= 0 && age <= limit; +} diff --git a/bun.lock b/bun.lock index 7886640ddd4..88f34b01dca 100644 --- a/bun.lock +++ b/bun.lock @@ -984,6 +984,7 @@ "@superset/agent-setup": "workspace:*", "@superset/chat": "workspace:*", "@superset/chat-runtime": "workspace:*", + "@superset/macos-process-metrics": "workspace:*", "@superset/port-scanner": "workspace:*", "@superset/pty-daemon": "workspace:*", "@superset/shared": "workspace:*", @@ -1004,6 +1005,7 @@ "pi-acp": "0.0.34", "semver": "7.7.4", "simple-git": "4.0.2", + "smol-toml": "1.9.1", "superjson": "2.2.6", "tree-kill": "1.2.2", "zod": "4.6.5", diff --git a/docs/environment-variables.md b/docs/environment-variables.md index b551334e2e3..22d1cd086d9 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -93,12 +93,18 @@ or the value arrives empty. ## Launcher-owned runtime values +`SUPERSET_NATIVE_CLAUDE_USAGE` is a local host opt-in for passive Claude subscription measurements. Only `1` enables it; the default is off. The host passes it through an explicitly selected account's new terminal command and consumes ACP metadata through that account's immutable launch context. It does not retrofit running terminals or change provider settings. This runtime preference is not a cloud API secret and does not belong in shared environment templates or deployment workflows. + `SUPERSET_HOST_INSTALL_SOURCE` is set by the desktop coordinator (`desktop`) or standalone CLI spawner (`cli`) on the host child process. A checkout may set `dev`; absent/unrecognized values report `unknown`. This is install provenance, not an API deployment setting: do not put it in shared `.env` templates or deployment secrets. The host ignores login-shell values for this key. In-place updates additionally require a standalone entrypoint and a valid install layout. `SUPERSET_AGENT_LAUNCH_ID` is set by the outer agent wrapper to a process-and-start-time identifier. Hook children inherit it so a new launch in the same terminal cannot inherit the previous login attribution. It is runtime metadata, not a deployment secret or user setting; it does not belong in `.env` templates or deploy workflows. +`SUPERSET_PINNED_ACCOUNT` is set only on an explicitly account-selected terminal agent command. It names `CLAUDE_CONFIG_DIR` or `CODEX_HOME` and tells the matching wrapper to preserve that launch's selection instead of rereading the global default pointer. It is scoped to the launched process and its children, not exported into the surrounding shell. It is not authentication proof or a deployment setting. + `SUPERSET_ACCOUNT_ATTRIBUTION_TOKEN` is issued by the host for each new terminal and authorizes only that terminal’s login-attribution hook metadata. It is not the host authentication token. Tokens expire when the host process restarts; open a new terminal to restore verified login attribution. The host injects it at PTY creation, so it does not belong in deployment configuration. `SUPERSET_HOST_AUTO_UPDATE` is a standalone host runtime preference, set to `true` by `superset start --auto-update` and `false` otherwise. Direct service launchers may set it explicitly. It defaults to `false`, is excluded from login-shell imports, and is inherited by update/rollback successors. Like install provenance, it does not belong in deployment secrets or shared environment templates. `SUPERSET_SANDBOX_AGENT_AUTOMATION_RUN_ID` is an internal first-boot variable. Cloud automation dispatch sets it when it starts a workspace, and host-service sends it back with the launch report so the run is correlated without guessing which row created the box. A manual cloud launch must not set it. It is not a deployment secret: do not add it to `.env` templates, the API env schema, or deploy workflows. + +`SUPERSET_NATIVE_CLAUDE_OWNED_LAUNCH` is a per-command configuration marker set only after the host captures a selected Claude launch's immutable credential generation. It permits the passive statusline overlay on a fresh exact resume. It is not quota or identity authority: the consumer still requires the captured launch permit, pinned account and current generation proof. Do not set it globally, in deployment templates or shared shell defaults. It never authorizes attaching to or modifying an existing provider. diff --git a/docs/native-claude-usage.md b/docs/native-claude-usage.md new file mode 100644 index 00000000000..654b2dfb3d5 --- /dev/null +++ b/docs/native-claude-usage.md @@ -0,0 +1,45 @@ +# Passive Claude subscription usage + +The host can reuse rate-limit measurements already returned to an explicitly selected Claude account. This is an optional producer for the shared usage tracker, not an additional provider poller. + +## Enable + +Start the host with `SUPERSET_NATIVE_CLAUDE_USAGE=1`, then select a Claude subscription account through Superset's account picker. The default is off. Turning this on does not edit any provider profile, settings file, login or account default. + +For a new terminal launch, Superset adds a per-process `--settings` status-line command. It preserves an existing command's stdin, stdout, stderr, exit status and status-line options. Claude documents that a custom status line hides some built-in footer keyboard hints. Disable the host opt-in to keep the normal footer on subsequent launches. + +Existing chats continue running. They receive the terminal hook only on a later natural **new** launch. Attach, resume, continue, fork, print/output-format and managed or ambiguous settings paths keep the original command unchanged. No configuration flag is added to a background attachment: Claude's attach behavior changes when configuration flags are supplied. + +The selected `claude-acp` harness also consumes the official adapter's `_claude/rateLimit` usage metadata. It uses the existing immutable account launch context and does not add status-line settings. The older accountless `claude-code` SDK harness remains on the shared HTTP tracker. + +## Identity and age + +Before a selected process starts, the host captures an opaque generation derived from its current credential, canonical profile and immutable public account identity. The native session and launch are bound separately. Lifecycle hooks require the terminal's existing attribution token and the exact live terminal, workspace, launch, native session and pinned account. A reported path, email or payload account name cannot authorize usage. + +The cached provider proof must independently authenticate the same principal and organization under that exact credential generation. Looking up that proof does not issue HTTP requests. With a cold proof cache, native counters and measurements remain quarantined. A later natural status-line frame or ACP event can promote them after the proof warms, preserving their original measurement dates and duplicate markers. It never requires the user to exit a chat just to warm the proof. + +The first status-line frame is a baseline. A rise in `cost.total_api_duration_ms` is required before supplied windows become observations. Timer, startup and configuration replays keep the old date. ACP replay and foreign/subagent events cannot advance the response counter. A restored SDK rate-limit event alone is not a new measurement. Each supplied window retains its own `observedAt` and source; a missing window is not fabricated. Lower utilization from a late event in the same reset epoch cannot replace a newer reading. + +The native payload does not expose a server observation timestamp. The host stamps each receipt synchronously before queuing or asynchronous identity validation. Proven API progress retains that original receipt as `observedAt` through caching, host restart and proof promotion. Missing, future or more than six-minute-old receipts are refused. Native display and HTTP-deferral eligibility expire together after six minutes; provider and financial readings keep their separate original dates and policies. An idle render or delayed validation cannot make a reading fresh. + +## Bounds and fallback + +- Claude currently documents the terminal `rate_limits` fields for Pro and Max. Windows can be independently absent. Team accounts and unsupported native versions continue using the common HTTP tracker. +- Only `five_hour` and `seven_day` subscription windows are accepted. Native spend limits, wallet balances, purchased credits, reset credits, plan names and model-specific limits are never inferred. +- Credential rotation, sign-out, registration changes, expired proof or conflicting organizations quarantine the feed. The existing HTTP tracker remains available. A running process cannot be silently rebound to a different credential generation. +- A missing readable credential at prelaunch, or a host crash before the first authenticated native-session capture, cannot acquire authority from a later unbound hook. It falls back to HTTP until a later natural new launch. +- Reconnecting an already-running background worker uses HTTP fallback. Its original hook environment cannot authorize a successor terminal. Late predecessor samples are ignored; previously recorded account measurements retain their original dates only. Pre-feature workers are not claimed to have a native hook. +- The status-line bridge has a 500 ms total local transport deadline, at most four loopback candidates, a bounded response and private bounded duplicate markers. Failed/cold captures retry locally after a short duplicate cooldown. No provider request is made by this path. +- Private observation storage contains only digests, bounded quota windows, counters and dates. It excludes credentials, emails, paths, prompts and transcript text. Observation files are written atomically with owner-only permissions and refuse unsafe symlink destinations. + +## Verification + +Synthetic regression tests cover replay age, host restart, cold-proof promotion, exact credential/profile/principal binding, rotation, foreign sessions, adoption fallback, partial fields and private storage. Real Node subprocess tests exercise the status-line wrapper, original-command preservation, loopback transport, timeout bounds and skipped attach/configuration paths. ACP fake-transport tests exercise real adapter notification handling, response counters and replay refusal. These tests do not launch a provider or change a real profile. + +Live qualification, if requested separately, must use one owned disposable chat with an explicit account, an actual native API response and readback through the common tracker. A synthetic payload is not proof of actual provider emission. + +Sources checked against current documentation and the pinned adapter: + +- [Claude status-line fields and update lifecycle](https://code.claude.com/docs/en/statusline) +- [Claude sessions and background attachment](https://code.claude.com/docs/en/sessions) +- [Official Claude ACP adapter v0.85.0 rate-limit forwarding](https://github.com/agentclientprotocol/claude-agent-acp/blob/v0.85.0/src/acp-agent.ts) diff --git a/packages/agent-setup/src/agent-wrappers-claude-codex-opencode.ts b/packages/agent-setup/src/agent-wrappers-claude-codex-opencode.ts index 218c9c321d8..d06282780be 100644 --- a/packages/agent-setup/src/agent-wrappers-claude-codex-opencode.ts +++ b/packages/agent-setup/src/agent-wrappers-claude-codex-opencode.ts @@ -11,6 +11,10 @@ import { writeFileIfChanged, } from "./agent-wrappers-common"; import { getArtifactGuardScriptPath } from "./artifact-guard-hook"; +import { + claudeUsageStatuslineLaunch, + createClaudeUsageStatuslineScript, +} from "./claude-usage-statusline"; import { getTemplatePath } from "./config"; import { buildNestedDesiredEntries, @@ -163,8 +167,8 @@ export function removeClaudeManagedHooks(): void { * on a non-default account would lose lifecycle/status hooks — Claude reads * settings exclusively from the active config dir. */ -export function ensureClaudeManagedHooksAt(configDir: string): void { - ensureManagedJsonHooks({ +export function ensureClaudeManagedHooksAt(configDir: string): boolean { + return ensureManagedJsonHooks({ ...claudeHooksSpec(getNotifyScriptPath()), getFilePath: () => path.join(configDir, "settings.json"), }); @@ -266,8 +270,8 @@ export function removeCodexManagedHooks(): void { * Merges Superset hooks into `/hooks.json` for a secondary Codex * home (CODEX_HOME account) — same rationale as ensureClaudeManagedHooksAt. */ -export function ensureCodexManagedHooksAt(codexHome: string): void { - ensureManagedJsonHooks({ +export function ensureCodexManagedHooksAt(codexHome: string): boolean { + return ensureManagedJsonHooks({ ...codexHooksSpec(getNotifyScriptPath()), getFilePath: () => path.join(codexHome, "hooks.json"), }); @@ -296,12 +300,15 @@ export function getOpenCodePluginContent(notifyPath: string): string { * in ~/.claude/settings.json (createClaudeSettingsJson). */ export function createClaudeWrapper(): void { - const script = buildWrapperScript("claude", `exec "$REAL_BIN" "$@"`, { + createClaudeUsageStatuslineScript(); + const script = buildWrapperScript("claude", claudeUsageStatuslineLaunch(), { agentId: "claude", - beforeLaunch: buildDefaultAccountResolver( - "CLAUDE_CONFIG_DIR", - "default-claude-config-dir", - ), + beforeLaunch: + `_superset_capture_usage=""\n[ -z "$SUPERSET_AGENT_ID" ] && [ "$SUPERSET_NATIVE_CLAUDE_USAGE" = "1" ] && [ "$SUPERSET_PINNED_ACCOUNT" = "CLAUDE_CONFIG_DIR" ] && _superset_capture_usage="1"\n` + + buildDefaultAccountResolver( + "CLAUDE_CONFIG_DIR", + "default-claude-config-dir", + ), }); createWrapper("claude", script); } diff --git a/packages/agent-setup/src/agent-wrappers-common.ts b/packages/agent-setup/src/agent-wrappers-common.ts index 4d4d0d1e8ae..cbe6b629808 100644 --- a/packages/agent-setup/src/agent-wrappers-common.ts +++ b/packages/agent-setup/src/agent-wrappers-common.ts @@ -156,6 +156,7 @@ export function buildDefaultAccountResolver( : `unset ${envVar} unset SUPERSET_DEFAULT_${envVar}`; return `if [ -n "$SUPERSET_TERMINAL_ID" ] && [ -n "$SUPERSET_HOME_DIR" ] \\ + && [ "$SUPERSET_PINNED_ACCOUNT" != "${envVar}" ] \\ && { [ -z "\${${envVar}}" ] || [ "\${${envVar}}" = "\${SUPERSET_DEFAULT_${envVar}}" ]; } \\ && [ -f ${pointer} ]; then superset_default_account="$(cat ${pointer} 2>/dev/null)" diff --git a/packages/agent-setup/src/agent-wrappers.test.ts b/packages/agent-setup/src/agent-wrappers.test.ts index a380745eaa1..12c7258d088 100644 --- a/packages/agent-setup/src/agent-wrappers.test.ts +++ b/packages/agent-setup/src/agent-wrappers.test.ts @@ -857,6 +857,8 @@ exit 0 SUPERSET_DEBUG_HOOKS: "1", SUPERSET_HOOK_DEBUG_LOG: debugLogPath, SUPERSET_TERMINAL_ID: "terminal-1", + // The generic delayed launch report is tested separately. + SUPERSET_AGENT_ID: "codex", }, encoding: "utf-8", }); @@ -898,6 +900,8 @@ exit 0 NOTIFY_CAPTURE_PATH: notifyCapturePath, PATH: `${TEST_BIN_DIR}:${realBinDir}:${process.env.PATH || ""}`, SUPERSET_TERMINAL_ID: "terminal-1", + // The generic delayed launch report is tested separately. + SUPERSET_AGENT_ID: "codex", }, encoding: "utf-8", }); diff --git a/packages/agent-setup/src/claude-usage-statusline.test.ts b/packages/agent-setup/src/claude-usage-statusline.test.ts new file mode 100644 index 00000000000..2417fff8c0f --- /dev/null +++ b/packages/agent-setup/src/claude-usage-statusline.test.ts @@ -0,0 +1,492 @@ +import { afterEach, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) + rmSync(directory, { recursive: true, force: true }); +}); +const bridge = fileURLToPath( + new URL("../templates/claude-usage-statusline.cjs", import.meta.url), +); +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "claude-native-bridge-")); + directories.push(dir); + const home = join(dir, "home"); + const cwd = join(dir, "project"); + const config = join(home, ".claude"); + mkdirSync(config, { recursive: true }); + mkdirSync(cwd); + const env = { + ...process.env, + HOME: home, + SUPERSET_HOME_DIR: join(home, ".superset"), + CLAUDE_CONFIG_DIR: config, + SUPERSET_AGENT_ID: "claude", + SUPERSET_NATIVE_CLAUDE_USAGE: "1", + SUPERSET_PINNED_ACCOUNT: "CLAUDE_CONFIG_DIR", + SUPERSET_TERMINAL_ID: "terminal", + SUPERSET_AGENT_LAUNCH_ID: "launch", + SUPERSET_ACCOUNT_ATTRIBUTION_TOKEN: "fixture-attribution", + }; + return { dir, cwd, config, env }; +} +test("real Node launch overlay preserves existing statusline options and leaves every settings file untouched", () => { + const f = fixture(); + const settings = JSON.stringify({ + statusLine: { + type: "command", + command: "printf 'custom output\\n'", + padding: 3, + refreshInterval: 9, + hideVimModeIndicator: true, + }, + permissions: { defaultMode: "default" }, + }); + writeFileSync(join(f.config, "settings.json"), settings); + const child = spawnSync("node", [bridge, "--prepare"], { + cwd: f.cwd, + env: f.env, + encoding: "utf8", + }); + expect(child.status).toBe(0); + const overlay = JSON.parse(child.stdout); + expect(overlay.statusLine).toMatchObject({ + padding: 3, + refreshInterval: 9, + hideVimModeIndicator: true, + }); + expect(overlay.statusLine.command).toContain("--status"); + expect(Object.keys(overlay)).toEqual(["statusLine"]); + expect(readFileSync(join(f.config, "settings.json"), "utf8")).toBe(settings); + for (const args of [ + ["--settings", "{}"], + ["--setting-sources=user"], + ["--print"], + ["attach", "session"], + ["--resume", "session"], + ["-r", "session"], + ["--continue"], + ["-c"], + ["--fork-session"], + ["--output-format", "stream-json"], + ]) { + expect( + spawnSync("node", [bridge, "--prepare", ...args], { + cwd: f.cwd, + env: f.env, + encoding: "utf8", + }).stdout, + ).toBe(""); + } +}); +test("real Node bridge preserves user stdin and output, sends only bounded native fields to the owning host", async () => { + const f = fixture(); + const requests: unknown[] = []; + const host = Bun.serve({ + port: 0, + async fetch(request) { + requests.push(await request.json()); + return Response.json({ result: { data: { json: { ignored: false } } } }); + }, + }); + try { + writeFileSync( + join(f.config, "settings.json"), + JSON.stringify({ + statusLine: { + type: "command", + command: "printf 'unchanged output\\n'; cat", + }, + }), + ); + const prepared = spawnSync("node", [bridge, "--prepare"], { + cwd: f.cwd, + env: f.env, + encoding: "utf8", + }); + const overlay = JSON.parse(prepared.stdout); + const input = JSON.stringify({ + session_id: "session", + cost: { total_api_duration_ms: 123, total_cost_usd: 2 }, + rate_limits: { + five_hour: { used_percentage: 25, resets_at: 1_800_000_600 }, + spend_limit: { used_usd: 999 }, + }, + transcript_path: "/never-forward", + account: { email: "never-forward@example.test" }, + other: "never-forward", + }); + const proc = Bun.spawn(["sh", "-c", overlay.statusLine.command], { + cwd: f.cwd, + env: { + ...f.env, + SUPERSET_HOST_AGENT_HOOK_URL: `http://127.0.0.1:${host.port}/trpc/notifications.hook`, + }, + stdin: Buffer.from(input), + stdout: "pipe", + stderr: "pipe", + }); + const [output, code, errors] = await Promise.all([ + new Response(proc.stdout).text(), + proc.exited, + new Response(proc.stderr).text(), + ]); + expect(code).toBe(0); + expect(errors).toBe(""); + expect(output).toBe(`unchanged output\n${input}`); + const repeated = Bun.spawn(["sh", "-c", overlay.statusLine.command], { + cwd: f.cwd, + env: { + ...f.env, + SUPERSET_HOST_AGENT_HOOK_URL: `http://127.0.0.1:${host.port}/trpc/notifications.hook`, + }, + stdin: Buffer.from(input), + stdout: "pipe", + stderr: "pipe", + }); + expect(await new Response(repeated.stdout).text()).toBe( + `unchanged output\n${input}`, + ); + expect(await repeated.exited).toBe(0); + expect(requests).toHaveLength(1); + expect(requests[0]).toEqual({ + json: { + terminalId: "terminal", + launchId: "launch", + attributionToken: "fixture-attribution", + agent: { agentId: "claude", sessionId: "session" }, + nativeClaudeUsage: { + session_id: "session", + cost: { total_api_duration_ms: 123 }, + rate_limits: { + five_hour: { used_percentage: 25, resets_at: 1_800_000_600 }, + }, + }, + }, + }); + } finally { + host.stop(true); + } +}); +test("ambiguous parent settings and nested working folders leave the native launch unchanged", () => { + const f = fixture(); + mkdirSync(join(f.dir, ".claude")); + writeFileSync( + join(f.dir, ".claude", "settings.json"), + JSON.stringify({ + statusLine: { type: "command", command: "printf parent" }, + }), + ); + expect( + spawnSync("node", [bridge, "--prepare"], { + cwd: f.cwd, + env: f.env, + encoding: "utf8", + }).stdout, + ).toBe(""); +}); + +test("statusline feed is opt-in and requires an explicit account pin", () => { + const f = fixture(); + for (const override of [ + { SUPERSET_NATIVE_CLAUDE_USAGE: "" }, + { SUPERSET_PINNED_ACCOUNT: "" }, + ]) { + const child = spawnSync("node", [bridge, "--prepare"], { + cwd: f.cwd, + env: { ...f.env, ...override }, + encoding: "utf8", + }); + expect(child.status).toBe(0); + expect(child.stdout).toBe(""); + } +}); + +test("capture transport has an absolute deadline even when a local host trickles bytes", async () => { + const f = fixture(); + let stopped = false; + const host = Bun.serve({ + port: 0, + fetch() { + return new Response( + new ReadableStream({ + start(controller) { + const timer = setInterval(() => { + if (stopped) { + clearInterval(timer); + return; + } + try { + controller.enqueue(new TextEncoder().encode(" ")); + } catch { + clearInterval(timer); + } + }, 25); + }, + }), + ); + }, + }); + try { + const saved = Buffer.from( + JSON.stringify({ type: "command", command: "printf 'kept output'" }), + ).toString("base64url"); + const started = Date.now(); + const proc = Bun.spawn(["node", bridge, "--status", saved], { + cwd: f.cwd, + env: { + ...f.env, + SUPERSET_HOST_AGENT_HOOK_URL: `http://127.0.0.1:${host.port}/trpc/notifications.hook`, + }, + stdin: Buffer.from( + JSON.stringify({ + session_id: "owned", + cost: { total_api_duration_ms: 0 }, + }), + ), + stdout: "pipe", + stderr: "pipe", + }); + expect(await new Response(proc.stdout).text()).toBe("kept output"); + expect(await proc.exited).toBe(0); + expect(Date.now() - started).toBeLessThan(2000); + } finally { + stopped = true; + await host.stop(true); + } +}); + +test("a user's statusline exit code and output survive a rejected or unavailable capture", () => { + const f = fixture(); + const saved = Buffer.from( + JSON.stringify({ type: "command", command: "printf 'retained'; exit 7" }), + ).toString("base64url"); + const child = spawnSync("node", [bridge, "--status", saved], { + cwd: f.cwd, + env: { + ...f.env, + SUPERSET_HOST_AGENT_HOOK_URL: + "https://public.example.test/trpc/notifications.hook", + }, + input: JSON.stringify({ + session_id: "owned", + cost: { total_api_duration_ms: 0 }, + }), + encoding: "utf8", + }); + expect(child.status).toBe(7); + expect(child.stdout).toBe("retained"); +}); + +test("native collection reaches the host while a custom statusline waits for its marker", async () => { + const f = fixture(); + const marker = join(f.dir, "collector-received"); + const custom = join(f.dir, "original.cjs"); + const input = Buffer.from( + JSON.stringify({ + session_id: "owned", + cost: { total_api_duration_ms: 123 }, + rate_limits: { + five_hour: { used_percentage: 25, resets_at: 1_800_000_600 }, + }, + }), + ); + const outputPrefix = Buffer.from([0, 255, 10]); + const expectedErrors = Buffer.from([101, 114, 114, 0, 254]); + writeFileSync( + custom, + ` +const fs = require("node:fs"); +const path = require("node:path"); +const marker = ${JSON.stringify(marker)}; +const chunks = []; +process.stdin.on("data", chunk => chunks.push(chunk)); +process.stdin.on("end", () => { + let watcher; + let timer; + let finished = false; + const finish = () => { + if (finished || !fs.existsSync(marker)) return; + finished = true; + clearTimeout(timer); + watcher?.close(); + process.stdout.write(Buffer.from([0, 255, 10])); + process.stdout.write(Buffer.concat(chunks)); + process.stderr.write(Buffer.from([101, 114, 114, 0, 254])); + process.exitCode = 7; + }; + watcher = fs.watch(path.dirname(marker), finish); + timer = setTimeout(() => { + watcher.close(); + process.stderr.write("collector never reached the host"); + process.exitCode = 91; + }, 1500); + finish(); +}); +`, + ); + let requests = 0; + const host = Bun.serve({ + port: 0, + async fetch(request) { + const body = (await request.json()) as { + json: { nativeClaudeUsage: { session_id: string } }; + }; + expect(body.json.nativeClaudeUsage.session_id).toBe("owned"); + requests++; + writeFileSync(marker, "received"); + return Response.json({ result: { data: { json: { ignored: false } } } }); + }, + }); + try { + const saved = Buffer.from( + JSON.stringify({ + type: "command", + command: `node '${custom.replaceAll("'", "'\\''")}'`, + padding: 3, + }), + ).toString("base64url"); + const proc = Bun.spawn(["node", bridge, "--status", saved], { + cwd: f.cwd, + env: { + ...f.env, + SUPERSET_HOST_AGENT_HOOK_URL: `http://127.0.0.1:${host.port}/trpc/notifications.hook`, + }, + stdin: input, + stdout: "pipe", + stderr: "pipe", + }); + const [output, errors, code] = await Promise.all([ + new Response(proc.stdout).arrayBuffer(), + new Response(proc.stderr).arrayBuffer(), + proc.exited, + ]); + expect(code).toBe(7); + expect(Buffer.from(output)).toEqual(Buffer.concat([outputPrefix, input])); + expect(Buffer.from(errors)).toEqual(expectedErrors); + expect(requests).toBe(1); + } finally { + await host.stop(true); + } +}); + +test("custom statusline output remains bounded while collection is unavailable", async () => { + const f = fixture(); + const custom = join(f.dir, "large-output.cjs"); + writeFileSync(custom, "process.stdout.write(Buffer.alloc(600 * 1024, 65));"); + const saved = Buffer.from( + JSON.stringify({ + type: "command", + command: `node '${custom.replaceAll("'", "'\\''")}'`, + }), + ).toString("base64url"); + const proc = Bun.spawn(["node", bridge, "--status", saved], { + cwd: f.cwd, + env: { + ...f.env, + SUPERSET_HOST_AGENT_HOOK_URL: + "https://public.example.test/trpc/notifications.hook", + }, + stdin: Buffer.from( + JSON.stringify({ + session_id: "owned", + cost: { total_api_duration_ms: 0 }, + }), + ), + stdout: "pipe", + stderr: "pipe", + }); + const [output, _errors, code] = await Promise.all([ + new Response(proc.stdout).arrayBuffer(), + new Response(proc.stderr).arrayBuffer(), + proc.exited, + ]); + expect(code).toBe(1); + expect(output.byteLength).toBeLessThanOrEqual(512 * 1024); + expect(output.byteLength).toBeGreaterThan(0); +}); + +test("the custom command keeps the combined stdout/stderr buffer ceiling", async () => { + const f = fixture(); + const custom = join(f.dir, "combined-output.cjs"); + writeFileSync( + custom, + "process.stdout.write(Buffer.alloc(300 * 1024, 65)); process.stderr.write(Buffer.alloc(300 * 1024, 66));", + ); + const saved = Buffer.from( + JSON.stringify({ + type: "command", + command: `node '${custom.replaceAll("'", "'\\''")}'`, + }), + ).toString("base64url"); + const proc = Bun.spawn(["node", bridge, "--status", saved], { + cwd: f.cwd, + env: { + ...f.env, + SUPERSET_HOST_AGENT_HOOK_URL: + "https://public.example.test/trpc/notifications.hook", + }, + stdin: Buffer.from( + JSON.stringify({ + session_id: "owned", + cost: { total_api_duration_ms: 0 }, + }), + ), + stdout: "pipe", + stderr: "pipe", + }); + const [output, errors, code] = await Promise.all([ + new Response(proc.stdout).arrayBuffer(), + new Response(proc.stderr).arrayBuffer(), + proc.exited, + ]); + expect(code).toBe(1); + expect(output.byteLength + errors.byteLength).toBeLessThanOrEqual(512 * 1024); + expect(output.byteLength).toBeGreaterThan(0); + expect(errors.byteLength).toBeGreaterThan(0); +}); + +test("only a host-prepared resume marker permits resume capture; attachment and fork clients stay excluded", () => { + const f = fixture(); + for (const args of [ + ["--resume", "owned-session"], + ["-r", "owned-session"], + ["--continue"], + ["-c"], + ]) { + const result = spawnSync("node", [bridge, "--prepare", ...args], { + cwd: f.cwd, + env: { ...f.env, SUPERSET_NATIVE_CLAUDE_OWNED_LAUNCH: "1" }, + encoding: "utf8", + }); + expect(result.status).toBe(0); + expect(JSON.parse(result.stdout).statusLine.command).toContain("--status"); + } + for (const args of [ + ["attach", "owned-session"], + ["resume", "owned-session"], + ["agents"], + ["sessions"], + ["background"], + ["--fork-session"], + ["--settings", "{}"], + ]) { + const result = spawnSync("node", [bridge, "--prepare", ...args], { + cwd: f.cwd, + env: { ...f.env, SUPERSET_NATIVE_CLAUDE_OWNED_LAUNCH: "1" }, + encoding: "utf8", + }); + expect(result.stdout).toBe(""); + } +}); diff --git a/packages/agent-setup/src/claude-usage-statusline.ts b/packages/agent-setup/src/claude-usage-statusline.ts new file mode 100644 index 00000000000..404ceb27088 --- /dev/null +++ b/packages/agent-setup/src/claude-usage-statusline.ts @@ -0,0 +1,27 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { getTemplatePath } from "./config"; +import { getHooksDir } from "./paths"; +import { writeFileIfChanged } from "./write-file-if-changed"; + +export const CLAUDE_USAGE_STATUSLINE_SCRIPT = "claude-usage-statusline.cjs"; +export function createClaudeUsageStatuslineScript(): void { + writeFileIfChanged( + join(getHooksDir(), CLAUDE_USAGE_STATUSLINE_SCRIPT), + readFileSync(getTemplatePath(CLAUDE_USAGE_STATUSLINE_SCRIPT), "utf8"), + 0o755, + ); +} +function quote(value: string): string { + return `'${value.replaceAll("'", `'\\''`)}'`; +} +export function claudeUsageStatuslineLaunch(): string { + const script = `"$SUPERSET_HOME_DIR/hooks/${CLAUDE_USAGE_STATUSLINE_SCRIPT}"`; + return `if [ "$_superset_capture_usage" = "1" ] && [ "$SUPERSET_AGENT_ID" = "claude" ] && [ -n "$SUPERSET_HOME_DIR" ] && [ -f ${script} ]; then + _superset_usage_settings=$(ELECTRON_RUN_AS_NODE=1 ${quote(process.execPath)} ${script} --prepare "$@" 2>/dev/null) + if [ -n "$_superset_usage_settings" ]; then + exec "$REAL_BIN" --settings "$_superset_usage_settings" "$@" + fi +fi +exec "$REAL_BIN" "$@"`; +} diff --git a/packages/agent-setup/src/default-account-resolver.test.ts b/packages/agent-setup/src/default-account-resolver.test.ts index 83d5a4d0bdb..503a811f7a0 100644 --- a/packages/agent-setup/src/default-account-resolver.test.ts +++ b/packages/agent-setup/src/default-account-resolver.test.ts @@ -1,10 +1,16 @@ -import { describe, expect, it } from "bun:test"; +import { afterEach, describe, expect, it } from "bun:test"; import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { buildDefaultAccountResolver } from "./agent-wrappers-common"; +const homes: string[] = []; +afterEach(() => { + for (const home of homes.splice(0)) + rmSync(home, { recursive: true, force: true }); +}); + /** Runs the resolver block under bash and returns the resulting env var. */ function resolve(env: Record): string { const script = `${buildDefaultAccountResolver( @@ -57,6 +63,7 @@ function makeHome(pointer: string | null): { profile: string; } { const home = mkdtempSync(join(tmpdir(), "superset-resolver-")); + homes.push(home); const profile = join(home, "profile"); mkdirSync(join(home, "state"), { recursive: true }); mkdirSync(profile); @@ -67,6 +74,21 @@ function makeHome(pointer: string | null): { } describe("buildDefaultAccountResolver", () => { + it("keeps an explicitly pinned system or profile account when the host default changes", () => { + const { home, profile } = makeHome(null); + writeFileSync(join(home, "state", "default-claude-config-dir"), profile); + for (const selected of [undefined, "/selected/account"]) { + expect( + resolve({ + SUPERSET_TERMINAL_ID: "t1", + SUPERSET_HOME_DIR: home, + SUPERSET_PINNED_ACCOUNT: "CLAUDE_CONFIG_DIR", + CLAUDE_CONFIG_DIR: selected, + SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR: selected, + }), + ).toBe(selected ?? ""); + } + }); it("adopts the pointer in a Paradev terminal with no spawn-time value", () => { const { home, profile } = makeHome(""); writeFileSync(join(home, "state", "default-claude-config-dir"), profile); diff --git a/packages/agent-setup/src/index.ts b/packages/agent-setup/src/index.ts index e36152c1e40..2c4986f858d 100644 --- a/packages/agent-setup/src/index.ts +++ b/packages/agent-setup/src/index.ts @@ -83,6 +83,7 @@ export { } from "./config"; export { readSharedDisabledAgentIds, + resolveDisabledAgentIds, writeSharedDisabledAgentIds, } from "./disabled-agent-hooks"; export { diff --git a/packages/agent-setup/src/managed-json-hooks.ts b/packages/agent-setup/src/managed-json-hooks.ts index 28b1b478861..0bf3e73fa03 100644 --- a/packages/agent-setup/src/managed-json-hooks.ts +++ b/packages/agent-setup/src/managed-json-hooks.ts @@ -128,9 +128,9 @@ export function getManagedJsonHooksContent( export function ensureManagedJsonHooks( spec: ManagedJsonHooksSpec, -): void { +): boolean { const content = getManagedJsonHooksContent(spec); - if (content === null) return; + if (content === null) return false; const filePath = spec.getFilePath(); fs.mkdirSync(path.dirname(filePath), { recursive: true }); @@ -138,6 +138,7 @@ export function ensureManagedJsonHooks( console.log( `[agent-setup] ${changed ? "Updated" : "Verified"} ${spec.fileLabel}`, ); + return true; } /** diff --git a/packages/agent-setup/templates/claude-usage-statusline.cjs b/packages/agent-setup/templates/claude-usage-statusline.cjs new file mode 100644 index 00000000000..55fd1f23206 --- /dev/null +++ b/packages/agent-setup/templates/claude-usage-statusline.cjs @@ -0,0 +1,446 @@ +const fs = require("node:fs"); +const path = require("node:path"); +const os = require("node:os"); +const http = require("node:http"); +const { createHash, randomUUID } = require("node:crypto"); +const { spawn, spawnSync } = require("node:child_process"); + +const MAX_INPUT = 512 * 1024; +function readJson(file) { + const info = fs.statSync(file); + if (!info.isFile() || info.size > MAX_INPUT) + throw new Error("Invalid settings"); + const value = JSON.parse(fs.readFileSync(file, "utf8")); + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Invalid settings"); + return value; +} +function optionalSettings(file) { + try { + return readJson(file); + } catch (error) { + if (error.code === "ENOENT") return {}; + throw error; + } +} +function quote(value) { + return `'${value.replaceAll("'", "'\\''")}'`; +} +function prepare(args) { + if ( + process.env.SUPERSET_NATIVE_CLAUDE_USAGE !== "1" || + process.env.SUPERSET_PINNED_ACCOUNT !== "CLAUDE_CONFIG_DIR" || + !process.env.SUPERSET_TERMINAL_ID || + !process.env.SUPERSET_AGENT_LAUNCH_ID || + !process.env.SUPERSET_ACCOUNT_ATTRIBUTION_TOKEN || + process.env.SUPERSET_AGENT_ID !== "claude" + ) + return; + const ownedLaunch = process.env.SUPERSET_NATIVE_CLAUDE_OWNED_LAUNCH === "1"; + for (const arg of args) { + if (arg === "--") break; + if ( + !ownedLaunch && + (/^(--resume|--continue)(=|$)/.test(arg) || ["-r", "-c"].includes(arg)) + ) + return; + if ( + /^(--settings|--setting-sources|--output-format|--input-format|--print|--bare|--help|--version|--fork-session|--remote|--teleport)(=|$)/.test( + arg, + ) || + [ + "-p", + "-h", + "-V", + "-v", + "resume", + "attach", + "agents", + "sessions", + "background", + ].includes(arg) + ) + return; + } + const config = + process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"); + for (const file of [ + path.join(config, "managed-settings.json"), + "/Library/Application Support/ClaudeCode/managed-settings.json", + "/etc/claude-code/managed-settings.json", + ]) + if (fs.existsSync(file)) return; + const cwd = process.cwd(); + const git = spawnSync("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 1000, + }); + const root = git.status === 0 ? git.stdout.trim() : cwd; + // Claude's directory traversal can select parent settings. Preserve unknown precedence. + if (path.resolve(root) !== path.resolve(cwd)) return; + for ( + let parent = path.dirname(cwd); + parent !== path.dirname(parent); + parent = path.dirname(parent) + ) { + if ( + fs.existsSync(path.join(parent, ".claude", "settings.json")) || + fs.existsSync(path.join(parent, ".claude", "settings.local.json")) + ) + return; + } + const files = [ + path.join(config, "settings.json"), + path.join(root, ".claude", "settings.json"), + path.join(root, ".claude", "settings.local.json"), + ]; + let original; + for (const file of files) { + const settings = optionalSettings(file); + if (Object.hasOwn(settings, "statusLine")) original = settings.statusLine; + } + if ( + original !== undefined && + (!original || + typeof original !== "object" || + original.type !== "command" || + typeof original.command !== "string" || + original.command.length > 65536) + ) + return; + const saved = Buffer.from(JSON.stringify(original || {})).toString( + "base64url", + ); + const command = `ELECTRON_RUN_AS_NODE=1 ${quote(process.execPath)} ${quote(__filename)} --status ${quote(saved)}`; + process.stdout.write( + JSON.stringify({ + statusLine: { ...(original || {}), type: "command", command }, + }), + ); +} +function sanitize(data) { + if ( + !data || + typeof data !== "object" || + Array.isArray(data) || + typeof data.session_id !== "string" || + !data.session_id || + data.session_id.length > 256 || + data.agent?.name + ) + return null; + const cost = data.cost?.total_api_duration_ms; + const result = { + session_id: data.session_id, + cost: { + total_api_duration_ms: + typeof cost === "number" && Number.isFinite(cost) && cost >= 0 + ? cost + : null, + }, + rate_limits: {}, + }; + for (const id of ["five_hour", "seven_day"]) { + const window = data.rate_limits?.[id]; + if ( + window && + typeof window.used_percentage === "number" && + Number.isFinite(window.used_percentage) && + window.used_percentage >= 0 && + window.used_percentage <= 100 && + typeof window.resets_at === "number" && + Number.isFinite(window.resets_at) + ) + result.rate_limits[id] = { + used_percentage: window.used_percentage, + resets_at: window.resets_at, + }; + } + return result; +} +function frameMarker(data) { + const home = process.env.SUPERSET_HOME_DIR; + if (!home) return null; + const directory = path.join(home, "state", "native-claude-feed"); + try { + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + const info = fs.lstatSync(directory); + if ( + !info.isDirectory() || + info.isSymbolicLink() || + (process.platform !== "win32" && + ((info.mode & 0o077) !== 0 || info.uid !== process.getuid())) + ) + return null; + const hash = (value) => + createHash("sha256").update(JSON.stringify(value)).digest("hex"); + const file = path.join( + directory, + `${hash([process.env.SUPERSET_TERMINAL_ID, process.env.SUPERSET_AGENT_LAUNCH_ID])}.json`, + ); + const signature = hash(data); + const read = (file) => { + const fd = fs.openSync( + file, + fs.constants.O_RDONLY | + fs.constants.O_NOFOLLOW | + fs.constants.O_NONBLOCK, + ); + try { + const stat = fs.fstatSync(fd); + if ( + !stat.isFile() || + stat.nlink !== 1 || + stat.size > 1024 || + (process.platform !== "win32" && + ((stat.mode & 0o077) !== 0 || stat.uid !== process.getuid())) + ) + throw new Error("Unsafe marker"); + const value = JSON.parse(fs.readFileSync(fd, "utf8")); + if ( + value.version !== 1 || + !/^[a-f0-9]{64}$/.test(value.signature) || + typeof value.accepted !== "boolean" || + !Number.isFinite(value.updatedAt) + ) + throw new Error("Unknown marker"); + return value; + } finally { + fs.closeSync(fd); + } + }; + let previous; + try { + previous = read(file); + } catch (error) { + if (error.code !== "ENOENT") return null; + } + const now = Date.now(); + if ( + previous?.signature === signature && + previous.updatedAt <= now && + now - previous.updatedAt < (previous.accepted ? 24 * 60 * 60_000 : 10_000) + ) + return { skip: true }; + if (!previous) { + const entries = fs.readdirSync(directory); + if (entries.length > 1024) return null; + const markers = entries + .filter((name) => /^[a-f0-9]{64}\.json$/.test(name)) + .map((name) => ({ + file: path.join(directory, name), + value: read(path.join(directory, name)), + })) + .sort((a, b) => a.value.updatedAt - b.value.updatedAt); + while (markers.length >= 256) fs.unlinkSync(markers.shift().file); + } + return { + skip: false, + write(accepted) { + const temporary = `${file}.${randomUUID()}.tmp`; + try { + fs.writeFileSync( + temporary, + JSON.stringify({ + version: 1, + signature, + accepted, + updatedAt: Date.now(), + }), + { flag: "wx", mode: 0o600 }, + ); + fs.renameSync(temporary, file); + } finally { + try { + fs.unlinkSync(temporary); + } catch {} + } + }, + }; + } catch { + return null; + } +} +function endpointCandidates() { + const urls = [process.env.SUPERSET_HOST_AGENT_HOOK_URL]; + const directory = path.join( + process.env.SUPERSET_HOME_DIR || path.join(os.homedir(), ".superset"), + "host", + ); + try { + for (const entry of fs.readdirSync(directory).slice(0, 32)) { + try { + urls.push( + new URL( + "/trpc/notifications.hook", + readJson(path.join(directory, entry, "manifest.json")).endpoint, + ).href, + ); + } catch {} + } + } catch {} + return [...new Set(urls)].slice(0, 4).flatMap((candidate) => { + try { + const url = new URL(candidate); + return url.protocol === "http:" && + ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) && + !url.username && + !url.password && + url.pathname === "/trpc/notifications.hook" + ? [url] + : []; + } catch { + return []; + } + }); +} +function post(url, body, deadline) { + return new Promise((resolve) => { + let settled = false; + let timer; + const finish = (accepted) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(accepted); + }; + const request = http.request( + url, + { + method: "POST", + headers: { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(body), + }, + timeout: 250, + }, + (response) => { + let text = ""; + response.on("data", (chunk) => { + text += chunk; + if (text.length > 4096) { + response.destroy(); + request.destroy(); + finish(false); + } + }); + response.on("end", () => finish(/"ignored"\s*:\s*false/.test(text))); + response.on("error", () => finish(false)); + }, + ); + request.on("timeout", () => request.destroy()); + request.on("error", () => finish(false)); + timer = setTimeout( + () => { + request.destroy(); + finish(false); + }, + Math.max(1, deadline - Date.now()), + ); + request.end(body); + }); +} +function originalStatusLine(command, input) { + if (typeof command !== "string" || !command) return Promise.resolve(0); + return new Promise((resolve) => { + try { + const child = spawn(command, { shell: true, env: process.env }); + const stdout = []; + const stderr = []; + let bytes = 0; + let failed = false; + const collect = (target, chunk) => { + const remaining = MAX_INPUT - bytes; + if (remaining > 0) target.push(chunk.subarray(0, remaining)); + bytes += chunk.length; + if (bytes > MAX_INPUT && !failed) { + // Keep spawnSync's combined output bound, without adding a user-command timeout. + failed = true; + child.kill(); + child.stdin.destroy(); + child.stdout.destroy(); + child.stderr.destroy(); + } + }; + child.stdout.on("data", (chunk) => collect(stdout, chunk)); + child.stderr.on("data", (chunk) => collect(stderr, chunk)); + child.on("error", () => { + failed = true; + }); + child.on("close", (code) => { + process.stdout.write(Buffer.concat(stdout)); + process.stderr.write(Buffer.concat(stderr)); + resolve(!failed && typeof code === "number" ? code : 1); + }); + // A command may exit without reading stdin. Its own result remains authoritative. + child.stdin.on("error", () => {}); + child.stdin.end(input); + } catch { + resolve(1); + } + }); +} +async function status(encoded) { + let input; + try { + input = fs.readFileSync(0); + } catch { + return; + } + if (input.length > MAX_INPUT) return; + let original; + try { + original = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")); + } catch { + return; + } + // The user's command retains its own lifetime; native collection must not wait for it. + const originalResult = originalStatusLine(original.command, input); + try { + const data = sanitize(JSON.parse(input)); + if ( + data && + process.env.SUPERSET_NATIVE_CLAUDE_USAGE === "1" && + process.env.SUPERSET_PINNED_ACCOUNT === "CLAUDE_CONFIG_DIR" && + process.env.SUPERSET_AGENT_ID === "claude" && + process.env.SUPERSET_TERMINAL_ID && + process.env.SUPERSET_AGENT_LAUNCH_ID && + process.env.SUPERSET_ACCOUNT_ATTRIBUTION_TOKEN + ) { + const marker = frameMarker(data); + if (!marker || marker.skip) { + return; + } + const body = JSON.stringify({ + json: { + terminalId: process.env.SUPERSET_TERMINAL_ID, + launchId: process.env.SUPERSET_AGENT_LAUNCH_ID, + attributionToken: process.env.SUPERSET_ACCOUNT_ATTRIBUTION_TOKEN, + agent: { agentId: "claude", sessionId: data.session_id }, + nativeClaudeUsage: data, + }, + }); + const deadline = Date.now() + 500; + let accepted = false; + for (const url of endpointCandidates()) { + if (Date.now() >= deadline) break; + if (await post(url, body, deadline)) { + accepted = true; + break; + } + } + marker.write(accepted); + } + } catch { + } finally { + process.exitCode = await originalResult; + } +} +if (process.argv[2] === "--prepare") { + try { + prepare(process.argv.slice(3)); + } catch {} +} else if (process.argv[2] === "--status") { + status(process.argv[3] || "").catch(() => {}); +} diff --git a/packages/chat-runtime/src/commands/commands/commands.ts b/packages/chat-runtime/src/commands/commands/commands.ts index 6f8ea6040bf..f13d257b4a0 100644 --- a/packages/chat-runtime/src/commands/commands/commands.ts +++ b/packages/chat-runtime/src/commands/commands/commands.ts @@ -1,5 +1,6 @@ import { randomUUID } from "node:crypto"; import { + deriveQueuedPrompts, deriveTimeline, emptySnapshot, outlineSnapshot, @@ -13,7 +14,9 @@ import type { ApprovalRequest, BackgroundSubagentInput, CancelTurnInput, + ChatLaunchContext, CloseSessionInput, + CloseStoppedAccountSessionInput, Cursor, DiscoverSessionsResult, DurableEvent, @@ -21,6 +24,7 @@ import type { GetSessionInput, PromptInput, QueuedPromptInput, + RecoverAccountSessionInput, RespondToApprovalInput, ResumeQueueInput, SetConfigOptionInput, @@ -31,7 +35,9 @@ import type { import { backgroundSubagentInputSchema, cancelTurnInputSchema, + chatLaunchContextSchema, closeSessionInputSchema, + closeStoppedAccountSessionInputSchema, createSessionInputSchema, discoverSessionsInputSchema, forkSessionInputSchema, @@ -42,6 +48,7 @@ import { listSessionsInputSchema, promptInputSchema, queuedPromptInputSchema, + recoverAccountSessionInputSchema, respondToApprovalInputSchema, resumeQueueInputSchema, rewindSessionInputSchema, @@ -54,6 +61,12 @@ import { z } from "zod"; import type { ChatDb, ChatSessionRow } from "../../db"; import type { ChatJournal } from "../../journal"; import type { ChatSessionStore } from "../../projection"; +import { + accountSuccessorMatches, + findAccountCommand, + findAccountSuccessor, + readLaunchContext, +} from "../../projection/launchContext"; import type { ChatResetReason, PageResult } from "../../replay"; import { latestSeq, readPage, readSince } from "../../replay"; import type { @@ -69,10 +82,13 @@ export const createSessionCommandSchema = createSessionInputSchema .extend({ scopeId: z.string().min(1), cwd: z.string().min(1), + launchContext: chatLaunchContextSchema.optional(), + predecessorSessionId: z.string().min(1).optional(), resume: z .object({ harnessSessionId: z.string().min(1), quiet: z.boolean().optional(), + requireExact: z.boolean().optional(), }) .optional(), }); @@ -157,9 +173,15 @@ export type DiscoverSessionsCommandInput = z.input< export type CreateSessionResult = { sessionId: string; epoch: string; + terminalId?: string; }; export type GetSessionResult = { + accountBound?: true; + account?: Pick< + ChatLaunchContext["account"], + "agent" | "selection" | "identity" + > | null; session: ChatSessionRow | null; cursor: Cursor | null; /** @@ -188,6 +210,7 @@ type ResumedChat = { export type GetQueueResult = QueueState & { live: boolean }; export type ChatSessionListEntry = ChatSessionRow & { + accountBound?: true; live: boolean; terminalId: string | null; }; @@ -195,6 +218,9 @@ export type ChatSessionListEntry = ChatSessionRow & { export type ChatCommands = { createSession(input: CreateSessionCommandInput): CreateSessionResult; resumeSession(input: ResumeSessionInput): CreateSessionResult; + recoverAccountSession( + input: RecoverAccountSessionInput, + ): Promise; prompt(input: PromptInput): PromptResult; removeQueuedPrompt(input: QueuedPromptInput): void; steerQueuedPrompt(input: QueuedPromptInput): void; @@ -207,6 +233,9 @@ export type ChatCommands = { setMode(input: SetModeInput): void; setConfigOption(input: SetConfigOptionInput): void; closeSession(input: CloseSessionInput): Promise; + closeStoppedAccountSession( + input: CloseStoppedAccountSessionInput, + ): Promise; closeScope(scopeId: string): Promise; forkSession( input: ForkSessionCommandInput, @@ -241,6 +270,11 @@ export type CommandsOptions = { dedupe: { run(commandId: string, execute: () => T): T }; mintSessionId?: () => string; subagentItems?: SubagentItems; + validateAccountLaunch?: ( + context: ChatLaunchContext, + harness: string, + scopeId: string, + ) => Promise; }; const MAX_CACHED_REPLAY_EVENTS = 20_000; @@ -248,6 +282,10 @@ const MAX_CACHED_REPLAY_EVENTS = 20_000; export function createCommands(options: CommandsOptions): ChatCommands { const mintSessionId = options.mintSessionId ?? randomUUID; const subagentItems = options.subagentItems ?? new SubagentItems(options.db); + const accountForks = new Map< + string, + { input: string; promise: Promise } + >(); const replays = new Map< string, @@ -357,6 +395,9 @@ export function createCommands(options: CommandsOptions): ChatCommands { const live = options.live.get(row.sessionId); return { ...row, + ...(row.launchContextJson !== null + ? { accountBound: true as const } + : {}), live: live !== null, terminalId: live?.terminalId ?? null, }; @@ -366,6 +407,57 @@ export function createCommands(options: CommandsOptions): ChatCommands { return { createSession(input) { const parsed = createSessionCommandSchema.parse(input); + if (parsed.launchContext) { + if ( + parsed.cwd !== parsed.launchContext.cwd || + parsed.terminalId !== parsed.launchContext.terminalId + ) + throw new Error( + "The saved chat launch context does not match the conversation.", + ); + const receipt = findAccountCommand(options.db, parsed.commandId); + if (receipt) { + if ( + receipt.scopeId !== parsed.scopeId || + receipt.harness !== parsed.harness || + receipt.launchContextJson !== + JSON.stringify(parsed.launchContext) || + receipt.predecessorSessionId !== + (parsed.predecessorSessionId ?? null) + ) + throw new Error( + "This command already belongs to a different account or conversation.", + ); + return { + sessionId: receipt.sessionId, + epoch: receipt.epoch, + terminalId: parsed.terminalId, + }; + } + } else { + for (const row of options.sessions.list()) { + if (row.launchContextJson === null) continue; + if ( + parsed.resume && + row.harnessSessionId === parsed.resume.harnessSessionId + ) + throw new Error( + "This conversation has a saved account. Use account-aware recovery.", + ); + if (parsed.terminalId) { + let context: ChatLaunchContext | null = null; + try { + context = readLaunchContext(row); + } catch { + continue; + } + if (context?.terminalId === parsed.terminalId) + throw new Error( + "This pane has a saved account. Use account-aware recovery.", + ); + } + } + } return options.dedupe.run(`createSession:${parsed.commandId}`, () => { const resumed = resumedFor(parsed); const handedOff = resumed && handOff(resumed); @@ -378,6 +470,14 @@ export function createCommands(options: CommandsOptions): ChatCommands { sessionId, scopeId: parsed.scopeId, harness: parsed.harness, + ...(parsed.launchContext + ? { + launchContextJson: JSON.stringify(parsed.launchContext), + createCommandId: parsed.commandId, + predecessorSessionId: parsed.predecessorSessionId, + harnessSessionId: parsed.resume?.harnessSessionId, + } + : {}), }); try { options.live.create({ @@ -389,13 +489,18 @@ export function createCommands(options: CommandsOptions): ChatCommands { modelId: parsed.modelId, resume: parsed.resume, terminalId: parsed.terminalId, + launchContext: parsed.launchContext, }); } catch (error) { options.journal.discard(sessionId); throw error; } if (resumed) sendPending(resumed, sessionId); - return { sessionId, epoch: opened.epoch }; + return { + sessionId, + epoch: opened.epoch, + ...(parsed.launchContext ? { terminalId: parsed.terminalId } : {}), + }; }); }, @@ -432,6 +537,101 @@ export function createCommands(options: CommandsOptions): ChatCommands { return created; }, + async recoverAccountSession(input) { + const parsed = recoverAccountSessionInputSchema.parse(input); + let source = options.sessions.get(parsed.sessionId); + if (!source) throw new Error("The saved conversation was not found."); + const visited = new Set(); + for (;;) { + if (visited.has(source.sessionId) || visited.size >= 100) + throw new Error("The saved conversation recovery chain is invalid."); + visited.add(source.sessionId); + const next = findAccountSuccessor(options.db, source.sessionId); + if (!next) break; + if (!accountSuccessorMatches(source, next)) + throw new Error("The saved conversation recovery account changed."); + source = next; + } + const context = readLaunchContext(source); + if (!context || !options.validateAccountLaunch) + throw new Error( + "This conversation does not have a recoverable saved account.", + ); + const receipt = findAccountCommand(options.db, parsed.commandId); + if (receipt && !visited.has(receipt.sessionId)) + throw new Error( + "This command already belongs to another conversation.", + ); + if (options.live.isClosing(source.sessionId)) + throw new Error( + "The previous agent is still closing. Wait for it to stop before recovering.", + ); + const registered = options.live.get(source.sessionId); + if (registered?.state.status === "dead") + throw new Error( + "The stopped agent is still registered. Close the stopped agent before retrying recovery.", + ); + if (registered || receipt) + return { + sessionId: source.sessionId, + epoch: source.epoch, + terminalId: context.terminalId, + }; + // Reading the journal repairs the native-id projection after a host restart. + options.journal.cursor(source.sessionId); + source = options.sessions.get(source.sessionId) as ChatSessionRow; + if (source.queuedCount > 0) + throw new Error( + "This conversation has unsent queued messages. Review and remove them before resuming.", + ); + if (!source.harnessSessionId) + throw new Error( + "The saved conversation has no confirmed native session ID.", + ); + const unchanged = JSON.stringify(source); + await options.validateAccountLaunch( + context, + source.harness, + source.scopeId, + ); + if ( + JSON.stringify(options.sessions.get(source.sessionId)) !== unchanged || + findAccountSuccessor(options.db, source.sessionId) || + options.live.isClosing(source.sessionId) || + options.live.get(source.sessionId) + ) + throw new Error( + "The conversation changed or was already resumed. Refresh it before trying again.", + ); + if ( + options.sessions + .list() + .some( + (row) => + row.sessionId !== source.sessionId && + (options.live.get(row.sessionId) || + options.live.isClosing(row.sessionId)) && + row.launchContextJson !== null && + readLaunchContext(row)?.terminalId === context.terminalId, + ) + ) + throw new Error("This pane already has a running conversation."); + const created = this.createSession({ + commandId: parsed.commandId, + scopeId: source.scopeId, + harness: source.harness, + cwd: context.cwd, + terminalId: context.terminalId, + launchContext: context, + predecessorSessionId: source.sessionId, + resume: { + harnessSessionId: source.harnessSessionId, + requireExact: true, + }, + }); + return { ...created, terminalId: context.terminalId }; + }, + prompt(input) { const parsed: PromptInput = promptInputSchema.parse(input); return options.dedupe.run(`prompt:${parsed.commandId}`, () => @@ -448,7 +648,29 @@ export function createCommands(options: CommandsOptions): ChatCommands { removeQueuedPrompt(input) { const parsed: QueuedPromptInput = queuedPromptInputSchema.parse(input); options.dedupe.run(`removeQueuedPrompt:${parsed.commandId}`, () => { - options.live.require(parsed.sessionId).removeQueued(parsed.itemId); + const live = options.live.get(parsed.sessionId); + if (live) { + live.removeQueued(parsed.itemId); + return; + } + const row = options.sessions.get(parsed.sessionId); + if (row?.launchContextJson == null) + throw new Error("The conversation is not live."); + const replayed = replaySession(parsed.sessionId); + if (!replayed.ok) throw new Error("The saved queue could not be read."); + const stored = replayed.snapshot.items.get(parsed.itemId); + const queued = deriveQueuedPrompts(replayed.snapshot).find( + (item) => item.id === parsed.itemId, + ); + if (!stored || !queued) + throw new Error("The queued message was not found."); + const item = { ...queued, discarded: true }; + delete item.queued; + options.journal.append(parsed.sessionId, { + type: "item", + item, + turnId: stored.turnId, + }); }); }, @@ -538,19 +760,134 @@ export function createCommands(options: CommandsOptions): ChatCommands { */ async forkSession(input) { const parsed = forkSessionCommandSchema.parse(input); - const live = options.live.require(parsed.sessionId); - const forked = await live.fork(); - if (!forked) return null; - const source = options.sessions.get(parsed.sessionId); - if (!source) return null; - return this.createSession({ - commandId: parsed.commandId, - scopeId: source.scopeId, - cwd: parsed.cwd, - harness: parsed.harness ?? source.harness, - resume: { harnessSessionId: forked }, - terminalId: parsed.terminalId ?? live.terminalId, + const original = options.sessions.get(parsed.sessionId); + const context = original ? readLaunchContext(original) : null; + if (context && original) { + const pending = accountForks.get(parsed.commandId); + if (pending) { + if (pending.input !== JSON.stringify(parsed)) + throw new Error( + "This command already belongs to another conversation.", + ); + return pending.promise; + } + } + const execute = async () => { + if (context && original) { + const receipt = findAccountCommand(options.db, parsed.commandId); + if (receipt) { + const prior = readLaunchContext(receipt); + if ( + prior?.forkOfSessionId !== parsed.sessionId || + receipt.scopeId !== original.scopeId || + receipt.harness !== (parsed.harness ?? original.harness) + ) + throw new Error( + "This command already belongs to another conversation.", + ); + return { + sessionId: receipt.sessionId, + epoch: receipt.epoch, + terminalId: prior.terminalId, + }; + } + if ( + parsed.cwd !== context.cwd || + (parsed.harness && parsed.harness !== original?.harness) || + !options.validateAccountLaunch + ) + throw new Error( + "An account-bound branch must keep its original agent and working folder.", + ); + await options.validateAccountLaunch( + context, + original.harness, + original.scopeId, + ); + } + const live = options.live.require(parsed.sessionId); + const forked = await live.fork(); + if (!forked) return null; + const source = options.sessions.get(parsed.sessionId); + if (!source) return null; + if (context) { + if (source.launchContextJson !== original?.launchContextJson) + throw new Error("The original conversation account changed."); + await options.validateAccountLaunch?.( + context, + source.harness, + source.scopeId, + ); + } + return this.createSession({ + commandId: parsed.commandId, + scopeId: source.scopeId, + cwd: parsed.cwd, + harness: parsed.harness ?? source.harness, + resume: { + harnessSessionId: forked, + ...(context ? { requireExact: true } : {}), + }, + terminalId: parsed.terminalId ?? live.terminalId, + ...(context + ? { + launchContext: { + ...context, + forkOfSessionId: source.sessionId, + }, + } + : {}), + }); + }; + if (!context) return execute(); + const promise = execute(); + accountForks.set(parsed.commandId, { + input: JSON.stringify(parsed), + promise, }); + try { + return await promise; + } finally { + accountForks.delete(parsed.commandId); + } + }, + + async closeStoppedAccountSession(input) { + const { sessionId } = closeStoppedAccountSessionInputSchema.parse(input); + const row = options.sessions.get(sessionId); + if (!row || !readLaunchContext(row)) + throw new Error( + "This action requires a saved account-bound conversation.", + ); + if (options.live.isClosing(sessionId)) + throw new Error( + "This agent is still closing. Wait before trying again.", + ); + const live = options.live.get(sessionId); + if (!live || live.state.status !== "dead") + throw new Error( + "Only a failed registered account agent can be stopped here.", + ); + const replayed = replaySession(sessionId); + if (!replayed.ok) + throw new Error( + "The saved queue could not be read. Nothing was stopped.", + ); + if ( + live.queueState.prompts.length > 0 || + deriveQueuedPrompts(replayed.snapshot).length > 0 + ) + throw new Error( + "This conversation has unsent queued messages. Review and remove them before stopping the agent.", + ); + // No await between queue validation and registry removal: a prompt cannot + // enter the agent after the user confirmed this bounded stop action. + replays.delete(sessionId); + try { + await options.live.dispose(sessionId); + } finally { + options.journal.announce(sessionId); + } }, /** @@ -663,7 +1000,18 @@ export function createCommands(options: CommandsOptions): ChatCommands { const session = options.sessions.get(parsed.sessionId); const lastError = session?.status === "dead" ? lastErrorNotice(parsed.sessionId) : null; + let account: GetSessionResult["account"] = null; + try { + const context = session ? readLaunchContext(session) : null; + if (context) { + const { agent, selection, identity } = context.account; + account = { agent, selection, identity }; + } + } catch {} return { + ...(session?.launchContextJson != null + ? { accountBound: true as const, account } + : {}), live: options.live.get(parsed.sessionId) !== null, session, cursor: session && seq !== null ? { epoch: session.epoch, seq } : null, @@ -674,7 +1022,23 @@ export function createCommands(options: CommandsOptions): ChatCommands { getQueue(input) { const parsed: GetSessionInput = getSessionInputSchema.parse(input); const session = options.live.get(parsed.sessionId); - if (!session) return { live: false, paused: false, prompts: [] }; + if (!session) { + const row = options.sessions.get(parsed.sessionId); + if (row?.launchContextJson == null) + return { live: false, paused: false, prompts: [] }; + const replayed = replaySession(parsed.sessionId); + if (!replayed.ok) throw new Error("The saved queue could not be read."); + return { + live: false, + paused: true, + prompts: deriveQueuedPrompts(replayed.snapshot).map((item) => ({ + itemId: item.id, + clientId: item.clientId, + content: item.content, + queuedAtMs: item.startedAtMs, + })), + }; + } return { live: true, ...session.queueState }; }, diff --git a/packages/chat-runtime/src/db/account-migration.test.ts b/packages/chat-runtime/src/db/account-migration.test.ts new file mode 100644 index 00000000000..e41e9b99923 --- /dev/null +++ b/packages/chat-runtime/src/db/account-migration.test.ts @@ -0,0 +1,107 @@ +import { Database } from "bun:sqlite"; +import { expect, test } from "bun:test"; +import { + copyFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; + +test("chat account migration preserves legacy data and durably enforces unique launch and successor receipts", () => { + const dir = mkdtempSync(join(tmpdir(), "chat-account-migration-")); + const source = resolve(import.meta.dir, "drizzle"); + const folder = join(dir, "migrations"); + mkdirSync(join(folder, "meta"), { recursive: true }); + const journal = JSON.parse( + readFileSync(join(source, "meta/_journal.json"), "utf8"), + ) as { entries: Array<{ tag: string }> }; + const index = journal.entries.findIndex( + (entry) => entry.tag === "0001_account_chat_launch_context", + ); + expect(index).toBe(1); + for (const entry of journal.entries) + copyFileSync( + join(source, `${entry.tag}.sql`), + join(folder, `${entry.tag}.sql`), + ); + const writeJournal = (count: number) => + writeFileSync( + join(folder, "meta/_journal.json"), + JSON.stringify({ ...journal, entries: journal.entries.slice(0, count) }), + ); + let sqlite = new Database(join(dir, "chat.db")); + try { + writeJournal(index); + migrate(drizzle(sqlite), { migrationsFolder: folder }); + sqlite.exec( + "INSERT INTO chat_sessions_local (session_id, scope_id, harness, harness_session_id, epoch, status, title, updated_at) VALUES ('old', 'workspace', 'claude-acp', 'native-old', 'epoch', 'idle', 'kept', 1)", + ); + const original = sqlite + .query("SELECT * FROM chat_sessions_local") + .get() as Record; + writeJournal(index + 1); + migrate(drizzle(sqlite), { migrationsFolder: folder }); + expect(sqlite.query("SELECT * FROM chat_sessions_local").get()).toEqual({ + ...original, + launch_context: null, + create_command_id: null, + predecessor_session_id: null, + }); + sqlite.exec( + "UPDATE chat_sessions_local SET launch_context='fixture', create_command_id='command', predecessor_session_id='source' WHERE session_id='old'", + ); + sqlite.close(); + sqlite = new Database(join(dir, "chat.db")); + migrate(drizzle(sqlite), { migrationsFolder: folder }); + expect( + sqlite + .query( + "SELECT launch_context, create_command_id, predecessor_session_id FROM chat_sessions_local", + ) + .get(), + ).toEqual({ + launch_context: "fixture", + create_command_id: "command", + predecessor_session_id: "source", + }); + for (const field of ["create_command_id", "predecessor_session_id"]) { + expect(() => + sqlite.exec( + `INSERT INTO chat_sessions_local (session_id, scope_id, harness, epoch, status, updated_at, ${field}) SELECT 'duplicate', 'workspace', 'claude-acp', 'epoch', 'idle', 1, ${field} FROM chat_sessions_local WHERE session_id='old'`, + ), + ).toThrow(`UNIQUE constraint failed: chat_sessions_local.${field}`); + } + const insertLegacy = sqlite.query( + "INSERT INTO chat_sessions_local (session_id, scope_id, harness, epoch, status, updated_at) VALUES (?, 'workspace', 'claude-acp', 'epoch', 'idle', 1)", + ); + insertLegacy.run("null-a"); + insertLegacy.run("null-b"); + expect( + sqlite + .query( + "SELECT session_id, create_command_id, predecessor_session_id FROM chat_sessions_local WHERE session_id IN ('null-a', 'null-b') ORDER BY session_id", + ) + .all(), + ).toEqual([ + { + session_id: "null-a", + create_command_id: null, + predecessor_session_id: null, + }, + { + session_id: "null-b", + create_command_id: null, + predecessor_session_id: null, + }, + ]); + } finally { + sqlite.close(); + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/packages/chat-runtime/src/db/drizzle/0001_account_chat_launch_context.sql b/packages/chat-runtime/src/db/drizzle/0001_account_chat_launch_context.sql new file mode 100644 index 00000000000..1ee58e6e03a --- /dev/null +++ b/packages/chat-runtime/src/db/drizzle/0001_account_chat_launch_context.sql @@ -0,0 +1,5 @@ +ALTER TABLE `chat_sessions_local` ADD `launch_context` text;--> statement-breakpoint +ALTER TABLE `chat_sessions_local` ADD `create_command_id` text;--> statement-breakpoint +ALTER TABLE `chat_sessions_local` ADD `predecessor_session_id` text;--> statement-breakpoint +CREATE UNIQUE INDEX `chat_sessions_local_create_command_id_idx` ON `chat_sessions_local` (`create_command_id`);--> statement-breakpoint +CREATE UNIQUE INDEX `chat_sessions_local_predecessor_session_id_idx` ON `chat_sessions_local` (`predecessor_session_id`); \ No newline at end of file diff --git a/packages/chat-runtime/src/db/drizzle/meta/0001_snapshot.json b/packages/chat-runtime/src/db/drizzle/meta/0001_snapshot.json new file mode 100644 index 00000000000..69d57134106 --- /dev/null +++ b/packages/chat-runtime/src/db/drizzle/meta/0001_snapshot.json @@ -0,0 +1,189 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "73ba863c-cd96-443a-8af8-398609a612a5", + "prevId": "0c9aa8ad-c478-45be-a2a7-661fae258042", + "tables": { + "chat_journal": { + "name": "chat_journal", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "epoch": { + "name": "epoch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seq": { + "name": "seq", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ts": { + "name": "ts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event_json": { + "name": "event_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "chat_journal_session_id_epoch_seq_pk": { + "columns": [ + "session_id", + "epoch", + "seq" + ], + "name": "chat_journal_session_id_epoch_seq_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_sessions_local": { + "name": "chat_sessions_local", + "columns": { + "session_id": { + "name": "session_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "scope_id": { + "name": "scope_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "harness": { + "name": "harness", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "harness_session_id": { + "name": "harness_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "launch_context": { + "name": "launch_context", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "create_command_id": { + "name": "create_command_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "predecessor_session_id": { + "name": "predecessor_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "epoch": { + "name": "epoch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "queued_count": { + "name": "queued_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "chat_sessions_local_scope_id_idx": { + "name": "chat_sessions_local_scope_id_idx", + "columns": [ + "scope_id" + ], + "isUnique": false + }, + "chat_sessions_local_create_command_id_idx": { + "name": "chat_sessions_local_create_command_id_idx", + "columns": [ + "create_command_id" + ], + "isUnique": true + }, + "chat_sessions_local_predecessor_session_id_idx": { + "name": "chat_sessions_local_predecessor_session_id_idx", + "columns": [ + "predecessor_session_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/chat-runtime/src/db/drizzle/meta/_journal.json b/packages/chat-runtime/src/db/drizzle/meta/_journal.json index 73957c8f3ee..2a68c020eb1 100644 --- a/packages/chat-runtime/src/db/drizzle/meta/_journal.json +++ b/packages/chat-runtime/src/db/drizzle/meta/_journal.json @@ -8,6 +8,13 @@ "when": 1785962456515, "tag": "0000_natural_wolverine", "breakpoints": true + }, + { + "idx": 1, + "version": "6", + "when": 1791593834266, + "tag": "0001_account_chat_launch_context", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/chat-runtime/src/db/schema/schema.ts b/packages/chat-runtime/src/db/schema/schema.ts index 2b0ec19b2ec..6cdade9d66a 100644 --- a/packages/chat-runtime/src/db/schema/schema.ts +++ b/packages/chat-runtime/src/db/schema/schema.ts @@ -5,6 +5,7 @@ import { primaryKey, sqliteTable, text, + uniqueIndex, } from "drizzle-orm/sqlite-core"; export const CHAT_DB_FILENAME = "chat.db"; @@ -30,13 +31,24 @@ export const chatSessionsLocal = sqliteTable( scopeId: text("scope_id").notNull(), harness: text().notNull(), harnessSessionId: text("harness_session_id"), + launchContextJson: text("launch_context"), + createCommandId: text("create_command_id"), + predecessorSessionId: text("predecessor_session_id"), epoch: text().notNull(), status: text().$type().notNull(), title: text(), queuedCount: integer("queued_count").notNull().default(0), updatedAt: integer("updated_at").notNull(), }, - (table) => [index("chat_sessions_local_scope_id_idx").on(table.scopeId)], + (table) => [ + index("chat_sessions_local_scope_id_idx").on(table.scopeId), + uniqueIndex("chat_sessions_local_create_command_id_idx").on( + table.createCommandId, + ), + uniqueIndex("chat_sessions_local_predecessor_session_id_idx").on( + table.predecessorSessionId, + ), + ], ); export type JournalRow = typeof chatJournal.$inferSelect; diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts index 0c8b6f3e47a..b1faacc64e9 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, jest } from "bun:test"; import { spawn } from "node:child_process"; import type { Item } from "@superset/chat/protocol"; import { AGENT_DEFAULT_MODE, wrapHiddenText } from "@superset/chat/protocol"; +import { waitFor } from "../../testing/testUtils"; import type { AdapterEvent } from "../types"; import { AcpAdapter, @@ -27,6 +28,10 @@ class FakeAcpAgent { loadError: { code: number; message: string } | null = null; /** Answer nothing, as an agent stuck on a login prompt does. */ silent = false; + loadSupported = true; + sessionSurface: Record | unknown[] | null = {}; + loadState: "running" | "requires_action" | null = null; + loadResult: Record | null = null; /** What the agent answers `initialize` with; older agents answer 1. */ protocolVersion = 2; /** agentInfo.name reported at initialize, as pdev reports "paradev". */ @@ -308,6 +313,11 @@ class FakeAcpAgent { const resumes = frame.method === "session/load" || frame.method === "session/resume"; queueMicrotask(() => { + if (resumes && this.loadState) + this.notify((frame.params as { sessionId: string }).sessionId, { + sessionUpdate: "state_update", + state: this.loadState, + }); if (frame.method === "initialize") { this.respond(frame.id as number, { ...(this.agentName @@ -318,6 +328,8 @@ class FakeAcpAgent { : {}), protocolVersion: this.protocolVersion, capabilities: { + loadSession: this.loadSupported, + ...(this.sessionSurface ? { session: this.sessionSurface } : {}), promptCapabilities: { image: true }, ...(this.sessionCapabilities ? { sessionCapabilities: this.sessionCapabilities } @@ -361,6 +373,8 @@ class FakeAcpAgent { const sessionId = (frame.params as { sessionId: string }).sessionId; for (const update of this.replayUpdates) this.notify(sessionId, update); this.respond(frame.id as number, null); + } else if (resumes && this.loadResult) { + this.respond(frame.id as number, this.loadResult); } else if (resumes && this.wholeMessageReplay) { const sessionId = (frame.params as { sessionId: string }).sessionId; this.notify(sessionId, { @@ -518,6 +532,8 @@ function startAdapter( selections: { modelId?: string; modeId?: string } = {}, adapterOptions: Pick< AcpAdapterOptions, + | "beforePrompt" + | "resolveAttachment" | "defaultModeId" | "requestTimeoutMs" | "clientApprovalModes" @@ -567,6 +583,292 @@ function textOf(item: Item | undefined): string { } describe("AcpAdapter", () => { + for (const sessionSurface of [null, []] as const) { + it(`refuses exact ACP v2 recovery without a plain session surface: ${JSON.stringify(sessionSurface)}`, async () => { + const agent = new FakeAcpAgent(); + agent.loadSupported = true; + agent.sessionSurface = sessionSurface === null ? null : []; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + }); + const events: AdapterEvent[] = []; + void collect( + adapter.start({ + cwd: "/work", + resume: { harnessSessionId: "sess-1", requireExact: true }, + }), + events, + ); + await waitFor(() => sessionsOf(events).at(-1)?.status === "dead"); + expect(agent.sent.map((frame) => frame.method)).toEqual(["initialize"]); + await adapter.dispose(); + }); + } + + it("Cancel while account validation is pending never dispatches the held prompt", async () => { + const agent = new FakeAcpAgent(); + let release!: () => void; + const validation = new Promise((resolve) => { + release = resolve; + }); + let validating = false; + const { adapter, events } = startAdapter( + agent, + undefined, + {}, + { + beforePrompt: async () => { + validating = true; + await validation; + }, + }, + ); + await waitFor(() => sessionsOf(events).at(-1)?.status === "idle"); + adapter.prompt([{ type: "text", text: "must not be sent" }]); + await waitFor(() => validating); + adapter.cancelTurn(); + release(); + await flush(30); + expect(agent.sent.some((frame) => frame.method === "session/prompt")).toBe( + false, + ); + expect(sessionsOf(events).at(-1)?.status).toBe("idle"); + expect( + events.filter((event) => event.kind === "turn").at(-1), + ).toMatchObject({ kind: "turn", turn: { status: "interrupted" } }); + await adapter.dispose(); + }); + + it("a turn completed during account validation cannot receive stale steering", async () => { + const agent = new FakeAcpAgent(); + agent.insertOnPrompt = true; + agent.steeringOutcome = "injected"; + let release!: () => void; + const validation = new Promise((resolve) => { + release = resolve; + }); + let checks = 0; + let steeringValidation = false; + const { adapter, events } = startAdapter( + agent, + undefined, + {}, + { + beforePrompt: async () => { + if (++checks > 1) { + steeringValidation = true; + await validation; + } + }, + }, + ); + await waitFor(() => sessionsOf(events).at(-1)?.status === "idle"); + adapter.prompt([{ type: "text", text: "first" }]); + await waitFor(() => adapter.canSteer()); + const pending = adapter.steer([{ type: "text", text: "stale steer" }]); + await waitFor(() => steeringValidation); + agent.notify("sess-1", { + sessionUpdate: "state_update", + state: "idle", + stopReason: "end_turn", + }); + await flush(20); + release(); + expect(await pending).toBe(false); + expect( + agent.sent.filter((frame) => frame.method === "session/prompt"), + ).toHaveLength(1); + expect( + agent.sent.some((frame) => frame.method === "_session/steering"), + ).toBe(false); + await adapter.dispose(); + }); + + it("keeps ACP v2's synchronized running state after exact resume", async () => { + const agent = new FakeAcpAgent(); + agent.sessionSurface = {}; + agent.loadSupported = false; + agent.loadState = "running"; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + }); + const events: AdapterEvent[] = []; + void collect( + adapter.start({ + cwd: "/work", + resume: { harnessSessionId: "sess-1", requireExact: true }, + }), + events, + ); + await waitFor(() => + sessionsOf(events).some( + (session) => session.harnessSessionId === "sess-1", + ), + ); + expect(sessionsOf(events).at(-1)?.status).toBe("running"); + expect(agent.sent.some((frame) => frame.method === "session/prompt")).toBe( + false, + ); + await adapter.dispose(); + }); + + it("exact ACP v2 resume uses the session surface without legacy loadSession", async () => { + const agent = new FakeAcpAgent(); + agent.loadSupported = false; + agent.sessionSurface = {}; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + }); + const events: AdapterEvent[] = []; + void collect( + adapter.start({ + cwd: "/work", + resume: { harnessSessionId: "sess-1", requireExact: true }, + }), + events, + ); + await waitFor(() => sessionsOf(events).at(-1)?.status === "idle"); + expect(agent.sent.some((frame) => frame.method === "session/resume")).toBe( + true, + ); + expect(agent.sent.some((frame) => frame.method === "session/new")).toBe( + false, + ); + expect(sessionsOf(events).at(-1)?.harnessSessionId).toBe("sess-1"); + await adapter.dispose(); + }); + + it("revalidates account identity before the ACP v2 prompt steering path", async () => { + const agent = new FakeAcpAgent(); + agent.insertOnPrompt = true; + agent.steeringOutcome = "injected"; + let valid = true; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + beforePrompt: async () => { + if (!valid) throw new Error("account changed"); + }, + }); + const events: AdapterEvent[] = []; + void collect(adapter.start({ cwd: "/work" }), events); + await flush(); + adapter.prompt([{ type: "text", text: "first" }]); + await flush(); + valid = false; + await expect( + adapter.steer([{ type: "text", text: "second" }]), + ).rejects.toThrow("account changed"); + expect( + agent.sent.filter((frame) => frame.method === "session/prompt"), + ).toHaveLength(1); + await adapter.dispose(); + }); + + for (const failure of [ + "missing-capability", + "load-error", + "different-id", + "malformed-metadata", + ] as const) { + it(`exact recovery refuses ${failure} without starting or prompting a different session`, async () => { + const agent = new FakeAcpAgent(); + agent.loadSupported = failure !== "missing-capability"; + if (failure === "missing-capability") agent.sessionSurface = null; + agent.loadFails = failure === "load-error"; + if (failure === "different-id") + agent.loadResult = { sessionId: "foreign" }; + if (failure === "malformed-metadata") + agent.loadResult = { sessionId: "foreign", modes: false }; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + }); + const events: AdapterEvent[] = []; + void collect( + adapter.start({ + cwd: "/work", + resume: { harnessSessionId: "sess-1", requireExact: true }, + }), + events, + ); + adapter.prompt([{ type: "text", text: "held" }]); + await flush(); + expect(agent.sent.map((frame) => frame.method)).not.toContain( + "session/new", + ); + expect(agent.sent.map((frame) => frame.method)).not.toContain( + "session/prompt", + ); + expect(sessionsOf(events).at(-1)?.status).toBe("dead"); + await adapter.dispose(); + }); + } + + for (const variant of ["user_message", "user_message_chunk"] as const) { + it(`ignores foreign ${variant} during exact history replay`, async () => { + const agent = new FakeAcpAgent(); + agent.foreignUpdateDuringLoad = { + sessionUpdate: variant, + content: + variant === "user_message" + ? [{ type: "text", text: "foreign history" }] + : { type: "text", text: "foreign history" }, + }; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + }); + const events: AdapterEvent[] = []; + void collect( + adapter.start({ + cwd: "/work", + resume: { harnessSessionId: "sess-1", requireExact: true }, + }), + events, + ); + await waitFor(() => sessionsOf(events).at(-1)?.status === "idle"); + expect(JSON.stringify(itemsOf(events))).not.toContain("foreign history"); + expect(sessionsOf(events).at(-1)?.status).toBe("idle"); + await adapter.dispose(); + }); + } + + it("revalidates a selected account before prompt and steering", async () => { + const agent = new FakeAcpAgent(); + agent.holdPrompts = true; + agent.steeringOutcome = "injected"; + let valid = true; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + beforePrompt: async () => { + if (!valid) throw new Error("account changed"); + }, + }); + const events: AdapterEvent[] = []; + void collect(adapter.start({ cwd: "/work" }), events); + await flush(); + adapter.prompt([{ type: "text", text: "first" }]); + await flush(); + valid = false; + await expect( + adapter.steer([{ type: "text", text: "second" }]), + ).rejects.toThrow("account changed"); + expect( + agent.sent.filter((frame) => frame.method === "_session/steering"), + ).toHaveLength(0); + adapter.prompt([{ type: "text", text: "third" }]); + await flush(); + expect( + agent.sent.filter((frame) => frame.method === "session/prompt"), + ).toHaveLength(1); + await adapter.dispose(); + }); + it("bootstraps, streams a turn, and maps items", async () => { const agent = new FakeAcpAgent(); let counter = 0; @@ -3981,6 +4283,34 @@ describe("AcpAdapter on protocol v2", () => { await adapter.dispose(); }); + it("revalidates the account before a child session prompt", async () => { + const agent = new FakeAcpAgent(); + let valid = true; + const { adapter } = startAdapter( + agent, + undefined, + {}, + { + beforePrompt: async () => { + if (!valid) throw new Error("account changed"); + }, + }, + ); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + valid = false; + await expect( + adapter.steerSubagent("subagent:child-1", [ + { type: "text", text: "continue" }, + ]), + ).rejects.toThrow("account changed"); + expect( + agent.sent.some((frame) => frame.method === "session/prompt"), + ).toBe(false); + await adapter.dispose(); + }); + it("steerSubagent prompts the child session", async () => { const agent = new FakeAcpAgent(); const { adapter, events } = startAdapter(agent); @@ -4010,6 +4340,366 @@ describe("AcpAdapter on protocol v2", () => { await adapter.dispose(); }); + it.each([ + "account changed", + "child closed", + ])("does not steer a child when %s while an attachment resolves", async (change) => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.steeringOutcome = "injected"; + let valid = true; + let release: + | ((value: { path: string; mimeType: string; data: string }) => void) + | undefined; + const { adapter } = startAdapter( + agent, + undefined, + {}, + { + resolveAttachment: () => + new Promise((resolve) => { + release = resolve; + }), + beforePrompt: async () => { + if (!valid) throw new Error("account changed"); + }, + }, + ); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + const pending = adapter.steerSubagent("subagent:child-1", [ + { + type: "attachment", + attachmentId: "owned-fixture", + name: "fixture.png", + mimeType: "image/png", + }, + ]); + await flush(); + if (!release) throw new Error("Expected deferred attachment"); + if (change === "account changed") valid = false; + else { + agent.notify("sess-1", { + sessionUpdate: "subagent_update", + sessionId: "child-1", + state: { state: "idle", stopReason: "end_turn" }, + }); + await flush(); + } + release({ + path: "/fixture/image.png", + mimeType: "image/png", + data: "aW1hZ2U=", + }); + if (change === "account changed") + await expect(pending).rejects.toThrow("account changed"); + else await expect(pending).resolves.toBe(false); + expect( + agent.sent.filter((frame) => + ["_session/steering", "session/prompt"].includes( + String(frame.method), + ), + ), + ).toEqual([]); + } finally { + await adapter.dispose(); + } + }); + + it("Stop during the v1 child fallback validation cannot restart the child", async () => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.steeringOutcome = "promptRequired"; + let calls = 0; + let validationStarted!: () => void; + let releaseValidation!: () => void; + const started = new Promise((resolve) => { + validationStarted = resolve; + }); + const blocked = new Promise((resolve) => { + releaseValidation = resolve; + }); + const { adapter } = startAdapter( + agent, + undefined, + {}, + { + beforePrompt: async () => { + if (++calls === 2) { + validationStarted(); + await blocked; + } + }, + }, + ); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + const pending = adapter.steerSubagent("subagent:child-1", [ + { type: "text", text: "continue" }, + ]); + await started; + expect(await adapter.stopBackgroundTask("subagent:child-1")).toBe(true); + releaseValidation(); + await expect(pending).resolves.toBe(false); + expect( + agent.sent.filter((frame) => frame.method === "_session/steering"), + ).toHaveLength(1); + expect( + agent.sent.filter((frame) => frame.method === "session/cancel"), + ).toMatchObject([{ params: { sessionId: "child-1" } }]); + expect( + agent.sent.filter((frame) => frame.method === "session/prompt"), + ).toEqual([]); + } finally { + releaseValidation(); + await adapter.dispose(); + } + }); + + it("revalidates before the v1 child promptRequired fallback", async () => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.steeringOutcome = "promptRequired"; + let calls = 0; + const { adapter } = startAdapter( + agent, + undefined, + {}, + { + beforePrompt: async () => { + if (++calls === 2) throw new Error("account changed"); + }, + }, + ); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + await expect( + adapter.steerSubagent("subagent:child-1", [ + { type: "text", text: "continue" }, + ]), + ).rejects.toThrow("account changed"); + expect( + agent.sent.some((frame) => frame.method === "session/prompt"), + ).toBe(false); + } finally { + await adapter.dispose(); + } + }); + + it.each([ + "injected", + "startedNewTurn", + ])("acknowledges a v1 child steer as %s without a second prompt", async (outcome) => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.steeringOutcome = outcome; + const { adapter } = startAdapter(agent); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + expect( + await adapter.steerSubagent("subagent:child-1", [ + { type: "text", text: "check the tests too" }, + ]), + ).toBe(true); + expect( + agent.sent.filter((frame) => frame.method === "_session/steering"), + ).toMatchObject([ + { + params: { + sessionId: "child-1", + prompt: [{ type: "text", text: "check the tests too" }], + _meta: { steering: { idleBehavior: "promptRequired" } }, + }, + }, + ]); + expect( + agent.sent.some((frame) => frame.method === "session/prompt"), + ).toBe(false); + } finally { + await adapter.dispose(); + } + }); + + it.each([ + "promptRequired", + "unsupported", + ])("handles the v1 child steer outcome %s without duplicating accepted input", async (outcome) => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.steeringOutcome = outcome; + const { adapter } = startAdapter(agent); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + expect( + await adapter.steerSubagent("subagent:child-1", [ + { type: "text", text: "continue" }, + ]), + ).toBe(outcome === "promptRequired"); + const requests = agent.sent.filter((frame) => + ["_session/steering", "session/prompt"].includes( + String(frame.method), + ), + ); + expect(requests.map((frame) => frame.method)).toEqual( + outcome === "promptRequired" + ? ["_session/steering", "session/prompt"] + : ["_session/steering"], + ); + } finally { + await adapter.dispose(); + } + }); + + it.each([ + 1, 2, + ])("keeps the normal child prompt path for protocol %s without v1 steering", async (version) => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = version; + agent.steeringOutcome = version === 2 ? "injected" : null; + const { adapter } = startAdapter(agent); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + expect( + await adapter.steerSubagent("subagent:child-1", [ + { type: "text", text: "continue" }, + ]), + ).toBe(true); + expect( + agent.sent.some((frame) => frame.method === "_session/steering"), + ).toBe(false); + expect( + agent.sent.filter((frame) => frame.method === "session/prompt"), + ).toHaveLength(1); + } finally { + await adapter.dispose(); + } + }); + + it("a child closed while its attachment resolves cannot receive steering", async () => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.steeringOutcome = "injected"; + let release!: (value: { + path: string; + mimeType: string; + data: string; + }) => void; + let attachmentStarted!: () => void; + const started = new Promise((resolve) => { + attachmentStarted = resolve; + }); + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_opts, handlers) => agent.transport(handlers), + resolveAttachment: () => + new Promise((resolve) => { + release = resolve; + attachmentStarted(); + }), + now: () => 1, + mintId: () => "fixture-id", + }); + void collect(adapter.start({ cwd: "/work" }), []); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + const pending = adapter.steerSubagent("subagent:child-1", [ + { + type: "attachment", + attachmentId: "fixture", + name: "fixture.png", + mimeType: "image/png", + }, + ]); + await started; + agent.notify("sess-1", { + sessionUpdate: "subagent_update", + sessionId: "child-1", + state: { state: "idle", stopReason: "end_turn" }, + }); + await flush(); + release({ + path: "/fixture/image.png", + mimeType: "image/png", + data: "aW1hZ2U=", + }); + await expect(pending).resolves.toBe(false); + expect( + agent.sent.filter((frame) => + ["_session/steering", "session/prompt"].includes( + String(frame.method), + ), + ), + ).toEqual([]); + } finally { + await adapter.dispose(); + } + }); + + it.each([ + "promptRequired", + "injected", + ])("Stop before the v1 child %s reply prevents only new input", async (outcome) => { + const agent = new FakeAcpAgent(); + agent.protocolVersion = 1; + agent.steeringOutcome = outcome; + let responseSeen!: () => void; + let releaseResponse!: () => void; + const held = new Promise((resolve) => { + responseSeen = resolve; + }); + const adapter = new AcpAdapter({ + command: "fake", + now: () => 1, + mintId: () => "fixture-id", + createTransport: (_opts, handlers) => + agent.transport({ + ...handlers, + onLine(line) { + const frame = JSON.parse(line); + if (frame.result?.outcome === outcome) { + releaseResponse = () => handlers.onLine(line); + responseSeen(); + } else handlers.onLine(line); + }, + }), + }); + void collect(adapter.start({ cwd: "/work" }), []); + await flush(); + agent.notify("sess-1", announce("child-1")); + await flush(); + try { + const pending = adapter.steerSubagent("subagent:child-1", [ + { type: "text", text: "continue" }, + ]); + await held; + expect(await adapter.stopBackgroundTask("subagent:child-1")).toBe(true); + releaseResponse(); + await expect(pending).resolves.toBe(outcome === "injected"); + expect( + agent.sent.filter((frame) => frame.method === "session/prompt"), + ).toEqual([]); + expect( + agent.sent.filter((frame) => frame.method === "session/cancel"), + ).toHaveLength(1); + } finally { + await adapter.dispose(); + } + }); + it("renders a steer echo in the child", async () => { const agent = new FakeAcpAgent(); const { adapter, events } = startAdapter(agent); @@ -5737,3 +6427,116 @@ describe("AcpAdapter when the agent fails", () => { await adapter.dispose(); }); }); + +describe("AcpAdapter passive Claude quota feed", () => { + it("forwards only main-session live metadata with a response counter", async () => { + const agent = new FakeAcpAgent(); + agent.holdPrompts = true; + const sessions: string[] = []; + const captured: Array<{ + sessionId: string; + rateLimitInfo: unknown; + responseCounter: number; + }> = []; + let disposed = 0; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_options, handlers) => agent.transport(handlers), + onSessionId: (id) => sessions.push(id), + onClaudeRateLimit: (value) => captured.push(value), + onDisposed: () => { + disposed++; + }, + }); + const events: AdapterEvent[] = []; + void collect(adapter.start({ cwd: "/work" }), events); + await flush(); + expect(sessions).toEqual(["sess-1"]); + const usage = { + sessionUpdate: "usage_update", + used: 10, + size: 100, + _meta: { + "_claude/rateLimit": { + rateLimitType: "five_hour", + utilization: 0.25, + resetsAt: 1_800_000_300, + }, + }, + }; + agent.notify("sess-1", usage); + agent.notify("foreign", usage); + expect(captured.map((item) => item.responseCounter)).toEqual([0]); + adapter.prompt([{ type: "text", text: "fixture" }]); + await flush(); + agent.notify("sess-1", { + sessionUpdate: "agent_message_chunk", + messageId: "response-1", + content: { type: "text", text: "fixture" }, + }); + agent.notify("sess-1", usage); + agent.notify("foreign", { + sessionUpdate: "agent_message_chunk", + messageId: "foreign-response", + content: { type: "text", text: "fixture" }, + }); + agent.notify("sess-1", { + sessionUpdate: "agent_message_chunk", + messageId: "response-1", + content: { type: "text", text: "fixture" }, + }); + agent.notify("sess-1", usage); + expect(captured.map((item) => item.responseCounter)).toEqual([0, 1, 1]); + await adapter.dispose(); + expect(disposed).toBe(1); + }); + it("does not interpret restored history as a current API response", async () => { + const agent = new FakeAcpAgent(); + agent.replayUpdates = [ + { + sessionUpdate: "agent_message", + messageId: "old-response", + content: [{ type: "text", text: "fixture history" }], + }, + { + sessionUpdate: "usage_update", + used: 10, + size: 100, + _meta: { + "_claude/rateLimit": { + utilization: 0.25, + rateLimitType: "five_hour", + resetsAt: 1_800_000_300, + }, + }, + }, + ]; + const captured: unknown[] = []; + const adapter = new AcpAdapter({ + command: "fake", + createTransport: (_options, handlers) => agent.transport(handlers), + onClaudeRateLimit: (value) => captured.push(value), + }); + const events: AdapterEvent[] = []; + void collect( + adapter.start({ cwd: "/work", resume: { harnessSessionId: "sess-1" } }), + events, + ); + await flush(40); + expect(captured).toEqual([]); + agent.notify("sess-1", { + sessionUpdate: "usage_update", + used: 10, + size: 100, + _meta: { + "_claude/rateLimit": { + utilization: 0.25, + rateLimitType: "five_hour", + resetsAt: 1_800_000_300, + }, + }, + }); + expect(captured).toEqual([expect.objectContaining({ responseCounter: 0 })]); + await adapter.dispose(); + }); +}); diff --git a/packages/chat-runtime/src/harness/acp/acpAdapter.ts b/packages/chat-runtime/src/harness/acp/acpAdapter.ts index d4bcac6c2d8..f13f194fac3 100644 --- a/packages/chat-runtime/src/harness/acp/acpAdapter.ts +++ b/packages/chat-runtime/src/harness/acp/acpAdapter.ts @@ -205,6 +205,14 @@ function sessionMissing(error: unknown): boolean { } export type AcpAdapterOptions = SpawnAcpOptions & { + onSessionId?: (sessionId: string) => void; + onClaudeRateLimit?: (input: { + sessionId: string; + rateLimitInfo: unknown; + responseCounter: number; + }) => void; + onDisposed?: () => void; + beforePrompt?: () => Promise; launch?: () => Promise>; /** Selected for a new session that asks for no mode, when the agent offers it. */ defaultModeId?: string; @@ -237,6 +245,7 @@ type SubagentRun = { parentSessionId: string; parentTaskId?: string; steers: Set<{ echoes: Set; shared: boolean }>; + cancelGeneration: number; }; type SubagentControls = { @@ -435,7 +444,11 @@ export class AcpAdapter implements HarnessAdapter { private unkeyedImageSequence = 0; private queuedPrompts: UserContent[][] = []; private disposed = false; + private claudeResponseCounter = 0; + private claudeResponseTurn: string | null = null; + private readonly claudeResponseIds = new Set(); private dead = false; + private startupStatus: SessionState["status"] | null = null; private stderrTail = ""; private customAnswer: string | null = null; private heldTurnId: string | null = null; @@ -512,11 +525,23 @@ export class AcpAdapter implements HarnessAdapter { const client = this.client; const sessionId = this.sessionId; if (!client || !sessionId || !this.canSteer()) return false; + const turnId = this.currentTurn?.id; + const prompt = await this.toAcpPrompt(content); + if (this.options.beforePrompt) await this.options.beforePrompt(); + if ( + this.disposed || + this.dead || + this.client !== client || + this.sessionId !== sessionId || + this.currentTurn?.id !== turnId || + !this.canSteer() + ) + return false; const v2TurnId = this.v2TurnIsCurrent() ? this.v2Turn?.id : undefined; if (v2TurnId) { const response = await client.request("session/prompt", { sessionId, - prompt: await this.toAcpPrompt(content), + prompt, }); const parsed = acpPromptResponseSchema.safeParse(response).data; if (parsed?.messageId !== undefined && parsed.stopReason === undefined) { @@ -527,7 +552,7 @@ export class AcpAdapter implements HarnessAdapter { } const response = await client.request(ACP_STEERING_METHOD, { sessionId, - prompt: await this.toAcpPrompt(content), + prompt, _meta: { steering: { idleBehavior: "promptRequired" } }, }); const outcome = acpSteeringResponseSchema.safeParse(response).data?.outcome; @@ -701,6 +726,7 @@ export class AcpAdapter implements HarnessAdapter { const run = subagentSessionId && this.subagents.get(subagentSessionId); if (subagentSessionId) { if (!run || run.item.canStop !== true) return false; + run.cancelGeneration++; this.client.notify("session/cancel", { sessionId: subagentSessionId }); this.cancelSubagentApprovals(subagentSessionId, run); return true; @@ -723,13 +749,44 @@ export class AcpAdapter implements HarnessAdapter { const run = subagentSessionId && this.subagents.get(subagentSessionId); if (!client || !subagentSessionId || !run || run.item.canSteer !== true) return false; + const cancelGeneration = run.cancelGeneration; + const prompt = await this.toAcpPrompt(content); + if (this.options.beforePrompt) await this.options.beforePrompt(); + if ( + this.disposed || + this.dead || + this.client !== client || + this.subagents.get(subagentSessionId) !== run || + run.cancelGeneration !== cancelGeneration || + run.item.canSteer !== true + ) + return false; const steer = { echoes: new Set(), shared: run.steers.size > 0 }; for (const other of run.steers) other.shared = true; run.steers.add(steer); try { + if (this.negotiatedVersion < 2 && this.supportsSteering) { + const response = await client.request(ACP_STEERING_METHOD, { + sessionId: subagentSessionId, + prompt, + _meta: { steering: { idleBehavior: "promptRequired" } }, + }); + const outcome = + acpSteeringResponseSchema.safeParse(response).data?.outcome; + if (outcome === "injected" || outcome === "startedNewTurn") return true; + if (outcome !== "promptRequired") return false; + if (this.options.beforePrompt) await this.options.beforePrompt(); + if ( + this.client !== client || + this.subagents.get(subagentSessionId) !== run || + run.cancelGeneration !== cancelGeneration || + run.item.canSteer !== true + ) + return false; + } await client.request("session/prompt", { sessionId: subagentSessionId, - prompt: await this.toAcpPrompt(content), + prompt, }); return true; } catch (error) { @@ -798,6 +855,15 @@ export class AcpAdapter implements HarnessAdapter { return parsed.success ? parsed.data.sessionId : null; } + private supportsExactResume(): boolean { + if (this.negotiatedVersion < 2) + return this.agentCapabilities.loadSession === true; + const session = this.agentCapabilities.session; + return ( + session !== null && typeof session === "object" && !Array.isArray(session) + ); + } + /** What `initialize` said this agent can do to a session. */ private supportsSessionCapability(name: string): boolean { const caps = this.agentCapabilities.sessionCapabilities; @@ -851,6 +917,9 @@ export class AcpAdapter implements HarnessAdapter { async dispose(): Promise { if (this.disposed) return; this.disposed = true; + try { + this.options.onDisposed?.(); + } catch {} this.stalePendingApprovals(); this.backgroundTasks.dispose(); if (this.shellPoll) clearInterval(this.shellPoll); @@ -948,6 +1017,10 @@ export class AcpAdapter implements HarnessAdapter { let response: unknown; let resumed = false; if (startOptions.resume) { + if (startOptions.resume.requireExact && !this.supportsExactResume()) + throw new Error( + "This agent cannot load the saved conversation. No new conversation was created.", + ); this.replaying = true; this.quietReplay = startOptions.resume.quiet === true; this.loadingSessionId = startOptions.resume.harnessSessionId; @@ -968,6 +1041,7 @@ export class AcpAdapter implements HarnessAdapter { ); resumed = true; } catch (loadError) { + if (startOptions.resume.requireExact) throw loadError; // A session that was started but never prompted has no transcript, // so the agent answers "not found". Any other failure keeps the // conversation, and a new session would hide it from the agent. @@ -1003,11 +1077,35 @@ export class AcpAdapter implements HarnessAdapter { ); } + // Validate identity separately: malformed optional response metadata must + // never conceal a different session ID during an exact load. + if (startOptions.resume?.requireExact && response !== null) { + const returnedId = + typeof response === "object" && + response !== null && + "sessionId" in response + ? response.sessionId + : undefined; + if ( + returnedId !== undefined && + returnedId !== startOptions.resume.harnessSessionId + ) + throw new Error( + "The agent returned a different conversation. No messages were sent.", + ); + } // session/load returns null after replaying history via session/update. const parsed = acpNewSessionResponseSchema.safeParse(response); this.sessionId = parsed.success ? parsed.data.sessionId : (startOptions.resume?.harnessSessionId ?? null); + if ( + startOptions.resume?.requireExact && + this.sessionId !== startOptions.resume.harnessSessionId + ) + throw new Error( + "The agent returned a different conversation. No messages were sent.", + ); if (!this.sessionId) { this.emitNotice("error", "acp agent returned no session id"); @@ -1018,9 +1116,13 @@ export class AcpAdapter implements HarnessAdapter { return; } + try { + this.options.onSessionId?.(this.sessionId); + } catch {} this.emitSession({ - status: "idle", + status: this.startupStatus ?? "idle", harnessSessionId: this.sessionId, + exactResumeSupported: this.supportsExactResume(), ...(this.options.clientApprovalModes ? { modeId: @@ -1075,15 +1177,29 @@ export class AcpAdapter implements HarnessAdapter { this.heldTurnId = turnId; await this.selectionsApplied(); if (this.heldTurnId !== turnId) return; - this.heldTurnId = null; const client = this.client; - if (!client || !this.sessionId || this.currentTurn?.id !== turnId) return; + const sessionId = this.sessionId; + if (!client || !sessionId || this.currentTurn?.id !== turnId) return; const v2 = this.negotiatedVersion >= 2; - if (v2) this.v2Turn = { id: turnId, inserted: false }; + const mayDispatch = () => + !this.disposed && + !this.dead && + this.client === client && + this.sessionId === sessionId && + this.heldTurnId === turnId && + this.currentTurn?.id === turnId && + this.currentTurn.status === "running"; try { + const prompt = await this.toAcpPrompt(content); + if (!mayDispatch()) return; + if (this.options.beforePrompt) await this.options.beforePrompt(); + if (!mayDispatch()) return; + // Keep cancellation local until all asynchronous preparation is complete. + this.heldTurnId = null; + if (v2) this.v2Turn = { id: turnId, inserted: false }; const response = await client.request("session/prompt", { - sessionId: this.sessionId, - prompt: await this.toAcpPrompt(content), + sessionId, + prompt, }); const parsed = acpPromptResponseSchema.safeParse(response).data; if ( @@ -1097,6 +1213,14 @@ export class AcpAdapter implements HarnessAdapter { if (this.v2Turn?.id === turnId) this.v2Turn = null; this.finishTurn(turnId, parsed?.stopReason); } catch (error) { + if (this.heldTurnId === turnId) this.heldTurnId = null; + if ( + this.disposed || + this.dead || + this.currentTurn?.id !== turnId || + this.currentTurn.status !== "running" + ) + return; if (this.v2Turn?.id === turnId) this.v2Turn = null; this.failTurn(turnId, (error as Error).message); } @@ -1192,6 +1316,12 @@ export class AcpAdapter implements HarnessAdapter { // this session has never seen them, so dropping them starts the transcript // at the agent's first reply. Each one opens a turn of its own, or the // whole replay lands in one group whose order comes down to item id. + if ( + this.replaying && + this.isForeignSession(outer.data.sessionId) && + (variant === "user_message_chunk" || variant === "user_message") + ) + return; const childSession = this.subagents.has(outer.data.sessionId) || this.finishedSubagents.has(outer.data.sessionId); @@ -1260,7 +1390,45 @@ export class AcpAdapter implements HarnessAdapter { return; } + if ( + !this.replaying && + (variant === "agent_message_chunk" || variant === "agent_message") && + this.currentTurn?.status === "running" + ) { + const responseId = messageIdOf(outer.data.update); + if ( + (responseId && !this.claudeResponseIds.has(responseId)) || + (!responseId && this.claudeResponseTurn !== this.currentTurn.id) + ) { + this.claudeResponseTurn = this.currentTurn.id; + this.claudeResponseCounter++; + if (responseId) this.claudeResponseIds.add(responseId); + if (this.claudeResponseIds.size > 256) + this.claudeResponseIds.delete( + this.claudeResponseIds.values().next().value as string, + ); + } + } if (variant === "usage_update") { + if (!this.replaying && this.sessionId === outer.data.sessionId) { + const metadata = ( + outer.data.update as { _meta?: Record } + )._meta; + const rateLimitInfo = metadata?.["_claude/rateLimit"]; + if ( + rateLimitInfo && + typeof rateLimitInfo === "object" && + !Array.isArray(rateLimitInfo) + ) { + try { + this.options.onClaudeRateLimit?.({ + sessionId: outer.data.sessionId, + rateLimitInfo, + responseCounter: this.claudeResponseCounter, + }); + } catch {} + } + } const usage = acpUsageUpdateSchema.safeParse(outer.data.update); if (usage.success && usage.data.cost !== undefined) this.main.flush(); if ( @@ -1702,6 +1870,7 @@ export class AcpAdapter implements HarnessAdapter { parentSessionId, ...(parent ? { parentTaskId: parent.item.id } : {}), steers: new Set(), + cancelGeneration: 0, }; this.subagents.set(sessionId, run); this.emitItem(item, turnId); @@ -2424,6 +2593,9 @@ export class AcpAdapter implements HarnessAdapter { } private emitSession(session: Partial): void { + // v2 resume synchronizes live state before its response; do not reset it. + if (!this.sessionId && session.status && session.status !== "starting") + this.startupStatus = session.status; if (session.modeId) this.modeId = session.modeId; this.emit({ kind: "session", session }); } diff --git a/packages/chat-runtime/src/harness/types.ts b/packages/chat-runtime/src/harness/types.ts index 201195cd3d7..9f5ab154793 100644 --- a/packages/chat-runtime/src/harness/types.ts +++ b/packages/chat-runtime/src/harness/types.ts @@ -19,7 +19,11 @@ export type HarnessStartOptions = { modeId?: string; modelId?: string; /** `quiet` loads the agent's history without replaying it as items. */ - resume?: { harnessSessionId: string; quiet?: boolean }; + resume?: { + harnessSessionId: string; + quiet?: boolean; + requireExact?: boolean; + }; }; /** Asks a harness for its own history. Must not open a session. */ diff --git a/packages/chat-runtime/src/index.ts b/packages/chat-runtime/src/index.ts index 14a3d5efb55..5646a4a8efe 100644 --- a/packages/chat-runtime/src/index.ts +++ b/packages/chat-runtime/src/index.ts @@ -1,4 +1,4 @@ -import type { ChatCommands } from "./commands"; +import type { ChatCommands, CommandsOptions } from "./commands"; import { CommandDedupe, createCommands } from "./commands"; import type { ChatDb, OpenChatDb } from "./db"; import { createChatDb } from "./db"; @@ -30,6 +30,7 @@ export type ChatRuntimeOptions = { bootstrapLimit?: number; dedupeCapacity?: number; onSessionChanged?: ChatJournalOptions["onSessionChanged"]; + validateAccountLaunch?: CommandsOptions["validateAccountLaunch"]; }; export type ChatRuntime = { @@ -75,6 +76,7 @@ export function createChatRuntime(options: ChatRuntimeOptions): ChatRuntime { live, dedupe: new CommandDedupe(options.dedupeCapacity), subagentItems, + validateAccountLaunch: options.validateAccountLaunch, }); return { diff --git a/packages/chat-runtime/src/journal/epoch/epoch.ts b/packages/chat-runtime/src/journal/epoch/epoch.ts index 01d3599efcb..76d471f88c5 100644 --- a/packages/chat-runtime/src/journal/epoch/epoch.ts +++ b/packages/chat-runtime/src/journal/epoch/epoch.ts @@ -15,6 +15,9 @@ export type ChatSessionInit = { harnessSessionId?: string | null; status?: SessionStatus; title?: string | null; + launchContextJson?: string; + createCommandId?: string; + predecessorSessionId?: string; }; export type OpenedEpoch = { @@ -36,6 +39,9 @@ export function openEpoch(db: ChatDb, init: ChatSessionInit): OpenedEpoch { scopeId: init.scopeId, harness: init.harness, harnessSessionId: init.harnessSessionId ?? null, + launchContextJson: init.launchContextJson ?? null, + createCommandId: init.createCommandId ?? null, + predecessorSessionId: init.predecessorSessionId ?? null, epoch, status: init.status ?? "starting", title: init.title ?? null, diff --git a/packages/chat-runtime/src/projection/launchContext.ts b/packages/chat-runtime/src/projection/launchContext.ts new file mode 100644 index 00000000000..c948ef63502 --- /dev/null +++ b/packages/chat-runtime/src/projection/launchContext.ts @@ -0,0 +1,65 @@ +import { + type ChatLaunchContext, + chatLaunchContextSchema, +} from "@superset/chat/protocol"; +import { eq } from "drizzle-orm"; +import type { ChatDb, ChatSessionRow } from "../db"; +import { chatSessionsLocal } from "../db"; + +export function readLaunchContext( + row: ChatSessionRow, +): ChatLaunchContext | null { + if (row.launchContextJson === null) return null; + try { + return chatLaunchContextSchema.parse(JSON.parse(row.launchContextJson)); + } catch { + throw new Error("The saved chat account is invalid. Nothing was launched."); + } +} + +export function findAccountCommand(db: ChatDb, commandId: string) { + return ( + db + .select() + .from(chatSessionsLocal) + .where(eq(chatSessionsLocal.createCommandId, commandId)) + .get() ?? null + ); +} + +export function findAccountSuccessor(db: ChatDb, sessionId: string) { + return ( + db + .select() + .from(chatSessionsLocal) + .where(eq(chatSessionsLocal.predecessorSessionId, sessionId)) + .get() ?? null + ); +} + +/** A switch is a recorded exact-conversation successor, never an arbitrary account change. */ +export function accountSuccessorMatches( + source: ChatSessionRow, + next: ChatSessionRow, +): boolean { + if ( + next.predecessorSessionId !== source.sessionId || + source.scopeId !== next.scopeId || + source.harness !== next.harness + ) + return false; + if (source.launchContextJson === next.launchContextJson) return true; + const from = readLaunchContext(source); + const to = readLaunchContext(next); + return Boolean( + from && + to && + next.predecessorSessionId === source.sessionId && + to.switchOfSessionId === source.sessionId && + source.harnessSessionId && + source.harnessSessionId === next.harnessSessionId && + from.cwd === to.cwd && + from.terminalId === to.terminalId && + from.account.agent === to.account.agent, + ); +} diff --git a/packages/chat-runtime/src/router/router/accountSessions.test.ts b/packages/chat-runtime/src/router/router/accountSessions.test.ts new file mode 100644 index 00000000000..51862b51802 --- /dev/null +++ b/packages/chat-runtime/src/router/router/accountSessions.test.ts @@ -0,0 +1,871 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { randomUUID } from "node:crypto"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { ChatLaunchAccount, SessionState } from "@superset/chat/protocol"; +import { eq } from "drizzle-orm"; +import { chatSessionsLocal } from "../../db"; +import { FakeHarness } from "../../harness/fake"; +import { + type ChatRuntime, + createChatRuntime, + type HarnessFactoryOptions, +} from "../../index"; +import { createBunChatDb } from "../../testing/testRuntime/testRuntime"; +import { waitFor } from "../../testing/testUtils"; +import { + type ChatRouterOptions, + createChatCallerFactory, + createChatRouter, +} from "./router"; + +const ACCOUNT: ChatLaunchAccount = { + agent: "claude", + selection: "/fixture/account-a", + identity: "a".repeat(64), + directory: "/fixture/account-a", +}; +const fixtures: Array<{ runtime: ChatRuntime; dir: string }> = []; +afterEach(async () => { + for (const f of fixtures.splice(0)) { + await f.runtime.dispose(); + rmSync(f.dir, { recursive: true, force: true }); + } +}); + +function fixture( + fixtureOptions: { + validate?: () => void; + beforeDispose?: () => Promise; + initialStatus?: "idle" | "dead" | "running"; + allowPendingPrompt?: boolean; + switcher?: NonNullable; + initialMode?: string; + stateExtras?: Partial; + validIdentities?: string[]; + } = {}, +) { + const dir = mkdtempSync(join(tmpdir(), "chat-account-")); + const launches: HarnessFactoryOptions[] = []; + let validationFailure = false; + let forks = 0; + const open = () => + createChatRuntime({ + dataDir: dir, + openDatabase: createBunChatDb, + validateAccountLaunch: async (context) => { + fixtureOptions.validate?.(); + if ( + validationFailure || + !(fixtureOptions.validIdentities ?? [ACCOUNT.identity]).includes( + context.account.identity, + ) + ) + throw new Error("saved account unavailable"); + }, + harnesses: new Map([ + [ + "claude-acp", + (options: HarnessFactoryOptions) => { + launches.push(options); + const adapter = new FakeHarness({ + start: [ + { + kind: "session", + session: { + status: fixtureOptions.initialStatus ?? "idle", + modeId: fixtureOptions.initialMode, + exactResumeSupported: true, + ...fixtureOptions.stateExtras, + harnessSessionId: + options.resume?.harnessSessionId ?? + `native-${options.sessionId}`, + }, + }, + ], + turns: fixtureOptions.allowPendingPrompt ? [[]] : [], + }); + const dispose = adapter.dispose.bind(adapter); + return Object.assign(adapter, { + dispose: async () => { + await fixtureOptions.beforeDispose?.(); + await dispose(); + }, + fork: async () => { + forks++; + return "native-branch"; + }, + }); + }, + ], + ]), + }); + const state = { runtime: open(), dir }; + fixtures.push(state); + const caller = () => + createChatCallerFactory( + createChatRouter(state.runtime, { + resolveCwd: () => "/fixture/work", + accountHarnesses: ["claude-acp"], + prepareAccountSwitch: fixtureOptions.switcher, + prepareAccount: async ({ account }) => { + if ( + account.selection !== ACCOUNT.selection || + account.identity !== ACCOUNT.identity + ) + throw new Error("changed account"); + return ACCOUNT; + }, + }), + )({}); + return { + state, + launches, + caller, + forks: () => forks, + fail: () => { + validationFailure = true; + }, + reopen: async () => { + await state.runtime.dispose(); + state.runtime = open(); + }, + }; +} + +function input() { + return { + commandId: randomUUID(), + workspaceId: "workspace", + harness: "claude-acp" as const, + account: { selection: ACCOUNT.selection, identity: ACCOUNT.identity }, + }; +} +async function idle(f: ReturnType, sessionId: string) { + await waitFor( + () => f.state.runtime.sessions.get(sessionId)?.status === "idle", + ); +} + +describe("account-bound chat lifecycle", () => { + test("persists an explicit account before launching and reconciles create after host restart", async () => { + const f = fixture(); + const request = input(); + const result = await f.caller().createAccountSession(request); + await idle(f, result.sessionId); + expect(f.launches[0]?.launchContext?.account).toEqual(ACCOUNT); + expect(f.launches[0]?.terminalId).toBe(result.terminalId); + await f.reopen(); + expect(await f.caller().createAccountSession(request)).toEqual(result); + expect( + await f + .caller() + .accountSessionByCommand({ commandId: request.commandId }), + ).toEqual(result); + expect(f.launches).toHaveLength(1); + expect( + (await f.caller().getSession({ sessionId: result.sessionId })) + .accountBound, + ).toBe(true); + }); + + test("concurrent identical create requests launch once and cannot repurpose their receipt", async () => { + const f = fixture(); + const request = input(); + const [a, b] = await Promise.all([ + f.caller().createAccountSession(request), + f.caller().createAccountSession(request), + ]); + expect(a).toEqual(b); + expect(f.launches).toHaveLength(1); + await expect( + f.caller().createAccountSession({ ...request, workspaceId: "different" }), + ).rejects.toThrow("another conversation"); + }); + + test("rejects client-supplied native and pane identities", async () => { + const f = fixture(); + await expect( + f + .caller() + .createAccountSession({ ...input(), terminalId: "occupied" } as never), + ).rejects.toThrow(); + await expect( + f.caller().createAccountSession({ + ...input(), + resume: { harnessSessionId: "foreign" }, + } as never), + ).rejects.toThrow(); + expect(f.launches).toHaveLength(0); + }); + + test("host restart resumes exact native ID in a single durable successor with original account", async () => { + const f = fixture(); + const source = await f.caller().createAccountSession(input()); + await idle(f, source.sessionId); + await f.reopen(); + const request = { commandId: randomUUID(), sessionId: source.sessionId }; + const recovered = await f.caller().recoverAccountSession(request); + expect(recovered.sessionId).not.toBe(source.sessionId); + expect(recovered.terminalId).toBe(source.terminalId); + expect(f.launches.at(-1)?.resume).toEqual({ + harnessSessionId: `native-${source.sessionId}`, + requireExact: true, + }); + expect(f.launches.at(-1)?.launchContext?.account).toEqual(ACCOUNT); + expect(await f.caller().recoverAccountSession(request)).toEqual(recovered); + expect( + await f + .caller() + .recoverAccountSession({ ...request, commandId: randomUUID() }), + ).toEqual(recovered); + expect(f.launches).toHaveLength(2); + expect(f.state.runtime.sessions.get(source.sessionId)).not.toBeNull(); + }); + + test("an unavailable account blocks recovery and generic routes cannot drop its binding", async () => { + const f = fixture(); + const source = await f.caller().createAccountSession(input()); + await idle(f, source.sessionId); + await f.reopen(); + f.fail(); + await expect( + f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }), + ).rejects.toThrow("unavailable"); + await expect( + f.caller().createSession({ + commandId: randomUUID(), + workspaceId: "workspace", + harness: "claude-acp", + resume: { harnessSessionId: `native-${source.sessionId}` }, + }), + ).rejects.toThrow("account-aware recovery"); + await expect( + f.caller().createSession({ + commandId: randomUUID(), + workspaceId: "workspace", + harness: "claude-acp", + terminalId: source.terminalId, + }), + ).rejects.toThrow("account-aware recovery"); + await expect( + f.caller().createSession({ + commandId: randomUUID(), + workspaceId: "workspace", + harness: "claude-acp", + account: input().account, + } as never), + ).rejects.toThrow(); + expect(f.launches).toHaveLength(1); + }); + + test("corrupt account metadata remains readable but cannot become a default-account launch", async () => { + const f = fixture(); + const source = await f.caller().createAccountSession(input()); + await idle(f, source.sessionId); + await f.reopen(); + f.state.runtime.db + .update(chatSessionsLocal) + .set({ launchContextJson: "broken" }) + .where(eq(chatSessionsLocal.sessionId, source.sessionId)) + .run(); + const read = await f.caller().getSession({ sessionId: source.sessionId }); + expect(read.accountBound).toBe(true); + expect(read.account).toBeNull(); + await expect( + f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }), + ).rejects.toThrow("invalid"); + expect(f.launches).toHaveLength(1); + }); + + test("does not resend a saved queue during recovery", async () => { + const f = fixture(); + const source = await f.caller().createAccountSession(input()); + await idle(f, source.sessionId); + await f.reopen(); + f.state.runtime.journal.append(source.sessionId, { + type: "item", + turnId: "queued-turn", + item: { + id: "queued-message", + kind: "user_message", + content: [{ type: "text", text: "not sent" }], + startedAtMs: 1, + queued: true, + }, + }); + await f.reopen(); + const queue = await f.caller().getQueue({ sessionId: source.sessionId }); + expect(queue.live).toBe(false); + expect(queue.prompts.map((p) => p.itemId)).toEqual(["queued-message"]); + await expect( + f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }), + ).rejects.toThrow("unsent queued"); + expect(f.launches).toHaveLength(1); + await f.caller().removeQueuedPrompt({ + commandId: randomUUID(), + sessionId: source.sessionId, + itemId: "queued-message", + }); + expect( + (await f.caller().getQueue({ sessionId: source.sessionId })).prompts, + ).toEqual([]); + await f.reopen(); + expect( + (await f.caller().getQueue({ sessionId: source.sessionId })).prompts, + ).toEqual([]); + await f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }); + expect(f.launches).toHaveLength(2); + }); + + test("a source change during account validation refuses recovery", async () => { + let mutate: (() => void) | undefined; + const f = fixture({ validate: () => mutate?.() }); + const source = await f.caller().createAccountSession(input()); + await idle(f, source.sessionId); + await f.reopen(); + mutate = () => { + f.state.runtime.db + .update(chatSessionsLocal) + .set({ title: "changed" }) + .where(eq(chatSessionsLocal.sessionId, source.sessionId)) + .run(); + }; + await expect( + f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }), + ).rejects.toThrow("changed or was already resumed"); + expect(f.launches).toHaveLength(1); + }); + + for (const close of ["session", "scope"] as const) { + test(`recovery waits for ${close} disposal to actually finish`, async () => { + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const f = fixture({ beforeDispose: () => gate }); + const source = await f.caller().createAccountSession(input()); + await idle(f, source.sessionId); + const closing = + close === "scope" + ? f.state.runtime.commands.closeScope("workspace") + : f.state.runtime.commands.closeSession({ + sessionId: source.sessionId, + }); + try { + await expect( + f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }), + ).rejects.toThrow("still closing"); + expect(f.launches).toHaveLength(1); + } finally { + release?.(); + await closing; + } + await f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }); + expect(f.launches).toHaveLength(2); + }); + } + + test("native forks inherit the account and duplicate requests do not fork twice", async () => { + const f = fixture(); + const source = await f.caller().createAccountSession(input()); + await idle(f, source.sessionId); + const request = { + commandId: randomUUID(), + sessionId: source.sessionId, + workspaceId: "workspace", + }; + const [branch, concurrent] = await Promise.all([ + f.caller().forkSession(request), + f.caller().forkSession(request), + ]); + expect(concurrent).toEqual(branch); + expect(branch).not.toBeNull(); + expect(f.launches.at(-1)?.launchContext?.account).toEqual(ACCOUNT); + expect(f.launches.at(-1)?.resume).toEqual({ + harnessSessionId: "native-branch", + requireExact: true, + }); + expect(await f.caller().forkSession(request)).toEqual(branch); + expect(f.forks()).toBe(1); + await expect( + f.caller().forkSession({ + ...request, + commandId: randomUUID(), + harness: "codex-acp", + }), + ).rejects.toThrow("original agent"); + }); +}); + +describe("explicit failed account agent stop", () => { + async function dead(f: ReturnType, sessionId: string) { + await waitFor( + () => f.state.runtime.live.get(sessionId)?.state.status === "dead", + ); + } + + test("stops only the exact failed account agent and keeps its saved conversation", async () => { + const f = fixture({ initialStatus: "dead" }); + const source = await f.caller().createAccountSession(input()); + const other = await f.caller().createAccountSession(input()); + await dead(f, source.sessionId); + await dead(f, other.sessionId); + await f + .caller() + .closeStoppedAccountSession({ sessionId: source.sessionId }); + expect(f.state.runtime.live.get(source.sessionId)).toBeNull(); + expect(f.state.runtime.live.get(other.sessionId)).not.toBeNull(); + expect( + f.state.runtime.sessions.get(source.sessionId)?.harnessSessionId, + ).toBe(`native-${source.sessionId}`); + expect( + (await f.caller().getSession({ sessionId: source.sessionId })) + .accountBound, + ).toBe(true); + }); + + for (const initialStatus of ["idle", "running"] as const) { + test(`refuses a registered ${initialStatus} account agent`, async () => { + const f = fixture({ initialStatus }); + const source = await f.caller().createAccountSession(input()); + await waitFor( + () => + f.state.runtime.live.get(source.sessionId)?.state.status === + initialStatus, + ); + await expect( + f.caller().closeStoppedAccountSession({ sessionId: source.sessionId }), + ).rejects.toThrow("Only a failed"); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); + }); + } + + test("refuses legacy or corrupt context instead of using ordinary close", async () => { + const f = fixture({ initialStatus: "dead" }); + const source = await f.caller().createAccountSession(input()); + await dead(f, source.sessionId); + for (const launchContextJson of [null, "broken"]) { + f.state.runtime.db + .update(chatSessionsLocal) + .set({ launchContextJson }) + .where(eq(chatSessionsLocal.sessionId, source.sessionId)) + .run(); + await expect( + f.caller().closeStoppedAccountSession({ sessionId: source.sessionId }), + ).rejects.toThrow(); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); + } + }); + + test("refuses a durable unsent message without removing it", async () => { + const f = fixture({ initialStatus: "dead" }); + const source = await f.caller().createAccountSession(input()); + await dead(f, source.sessionId); + f.state.runtime.journal.append(source.sessionId, { + type: "item", + turnId: "queued-turn", + item: { + id: "queued-message", + kind: "user_message", + content: [{ type: "text", text: "keep this draft" }], + startedAtMs: 1, + queued: true, + }, + }); + await expect( + f.caller().closeStoppedAccountSession({ sessionId: source.sessionId }), + ).rejects.toThrow("unsent queued"); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); + expect(f.state.runtime.sessions.get(source.sessionId)?.queuedCount).toBe(1); + }); + + test("refuses the live queue even when the provider still reports dead", async () => { + const f = fixture({ initialStatus: "dead", allowPendingPrompt: true }); + const source = await f.caller().createAccountSession(input()); + await dead(f, source.sessionId); + const live = f.state.runtime.live.require(source.sessionId); + live.prompt([{ type: "text", text: "pending delivery" }], "fixture"); + const queued = live.prompt( + [{ type: "text", text: "keep queued" }], + "fixture", + ); + expect(queued.queued).toBe(true); + await expect( + f.caller().closeStoppedAccountSession({ sessionId: source.sessionId }), + ).rejects.toThrow("unsent queued"); + expect(live.queueState.prompts.map((p) => p.itemId)).toEqual([ + queued.itemId, + ]); + }); + + test("keeps recovery blocked when provider disposal fails without confirming exit", async () => { + const f = fixture({ + initialStatus: "dead", + beforeDispose: async () => { + throw new Error("provider exit unconfirmed"); + }, + }); + const source = await f.caller().createAccountSession(input()); + await dead(f, source.sessionId); + await expect( + f.caller().closeStoppedAccountSession({ sessionId: source.sessionId }), + ).rejects.toThrow("provider exit unconfirmed"); + expect(f.state.runtime.live.isClosing(source.sessionId)).toBe(true); + await expect( + f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }), + ).rejects.toThrow("still closing"); + await expect( + f.caller().closeStoppedAccountSession({ sessionId: source.sessionId }), + ).rejects.toThrow("still closing"); + expect(f.launches).toHaveLength(1); + }); + + test("prevents enqueue and recovery until confirmed disposal finishes", async () => { + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + const f = fixture({ initialStatus: "dead", beforeDispose: () => gate }); + const source = await f.caller().createAccountSession(input()); + await dead(f, source.sessionId); + const closing = f.state.runtime.commands.closeStoppedAccountSession({ + sessionId: source.sessionId, + }); + try { + expect(f.state.runtime.live.isClosing(source.sessionId)).toBe(true); + expect(() => + f.state.runtime.commands.prompt({ + commandId: randomUUID(), + sessionId: source.sessionId, + clientId: "fixture", + content: [{ type: "text", text: "must not enqueue" }], + }), + ).toThrow("not running"); + await expect( + f.caller().recoverAccountSession({ + commandId: randomUUID(), + sessionId: source.sessionId, + }), + ).rejects.toThrow("still closing"); + await expect( + f.caller().closeStoppedAccountSession({ sessionId: source.sessionId }), + ).rejects.toThrow("still closing"); + } finally { + release?.(); + await closing; + } + expect(f.state.runtime.live.isClosing(source.sessionId)).toBe(false); + expect(f.state.runtime.sessions.get(source.sessionId)?.queuedCount).toBe(0); + }); +}); + +const TARGET: ChatLaunchAccount = { + ...ACCOUNT, + selection: "/fixture/account-b", + directory: "/fixture/account-b", + identity: "b".repeat(64), +}; +function switchInput(sessionId: string) { + return { + commandId: randomUUID(), + sessionId, + account: { selection: TARGET.selection, identity: TARGET.identity }, + }; +} + +describe("in-place account switch", () => { + test("an older host has no switching capability and leaves the source running", async () => { + const f = fixture({ initialMode: "ask" }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await idle(f, source.sessionId); + expect((await c.accountCapabilities()).accountSwitch).toBe(false); + await expect( + c.switchAccountSession(switchInput(source.sessionId)), + ).rejects.toThrow("does not support"); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); + expect(f.launches).toHaveLength(1); + }); + + test("reopens the exact native conversation, keeps other chats, and reconciles a lost reply", async () => { + let releases = 0; + const f = fixture({ + initialMode: "ask", + validIdentities: [ACCOUNT.identity, TARGET.identity], + switcher: async () => ({ + finish: async () => ({ account: TARGET, assertCurrent() {} }), + release() { + releases++; + }, + }), + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + const other = await c.createAccountSession(input()); + await idle(f, source.sessionId); + await idle(f, other.sessionId); + const request = switchInput(source.sessionId); + const switched = await c.switchAccountSession(request); + expect(switched.terminalId).toBe(source.terminalId); + expect(switched.sessionId).not.toBe(source.sessionId); + expect(f.state.runtime.live.get(source.sessionId)).toBeNull(); + expect(f.state.runtime.live.get(other.sessionId)).not.toBeNull(); + expect(f.launches.at(-1)?.resume).toEqual({ + harnessSessionId: `native-${source.sessionId}`, + requireExact: true, + }); + expect(f.launches.at(-1)?.launchContext?.account).toEqual(TARGET); + expect(f.launches.at(-1)?.modeId).toBe("ask"); + expect(await c.switchAccountSession(request)).toEqual(switched); + expect( + await c.accountSessionByCommand({ commandId: request.commandId }), + ).toEqual(switched); + expect(f.launches).toHaveLength(3); + expect(releases).toBe(1); + await f.reopen(); + const recovered = await f.caller().recoverAccountSession({ + sessionId: source.sessionId, + commandId: randomUUID(), + }); + expect(f.launches.at(-1)?.launchContext?.account).toEqual(TARGET); + expect(recovered.terminalId).toBe(source.terminalId); + }); + + test("a rejected destination does not close the source", async () => { + const f = fixture({ + initialMode: "ask", + switcher: async () => { + throw new Error("independent history"); + }, + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await idle(f, source.sessionId); + await expect( + c.switchAccountSession(switchInput(source.sessionId)), + ).rejects.toThrow("independent history"); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); + expect(f.launches).toHaveLength(1); + }); + + for (const stateExtras of [ + { status: "running" }, + { status: "awaiting_input" }, + { awaitingBackground: true }, + { + backgroundTasks: [ + { + id: "job", + kind: "process", + name: "server", + canStop: true, + startedAtMs: 1, + }, + ], + }, + ] as Partial[]) { + test(`refuses active or background work: ${JSON.stringify(stateExtras)}`, async () => { + let prepared = false; + const f = fixture({ + initialMode: "ask", + stateExtras, + switcher: async () => { + prepared = true; + throw new Error("unexpected preparation"); + }, + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await waitFor(() => + Boolean( + f.state.runtime.live.get(source.sessionId)?.state.harnessSessionId, + ), + ); + await expect( + c.switchAccountSession(switchInput(source.sessionId)), + ).rejects.toThrow("Finish active"); + expect(prepared).toBe(false); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); + }); + } + + test("rejects a changed source while destination checks are pending", async () => { + let release!: () => void; + let preparationStarted!: () => void; + const started = new Promise((resolve) => { + preparationStarted = resolve; + }); + const f = fixture({ + initialMode: "ask", + switcher: async () => { + preparationStarted(); + await new Promise((resolve) => { + release = resolve; + }); + return { + finish: async () => ({ account: TARGET, assertCurrent() {} }), + release() {}, + }; + }, + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await idle(f, source.sessionId); + const pending = c.switchAccountSession(switchInput(source.sessionId)); + await started; + f.state.runtime.db + .update(chatSessionsLocal) + .set({ launchContextJson: "broken" }) + .where(eq(chatSessionsLocal.sessionId, source.sessionId)) + .run(); + release(); + await expect(pending).rejects.toThrow("conversation changed"); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); + }); + + test("a post-exit verification failure preserves saved recovery and starts nothing else", async () => { + let releases = 0; + const f = fixture({ + initialMode: "ask", + switcher: async () => ({ + finish: async () => { + throw new Error("final history changed"); + }, + release() { + releases++; + }, + }), + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await idle(f, source.sessionId); + await expect( + c.switchAccountSession(switchInput(source.sessionId)), + ).rejects.toThrow("final history changed"); + expect(f.launches).toHaveLength(1); + expect(releases).toBe(1); + const recovered = await c.recoverAccountSession({ + sessionId: source.sessionId, + commandId: randomUUID(), + }); + expect(recovered.terminalId).toBe(source.terminalId); + expect(f.launches.at(-1)?.launchContext?.account).toEqual(ACCOUNT); + }); +}); + +test("a durable queued message prevents an account switch even if the live queue has not replayed it", async () => { + let prepared = false; + const f = fixture({ + initialMode: "ask", + switcher: async () => { + prepared = true; + throw new Error("unexpected"); + }, + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await idle(f, source.sessionId); + f.state.runtime.journal.append(source.sessionId, { + type: "item", + turnId: "queued-turn", + item: { + id: "queued-message", + kind: "user_message", + content: [{ type: "text", text: "not sent" }], + startedAtMs: 1, + queued: true, + }, + }); + await expect( + c.switchAccountSession(switchInput(source.sessionId)), + ).rejects.toThrow("queued messages"); + expect(prepared).toBe(false); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); +}); + +test("concurrent identical switches share one result and a second command cannot close the source", async () => { + let continuePreparation!: () => void; + let entered!: () => void; + let preparations = 0; + let releases = 0; + const started = new Promise((resolve) => { + entered = resolve; + }); + const f = fixture({ + initialMode: "ask", + switcher: async () => { + preparations++; + entered(); + await new Promise((resolve) => { + continuePreparation = resolve; + }); + return { + finish: async () => ({ account: TARGET, assertCurrent() {} }), + release() { + releases++; + }, + }; + }, + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await idle(f, source.sessionId); + const request = switchInput(source.sessionId); + const a = c.switchAccountSession(request); + const b = c.switchAccountSession(request); + await started; + await expect( + c.switchAccountSession(switchInput(source.sessionId)), + ).rejects.toThrow("already switching"); + continuePreparation(); + expect(await a).toEqual(await b); + expect(preparations).toBe(1); + expect(releases).toBe(1); + expect(f.launches).toHaveLength(2); +}); + +test("unknown exact-load support refuses the switch before touching the idle source", async () => { + let prepared = false; + const f = fixture({ + initialMode: "ask", + stateExtras: { exactResumeSupported: false }, + switcher: async () => { + prepared = true; + throw new Error("unexpected"); + }, + }); + const c = f.caller(); + const source = await c.createAccountSession(input()); + await idle(f, source.sessionId); + await expect( + c.switchAccountSession(switchInput(source.sessionId)), + ).rejects.toThrow("not confirmed exact"); + expect(prepared).toBe(false); + expect(f.state.runtime.live.get(source.sessionId)).not.toBeNull(); +}); diff --git a/packages/chat-runtime/src/router/router/router.ts b/packages/chat-runtime/src/router/router/router.ts index f190bf0536e..669784e400f 100644 --- a/packages/chat-runtime/src/router/router/router.ts +++ b/packages/chat-runtime/src/router/router/router.ts @@ -1,7 +1,12 @@ import { backgroundSubagentInputSchema, + type ChatAccountSelection, + type ChatLaunchAccount, + type ChatLaunchContext, cancelTurnInputSchema, closeSessionInputSchema, + closeStoppedAccountSessionInputSchema, + createAccountSessionInputSchema, createSessionInputSchema, discoverSessionsInputSchema, forkSessionInputSchema, @@ -12,25 +17,53 @@ import { listSessionsInputSchema, promptInputSchema, queuedPromptInputSchema, + recoverAccountSessionInputSchema, respondToApprovalInputSchema, resumeQueueInputSchema, rewindSessionInputSchema, + type SwitchAccountSessionInput, setConfigOptionInputSchema, setModeInputSchema, steerSubagentInputSchema, stopBackgroundTaskInputSchema, + switchAccountSessionInputSchema, } from "@superset/chat/protocol"; import type { inferRouterInputs, inferRouterOutputs } from "@trpc/server"; import { initTRPC, TRPCError } from "@trpc/server"; import { z } from "zod"; import type { ChatRuntime } from "../../index"; +import { + findAccountCommand, + findAccountSuccessor, + readLaunchContext, +} from "../../projection/launchContext"; const t = initTRPC.create(); export const createChatCallerFactory = t.createCallerFactory; +export type PrepareAccountSwitchInput = { + harness: string; + account: ChatAccountSelection; + cwd: string; + scopeId: string; + harnessSessionId: string; + source: ChatLaunchContext; +}; + export type ChatRouterOptions = { + prepareAccountSwitch?(input: PrepareAccountSwitchInput): Promise<{ + finish(): Promise<{ account: ChatLaunchAccount; assertCurrent(): void }>; + release(): void; + }>; resolveCwd(workspaceId: string): string | Promise; + accountHarnesses?: readonly string[]; + prepareAccount?(input: { + harness: string; + account: ChatAccountSelection; + cwd: string; + scopeId: string; + }): Promise; }; const UNKNOWN_HARNESS = /^unknown harness /; @@ -83,9 +116,358 @@ export function createChatRouter( } } + const switching = new Map< + string, + { + input: string; + promise: Promise<{ + sessionId: string; + epoch: string; + terminalId: string; + }>; + } + >(); + const claimed = new Set(); + const refuseSwitch = (message: string): never => { + throw new TRPCError({ code: "PRECONDITION_FAILED", message }); + }; + async function switchAccount(input: SwitchAccountSessionInput) { + if (!options.prepareAccountSwitch) + return refuseSwitch( + "This host does not support switching chat accounts safely.", + ); + const receipt = findAccountCommand(runtime.db, input.commandId); + if (receipt) { + const saved = readLaunchContext(receipt); + if ( + !saved || + receipt.predecessorSessionId !== input.sessionId || + saved.switchOfSessionId !== input.sessionId || + saved.account.selection !== input.account.selection || + saved.account.identity !== input.account.identity + ) + throw new TRPCError({ + code: "CONFLICT", + message: + "This command already belongs to another conversation or account.", + }); + return { + sessionId: receipt.sessionId, + epoch: receipt.epoch, + terminalId: saved.terminalId, + }; + } + // Repair the native-id projection before taking the immutable source snapshot. + runtime.commands.getSession({ sessionId: input.sessionId }); + const source = runtime.sessions.get(input.sessionId); + const context = source ? readLaunchContext(source) : null; + if ( + !source || + !context || + !source.harnessSessionId || + !options.accountHarnesses?.includes(source.harness) + ) + return refuseSwitch( + "The saved conversation and its account could not be verified.", + ); + const live = runtime.live.get(source.sessionId); + if ( + !live || + live.state.harnessSessionId !== source.harnessSessionId || + live.terminalId !== context.terminalId + ) + return refuseSwitch( + "Resume this conversation with its saved account before switching accounts.", + ); + const claim = `${source.harness}:${source.harnessSessionId}`; + if (claimed.has(claim)) + throw new TRPCError({ + code: "CONFLICT", + message: "This conversation is already switching accounts.", + }); + claimed.add(claim); + let preparation: + | Awaited< + ReturnType> + > + | undefined; + try { + const original = JSON.stringify([ + source.epoch, + source.scopeId, + source.harness, + source.harnessSessionId, + source.launchContextJson, + ]); + const assertSource = (running: boolean) => { + const current = runtime.sessions.get(source.sessionId); + if ( + !current || + JSON.stringify([ + current.epoch, + current.scopeId, + current.harness, + current.harnessSessionId, + current.launchContextJson, + ]) !== original || + findAccountSuccessor(runtime.db, source.sessionId) || + runtime.live.isClosing(source.sessionId) || + runtime.live.get(source.sessionId) !== (running ? live : null) + ) + return refuseSwitch( + "The conversation changed or was already resumed. Nothing else was restarted.", + ); + if ( + current.queuedCount > 0 || + runtime.commands.getQueue({ sessionId: source.sessionId }).prompts + .length + ) + refuseSwitch( + "Review and remove queued messages before switching accounts.", + ); + if ( + running && + (live.state.status !== "idle" || + live.turn?.status === "running" || + live.unfinished() !== null || + live.state.awaitingBackground || + (live.state.backgroundTasks?.length ?? 0) > 0) + ) + refuseSwitch( + "Finish active tools, background work and questions before switching accounts.", + ); + }; + assertSource(true); + if (live.state.exactResumeSupported !== true) + return refuseSwitch( + "This agent has not confirmed exact conversation recovery. Nothing was restarted.", + ); + const cwd = await options.resolveCwd(source.scopeId); + if (cwd !== context.cwd) + return refuseSwitch( + "The conversation's working folder changed. Nothing was restarted.", + ); + preparation = await options.prepareAccountSwitch({ + harness: source.harness, + account: input.account, + cwd, + scopeId: source.scopeId, + harnessSessionId: source.harnessSessionId, + source: context, + }); + if ((await options.resolveCwd(source.scopeId)) !== cwd) + return refuseSwitch( + "The conversation's working folder changed. Nothing was restarted.", + ); + assertSource(true); + const modeId = live.state.modeId; + const modelId = live.state.modelId; + if (!modeId) + return refuseSwitch( + "The current permission mode is unknown. Nothing was restarted.", + ); + // closeSession removes the idle source synchronously before its first await. + await runtime.commands.closeSession({ sessionId: source.sessionId }); + const prepared = await preparation.finish(); + if ( + prepared.account.selection !== input.account.selection || + prepared.account.identity !== input.account.identity || + prepared.account.agent !== context.account.agent + ) + return refuseSwitch( + "The selected account changed. The saved conversation remains recoverable.", + ); + if ((await options.resolveCwd(source.scopeId)) !== cwd) + return refuseSwitch( + "The conversation's working folder changed. The saved conversation remains recoverable.", + ); + assertSource(false); + prepared.assertCurrent(); + const created = runtime.commands.createSession({ + commandId: input.commandId, + scopeId: source.scopeId, + harness: source.harness, + cwd, + terminalId: context.terminalId, + modeId, + ...(modelId ? { modelId } : {}), + predecessorSessionId: source.sessionId, + resume: { + harnessSessionId: source.harnessSessionId, + requireExact: true, + }, + launchContext: { + ...context, + account: prepared.account, + initialModeId: modeId, + initialModelId: modelId, + switchOfSessionId: source.sessionId, + }, + }); + return { ...created, terminalId: context.terminalId }; + } finally { + preparation?.release(); + claimed.delete(claim); + } + } + return t.router({ + accountSessionByCommand: t.procedure + .input(z.strictObject({ commandId: z.uuid() })) + .query(({ input }) => { + const row = findAccountCommand(runtime.db, input.commandId); + if (!row) return null; + const context = readLaunchContext(row); + if (!context) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: "The saved chat account is unavailable.", + }); + return { + sessionId: row.sessionId, + epoch: row.epoch, + terminalId: context.terminalId, + }; + }), + accountCapabilities: t.procedure.query(() => ({ + version: 1 as const, + accountSwitch: Boolean(options.prepareAccountSwitch), + harnesses: options.prepareAccount + ? [...(options.accountHarnesses ?? [])] + : [], + })), + + createAccountSession: t.procedure + .input(createAccountSessionInputSchema) + .mutation(async ({ input }) => { + if ( + !options.prepareAccount || + !options.accountHarnesses?.includes(input.harness) + ) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "This host does not support account selection for this chat agent.", + }); + const receipt = findAccountCommand(runtime.db, input.commandId); + if (receipt) { + const context = readLaunchContext(receipt); + if ( + !context || + context.forkOfSessionId !== undefined || + receipt.predecessorSessionId !== null || + receipt.scopeId !== input.workspaceId || + receipt.harness !== input.harness || + context.account.selection !== input.account.selection || + context.account.identity !== input.account.identity || + context.initialModeId !== input.modeId || + context.initialModelId !== input.modelId + ) + throw new TRPCError({ + code: "CONFLICT", + message: + "This command already belongs to another conversation or account.", + }); + return { + sessionId: receipt.sessionId, + epoch: receipt.epoch, + terminalId: context.terminalId as string, + }; + } + const cwd = await options.resolveCwd(input.workspaceId); + const account = await options.prepareAccount({ + harness: input.harness, + account: input.account, + cwd, + scopeId: input.workspaceId, + }); + if ( + account.selection !== input.account.selection || + account.identity !== input.account.identity + ) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: "The selected chat account changed. Nothing was launched.", + }); + const concurrent = findAccountCommand(runtime.db, input.commandId); + if (concurrent) { + const context = readLaunchContext(concurrent); + if ( + !context || + context.forkOfSessionId !== undefined || + concurrent.predecessorSessionId !== null || + concurrent.scopeId !== input.workspaceId || + concurrent.harness !== input.harness || + context.account.selection !== input.account.selection || + context.account.identity !== input.account.identity || + context.initialModeId !== input.modeId || + context.initialModelId !== input.modelId + ) + throw new TRPCError({ + code: "CONFLICT", + message: + "This command already belongs to another conversation or account.", + }); + return { + sessionId: concurrent.sessionId, + epoch: concurrent.epoch, + terminalId: context.terminalId, + }; + } + const terminalId = crypto.randomUUID(); + const created = guarded(() => + runtime.commands.createSession({ + commandId: input.commandId, + scopeId: input.workspaceId, + harness: input.harness, + cwd, + terminalId, + modeId: input.modeId, + modelId: input.modelId, + launchContext: { + v: 1, + cwd, + terminalId, + account, + initialModeId: input.modeId, + initialModelId: input.modelId, + }, + }), + ); + return { ...created, terminalId }; + }), + + switchAccountSession: t.procedure + .input(switchAccountSessionInputSchema) + .mutation(({ input }) => { + const signature = JSON.stringify(input); + const prior = switching.get(input.commandId); + if (prior) { + if (prior.input !== signature) + throw new TRPCError({ + code: "CONFLICT", + message: "This command already belongs to another account.", + }); + return prior.promise; + } + const promise = switchAccount(input).finally(() => + switching.delete(input.commandId), + ); + switching.set(input.commandId, { input: signature, promise }); + return promise; + }), + + recoverAccountSession: t.procedure + .input(recoverAccountSessionInputSchema) + .mutation(({ input }) => runtime.commands.recoverAccountSession(input)), + createSession: t.procedure - .input(createSessionInputSchema) + .input( + createSessionInputSchema.extend({ + account: z.never().optional(), + launchContext: z.never().optional(), + }), + ) .mutation(async ({ input }) => { const { workspaceId, ...rest } = input; const cwd = await options.resolveCwd(workspaceId); @@ -183,6 +565,11 @@ export function createChatRouter( const cwd = await options.resolveCwd(workspaceId); return guarded(() => runtime.commands.rewindSession({ ...rest, cwd })); }), + closeStoppedAccountSession: t.procedure + .input(closeStoppedAccountSessionInputSchema) + .mutation(({ input }) => + runtime.commands.closeStoppedAccountSession(input), + ), closeSession: t.procedure .input(closeSessionInputSchema) diff --git a/packages/chat-runtime/src/sessions/liveSession/liveSession.test.ts b/packages/chat-runtime/src/sessions/liveSession/liveSession.test.ts index d55840e0a86..9646d83a9ea 100644 --- a/packages/chat-runtime/src/sessions/liveSession/liveSession.test.ts +++ b/packages/chat-runtime/src/sessions/liveSession/liveSession.test.ts @@ -23,7 +23,10 @@ import { waitFor, } from "../../testing/testUtils"; -function startSession(script: FakeHarnessScript): { +function startSession( + script: FakeHarnessScript, + accountBound = false, +): { runtime: ChatRuntime; sessionId: string; } { @@ -34,6 +37,22 @@ function startSession(script: FakeHarnessScript): { scopeId: "workspace-1", harness: FAKE_HARNESS, cwd: "/tmp/workspace", + ...(accountBound + ? { + terminalId: "account-pane", + launchContext: { + v: 1 as const, + cwd: "/tmp/workspace", + terminalId: "account-pane", + account: { + agent: "claude" as const, + selection: "/fixture/account", + directory: "/fixture/account", + identity: "a".repeat(64), + }, + }, + } + : {}), }); return { runtime, sessionId }; } @@ -580,11 +599,17 @@ describe("LiveSession", () => { await runtime.dispose(); }); - test("a queued prompt whose steer is refused still runs next", async () => { - const { runtime, sessionId } = startSession({ - ...GATED_THEN_QUICK, - steer: false, - }); + test.each([ + false, + true, + ])("a queued prompt whose steer is refused still runs next (account bound: %s)", async (accountBound) => { + const { runtime, sessionId } = startSession( + { + ...GATED_THEN_QUICK, + steer: false, + }, + accountBound, + ); sendPrompt(runtime, sessionId, "first"); const second = sendPrompt(runtime, sessionId, "second"); const third = sendPrompt(runtime, sessionId, "third"); @@ -682,8 +707,11 @@ describe("LiveSession", () => { await runtime.dispose(); }); - test("steerQueuedPrompt interrupts the turn and delivers that prompt next", async () => { - const { runtime, sessionId } = startSession(GATED_THEN_QUICK); + test.each([ + false, + true, + ])("steerQueuedPrompt interrupts the turn and delivers that prompt next (account bound: %s)", async (accountBound) => { + const { runtime, sessionId } = startSession(GATED_THEN_QUICK, accountBound); sendPrompt(runtime, sessionId, "first"); await waitForApproval(runtime, sessionId); const second = sendPrompt(runtime, sessionId, "second"); @@ -713,8 +741,11 @@ describe("LiveSession", () => { await runtime.dispose(); }); - test("a prompt sent with steer for the running turn interrupts it and runs next", async () => { - const { runtime, sessionId } = startSession(GATED_THEN_QUICK); + test.each([ + false, + true, + ])("a prompt sent with steer for the running turn interrupts it and runs next (account bound: %s)", async (accountBound) => { + const { runtime, sessionId } = startSession(GATED_THEN_QUICK, accountBound); sendPrompt(runtime, sessionId, "first"); await waitForApproval(runtime, sessionId); const second = sendPrompt(runtime, sessionId, "second"); @@ -891,8 +922,11 @@ describe("LiveSession", () => { await runtime.dispose(); }); - test("cancelTurn without pauseQueue keeps sending the queue", async () => { - const { runtime, sessionId } = startSession(GATED_THEN_QUICK); + test.each([ + false, + true, + ])("cancelTurn without pauseQueue keeps sending the queue (account bound: %s)", async (accountBound) => { + const { runtime, sessionId } = startSession(GATED_THEN_QUICK, accountBound); sendPrompt(runtime, sessionId, "first"); await waitForApproval(runtime, sessionId); const second = sendPrompt(runtime, sessionId, "second"); @@ -981,6 +1015,113 @@ describe("LiveSession", () => { await runtime.dispose(); }); + test("an account-bound failed turn publishes its paused queue and resumes only on request", async () => { + const { runtime, sessionId } = startSession( + { + turns: [ + [ + { kind: "turn", turn: turn("t1") }, + { kind: "item", item: approvalRequest("ap1"), turnId: "t1" }, + { + kind: "turn", + turn: turn("t1", { status: "failed", completedAtMs: 2 }), + }, + { kind: "session", session: { status: "idle" } }, + ], + [ + { kind: "turn", turn: turn("t2") }, + { + kind: "turn", + turn: turn("t2", { status: "completed", completedAtMs: 3 }), + }, + { kind: "session", session: { status: "idle" } }, + ], + ], + }, + true, + ); + try { + sendPrompt(runtime, sessionId, "first"); + await waitForApproval(runtime, sessionId); + const pending = sendPrompt(runtime, sessionId, "second"); + runtime.commands.respondToApproval({ + commandId: randomUUID(), + sessionId, + approvalId: "ap1", + decision: { type: "accept" }, + }); + const latest = () => + reduceMany(emptySnapshot(), journalEnvelopes(runtime, sessionId)); + await waitFor(() => latest().session?.status === "idle"); + expect(latest().session?.queuePaused).toBe(true); + expect(runtime.commands.getQueue({ sessionId })).toMatchObject({ + paused: true, + prompts: [{ itemId: pending.itemId }], + }); + runtime.commands.resumeQueue({ commandId: randomUUID(), sessionId }); + await waitFor(() => latest().items.get(pending.itemId)?.turnId === "t2"); + expect(latest().session?.queuePaused).toBe(false); + } finally { + await runtime.dispose(); + } + }); + + test("an account-bound agent crash keeps unsent messages for explicit review", async () => { + const { runtime, sessionId } = startSession( + { + turns: [ + [ + { kind: "turn", turn: turn("t1") }, + { + kind: "turn", + turn: turn("t1", { status: "failed", completedAtMs: 2 }), + delayMs: 1, + }, + { kind: "session", session: { status: "dead" } }, + ], + ], + }, + true, + ); + sendPrompt(runtime, sessionId, "first"); + const pending = sendPrompt(runtime, sessionId, "second"); + await waitFor(() => runtime.sessions.get(sessionId)?.status === "dead"); + expect( + runtime.commands + .getQueue({ sessionId }) + .prompts.map((item) => item.itemId), + ).toEqual([pending.itemId]); + await runtime.commands.closeSession({ sessionId }); + const stored = runtime.commands.getQueue({ sessionId }); + expect(stored.live).toBe(false); + expect(stored.prompts.map((item) => item.itemId)).toEqual([pending.itemId]); + runtime.commands.removeQueuedPrompt({ + sessionId, + itemId: pending.itemId, + commandId: randomUUID(), + }); + expect(runtime.commands.getQueue({ sessionId }).prompts).toEqual([]); + await runtime.dispose(); + }); + + test("closing an account-bound session keeps its unsent queue", async () => { + const { runtime, sessionId } = startSession(GATED_THEN_QUICK, true); + sendPrompt(runtime, sessionId, "first"); + await waitForApproval(runtime, sessionId); + const pending = sendPrompt(runtime, sessionId, "second"); + await runtime.commands.closeSession({ sessionId }); + expect( + reduceMany(emptySnapshot(), journalEnvelopes(runtime, sessionId)).session + ?.queuePaused, + ).toBe(true); + expect( + runtime.commands + .getQueue({ sessionId }) + .prompts.map((item) => item.itemId), + ).toEqual([pending.itemId]); + await runtime.dispose(); + }); + test("queue commands reject a prompt that is not queued", async () => { const { runtime, sessionId } = startSession(SINGLE_TURN); expect(() => diff --git a/packages/chat-runtime/src/sessions/liveSession/liveSession.ts b/packages/chat-runtime/src/sessions/liveSession/liveSession.ts index 6b812ae4506..5621947f3a8 100644 --- a/packages/chat-runtime/src/sessions/liveSession/liveSession.ts +++ b/packages/chat-runtime/src/sessions/liveSession/liveSession.ts @@ -23,6 +23,7 @@ export type LiveSessionOptions = { scopeId: string; harness: string; terminalId?: string; + retainQueuedOnStop?: boolean; journal: ChatJournal; publish: (envelope: Envelope) => void; adapter: HarnessAdapter; @@ -392,7 +393,7 @@ export class LiveSession { async dispose(): Promise { this.stopped = true; - this.discardPending(); + this.settlePendingOnStop(); await this.options.adapter.dispose(); await this.pump; } @@ -426,6 +427,13 @@ export class LiveSession { if (steered && this.queue[0]?.item.id === steered) { this.options.adapter.cancelTurn(); } + } else if ( + this.options.retainQueuedOnStop && + event.turn.status === "failed" && + this.steerTarget === null && + this.queue.length > 0 + ) { + this.pauseQueue(); } else { this.noteSilentTurn(event.turn); this.deliverNextQueued(); @@ -433,7 +441,7 @@ export class LiveSession { return; } case "session": - if (event.session.status === "dead") this.discardPending(); + if (event.session.status === "dead") this.settlePendingOnStop(); this.emitSession(event.session); this.releaseHeldPrompts(); if (event.session.awaitingBackground) this.steerQueueIntoHeldTurn(); @@ -606,7 +614,7 @@ export class LiveSession { }; this.appendDurable({ type: "turn", turn: this.currentTurn }); } - this.discardPending(); + this.settlePendingOnStop(); this.appendDurable({ type: "item", item: { @@ -630,6 +638,16 @@ export class LiveSession { }); } + private settlePendingOnStop(): void { + const retained = this.options.retainQueuedOnStop + ? this.queue.splice(0) + : []; + this.discardPending(); + this.queue.push(...retained); + if (this.options.retainQueuedOnStop && this.queue.length > 0) + this.pauseQueue(); + } + private discardPending(): void { const pending = [ ...(this.awaitingTurn?.item.queued ? [this.awaitingTurn] : []), @@ -656,6 +674,12 @@ export class LiveSession { this.deliver(next); } + private pauseQueue(): void { + if (this.queuePaused) return; + this.queuePaused = true; + this.emitSession({ queuePaused: true }); + } + private unpauseIfEmpty(): void { if (!this.queuePaused || this.queue.length > 0) return; this.queuePaused = false; diff --git a/packages/chat-runtime/src/sessions/registry/registry.ts b/packages/chat-runtime/src/sessions/registry/registry.ts index 2c3d7f4b384..6d6ad68731a 100644 --- a/packages/chat-runtime/src/sessions/registry/registry.ts +++ b/packages/chat-runtime/src/sessions/registry/registry.ts @@ -1,5 +1,9 @@ import { randomUUID } from "node:crypto"; -import type { DiscoverSessionsResult, Envelope } from "@superset/chat/protocol"; +import type { + ChatLaunchContext, + DiscoverSessionsResult, + Envelope, +} from "@superset/chat/protocol"; import type { DiscoverNativeSessionsInput, HarnessAdapter, @@ -15,8 +19,13 @@ export type HarnessFactoryOptions = { cwd: string; modeId?: string; modelId?: string; - resume?: { harnessSessionId: string; quiet?: boolean }; + resume?: { + harnessSessionId: string; + quiet?: boolean; + requireExact?: boolean; + }; terminalId?: string; + launchContext?: ChatLaunchContext; }; export type HarnessFactory = (options: HarnessFactoryOptions) => HarnessAdapter; @@ -40,6 +49,7 @@ export type LiveSessionRegistryOptions = { export class LiveSessionRegistry { private readonly live = new Map(); + private readonly closing = new Set(); constructor(private readonly options: LiveSessionRegistryOptions) {} @@ -108,6 +118,7 @@ export class LiveSessionRegistry { scopeId: options.scopeId, harness: options.harness, terminalId: options.terminalId, + retainQueuedOnStop: options.launchContext !== undefined, journal: this.options.journal, publish: (envelope) => { this.options.publish(envelope); @@ -147,6 +158,10 @@ export class LiveSessionRegistry { return this.live.get(sessionId) ?? null; } + isClosing(sessionId: string): boolean { + return this.closing.has(sessionId); + } + require(sessionId: string): LiveSession { const session = this.live.get(sessionId); if (!session) throw new Error(`chat session ${sessionId} is not running`); @@ -163,9 +178,11 @@ export class LiveSessionRegistry { async dispose(sessionId: string): Promise { const session = this.live.get(sessionId); if (!session) return; + this.closing.add(sessionId); this.live.delete(sessionId); this.observe(() => this.options.observer?.stopped(sessionId)); await session.dispose(); + this.closing.delete(sessionId); } async disposeAll(): Promise { @@ -180,12 +197,18 @@ export class LiveSessionRegistry { matches: (session: LiveSession) => boolean, ): Promise { const sessions = [...this.live.values()].filter(matches); - for (const session of sessions) this.live.delete(session.sessionId); + for (const session of sessions) { + this.closing.add(session.sessionId); + this.live.delete(session.sessionId); + } for (const session of sessions) { this.observe(() => this.options.observer?.stopped(session.sessionId)); } const results = await Promise.allSettled( - sessions.map((session) => session.dispose()), + sessions.map(async (session) => { + await session.dispose(); + this.closing.delete(session.sessionId); + }), ); const failure = results.find((result) => result.status === "rejected"); if (failure?.status === "rejected") throw failure.reason; diff --git a/packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.test.tsx b/packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.test.tsx new file mode 100644 index 00000000000..7a46b6fc964 --- /dev/null +++ b/packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.test.tsx @@ -0,0 +1,326 @@ +import { afterAll, afterEach, expect, mock, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import type { LexicalEditor } from "lexical"; +import type { ComposerBodyProps } from "./ComposerBody"; + +const alreadyRegistered = GlobalRegistrator.isRegistered; +if (!alreadyRegistered) GlobalRegistrator.register(); +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +mock.module("@lingui/react/macro", () => ({ + Trans: ({ children }: { children?: unknown }) => children, + useLingui: () => ({ + t: ({ message }: { message: string }) => message, + }), +})); + +const { act, cleanup, fireEvent, render } = await import( + "@testing-library/react" +); +const { useEffect } = await import("react"); +const { LexicalComposer } = await import("@lexical/react/LexicalComposer"); +const { useLexicalComposerContext } = await import( + "@lexical/react/LexicalComposerContext" +); +const { + $createParagraphNode, + $createTextNode, + $getRoot, + $isElementNode, + KEY_ARROW_DOWN_COMMAND, + KEY_ARROW_UP_COMMAND, + KEY_ENTER_COMMAND, +} = await import("lexical"); +const { MentionChipNode } = await import("../../nodes/mentionChipNode"); +const { ComposerBody } = await import("./ComposerBody"); + +function EditorProbe({ + onEditor, +}: { + onEditor: (editor: LexicalEditor) => void; +}) { + const [editor] = useLexicalComposerContext(); + useEffect(() => onEditor(editor), [editor, onEditor]); + return null; +} + +async function setup( + onSubmit: ComposerBodyProps["onSubmit"], + { history }: Pick = {}, +) { + let editor: LexicalEditor | undefined; + const view = render( + { + throw error; + }, + }} + > + { + editor = value; + }} + /> + + , + ); + const currentEditor = editor; + if (!currentEditor) throw new Error("Editor did not mount"); + const write = async (text: string, chip = false) => { + await act(async () => { + currentEditor.update( + () => { + const paragraph = $createParagraphNode(); + paragraph.append($createTextNode(text)); + if (chip) + paragraph.append( + MentionChipNode.fromChip({ + label: "Example file", + serialized: "@example.ts", + data: { path: "example.ts" }, + }), + ); + $getRoot().clear().append(paragraph); + }, + { discrete: true }, + ); + }); + }; + const attach = (file: File) => { + const input = + view.container.querySelector("input[type=file]"); + if (!input) throw new Error("File input did not mount"); + fireEvent.change(input, { target: { files: [file] } }); + }; + await write("Review the file"); + return { + ...view, + editor: currentEditor, + write, + attach, + text: () => + currentEditor.getEditorState().read(() => $getRoot().getTextContent()), + submit: () => + fireEvent.click(view.getByRole("button", { name: "Send message" })), + }; +} + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: Error) => void; + const promise = new Promise((onResolve, onReject) => { + resolve = onResolve; + reject = onReject; + }); + return { promise, resolve, reject }; +} + +afterEach(cleanup); +afterAll(async () => { + if (!alreadyRegistered) await GlobalRegistrator.unregister(); +}); + +test("keeps the full draft and attachment while submission is pending", async () => { + const pending = deferred(); + const view = await setup(() => pending.promise); + view.attach(new File(["fixture"], "review.txt")); + view.submit(); + await act(async () => {}); + try { + expect(view.text()).toBe("Review the file"); + expect(view.getByText("review.txt")).toBeTruthy(); + } finally { + await act(async () => pending.resolve()); + } +}); + +test("does not submit twice while acceptance is pending", async () => { + const pending = deferred(); + const onSubmit = mock(() => pending.promise); + const view = await setup(onSubmit); + view.submit(); + await view.write("Another draft"); + view.submit(); + await act(async () => pending.resolve()); + expect(onSubmit).toHaveBeenCalledTimes(1); +}); + +test("ignores another Enter key while submission is pending", async () => { + const pending = deferred(); + const onSubmit = mock(() => pending.promise); + const view = await setup(onSubmit); + view.submit(); + await view.write("Another draft"); + await act(async () => { + view.editor.dispatchCommand( + KEY_ENTER_COMMAND, + new KeyboardEvent("keydown", { key: "Enter" }), + ); + }); + await act(async () => pending.resolve()); + expect(onSubmit).toHaveBeenCalledTimes(1); + expect(view.text()).toBe("Another draft"); +}); + +test("keeps a draft when submission returns false", async () => { + const view = await setup(() => false); + view.submit(); + await act(async () => {}); + expect(view.text()).toBe("Review the file"); +}); + +test("keeps text and files when asynchronous submission declines", async () => { + const view = await setup(async () => false); + view.attach(new File(["fixture"], "review.txt")); + view.submit(); + await act(async () => {}); + expect(view.text()).toBe("Review the file"); + expect(view.getByText("review.txt")).toBeTruthy(); +}); + +test("handles rejected submission and leaves the draft available for a manual retry", async () => { + const pending = deferred(); + const onSubmit = mock(() => pending.promise); + const view = await setup(onSubmit); + view.attach(new File(["fixture"], "review.txt")); + view.submit(); + await act(async () => pending.reject(new Error("Transport unavailable"))); + expect(view.text()).toBe("Review the file"); + expect(view.getByText("review.txt")).toBeTruthy(); + expect(onSubmit).toHaveBeenCalledTimes(1); +}); + +test("clears an accepted unchanged draft and its attachments", async () => { + const pending = deferred(); + const view = await setup(() => pending.promise); + view.attach(new File(["fixture"], "review.txt")); + view.submit(); + await act(async () => pending.resolve()); + expect(view.text()).toBe(""); + expect(view.queryByText("review.txt")).toBeNull(); +}); + +test("preserves new Lexical chips, text and files after an earlier send succeeds", async () => { + const pending = deferred(); + const view = await setup(() => pending.promise); + view.attach(new File(["old"], "review.txt")); + view.submit(); + await view.write("Next task ", true); + view.attach(new File(["new"], "next.txt")); + await act(async () => pending.resolve()); + expect(view.text()).toBe("Next task @example.ts"); + expect(view.getByText("Example file")).toBeTruthy(); + expect(view.getByText("next.txt")).toBeTruthy(); + expect(view.queryByText("review.txt")).toBeNull(); +}); + +test("preserves a draft edited back to its original text while pending", async () => { + const pending = deferred(); + const view = await setup(() => pending.promise); + view.submit(); + await view.write("Different draft"); + await view.write("Review the file"); + await act(async () => pending.resolve()); + expect(view.text()).toBe("Review the file"); +}); + +test("preserves the newer draft saved by history navigation while a send is pending", async () => { + const pending = deferred(); + const view = await setup(() => pending.promise, { + history: ["Earlier question"], + }); + view.submit(); + await view.write("Next task draft"); + await act(async () => { + view.editor.update( + () => { + $getRoot().selectStart(); + view.editor.dispatchCommand(KEY_ARROW_UP_COMMAND, null); + }, + { discrete: true }, + ); + }); + expect(view.text()).toBe("Earlier question"); + await act(async () => pending.resolve()); + await act(async () => { + view.editor.update( + () => { + $getRoot().selectEnd(); + view.editor.dispatchCommand(KEY_ARROW_DOWN_COMMAND, null); + }, + { discrete: true }, + ); + }); + expect(view.text()).toBe("Next task draft"); +}); + +test("selection changes do not keep an otherwise accepted unchanged draft", async () => { + const pending = deferred(); + const view = await setup(() => pending.promise); + view.submit(); + await act(async () => { + view.editor.update(() => $getRoot().selectStart(), { discrete: true }); + }); + await act(async () => pending.resolve()); + expect(view.text()).toBe(""); +}); + +test("flushes a pending Lexical edit before deciding whether to clear it", async () => { + const pending = deferred(); + const view = await setup(() => pending.promise); + view.submit(); + await act(async () => { + pending.resolve(); + view.editor.update(() => { + const paragraph = $getRoot().getFirstChildOrThrow(); + if (!$isElementNode(paragraph)) throw new Error("Expected a paragraph"); + paragraph.append($createTextNode(" with more context")); + }); + }); + expect(view.text()).toBe("Review the file with more context"); +}); + +test("submission exposes the flushed content revision used for draft clearing", async () => { + const pending = deferred(); + let isDraftUnchanged: (() => boolean) | undefined; + const view = await setup((payload) => { + isDraftUnchanged = payload.isDraftUnchanged; + return pending.promise; + }); + await view.write("@example.ts"); + view.submit(); + expect(isDraftUnchanged?.()).toBe(true); + await act(async () => { + view.editor.update(() => $getRoot().selectStart(), { discrete: true }); + }); + expect(isDraftUnchanged?.()).toBe(true); + await act(async () => { + view.editor.update(() => { + const paragraph = $getRoot().getFirstChildOrThrow(); + if (!$isElementNode(paragraph)) throw new Error("Expected a paragraph"); + paragraph.clear().append( + MentionChipNode.fromChip({ + label: "Example file", + serialized: "@example.ts", + }), + ); + }); + expect(isDraftUnchanged?.()).toBe(false); + }); + await act(async () => pending.resolve()); + expect(view.text()).toBe("@example.ts"); + expect(view.getByText("Example file")).toBeTruthy(); +}); diff --git a/packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.tsx b/packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.tsx index 5bc1db83d86..5908acfe2ee 100644 --- a/packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.tsx +++ b/packages/chat-ui/src/components/PromptInput/components/ComposerBody/ComposerBody.tsx @@ -201,17 +201,20 @@ export function ComposerBody({ }: ComposerBodyProps) { const { t } = useLingui(); const [editor] = useLexicalComposerContext(); + const draftRevision = useRef(0); const onChangeRef = useRef(onChange); onChangeRef.current = onChange; const pasted = usePastedTexts(editor, { enabled: Boolean(collapseLargePastes), - onCardsChange: (cards, editorText) => + onCardsChange: (cards, editorText) => { + draftRevision.current += 1; onChangeRef.current?.( appendPastedText( editorText, cards.map((card) => card.text), ), - ), + ); + }, }); const { cardsRef } = pasted; const draftText = useCallback( @@ -285,6 +288,8 @@ export function ComposerBody({ [draftText, editor, focusAtEnd, pasted.restore, splitPastes], ); const [attachments, setAttachments] = useState([]); + const [isSubmitting, setIsSubmitting] = useState(false); + const submitting = useRef(false); const [isEmpty, setIsEmpty] = useState(true); const [dragging, setDragging] = useState(false); const [mentionQuery, setMentionQuery] = useState(null); @@ -367,10 +372,15 @@ export function ComposerBody({ useEffect( () => - editor.registerUpdateListener(({ editorState }) => { - const text = editorState.read(() => $getRoot().getTextContent()); - onChangeRef.current?.(draftText(text)); - }), + editor.registerUpdateListener( + ({ editorState, dirtyElements, dirtyLeaves }) => { + if (dirtyElements.size > 0 || dirtyLeaves.size > 0) { + draftRevision.current += 1; + } + const text = editorState.read(() => $getRoot().getTextContent()); + onChangeRef.current?.(draftText(text)); + }, + ), [draftText, editor], ); @@ -507,7 +517,8 @@ export function ComposerBody({ if (attachment.previewUrl) URL.revokeObjectURL(attachment.previewUrl); }; - const submit = ({ steer = false }: { steer?: boolean } = {}) => { + const submit = async ({ steer = false }: { steer?: boolean } = {}) => { + if (submitting.current) return; if ( stateRef.current.status === "streaming" && !stateRef.current.submitWhileStreaming @@ -529,25 +540,56 @@ export function ComposerBody({ ) { return; } - if ( - stateRef.current.onSubmit?.({ - text, - files, - mentions, - pastedTexts, - steer, - }) === false - ) - return; - historyNavigationRef.current?.reset(); - if (!stateRef.current.clearOnSubmit) return; - pasted.clear(); - editor.update(() => $getRoot().clear()); - setAttachments((previous) => { - for (const attachment of previous) releaseAttachment(attachment); - return []; - }); - setPanel(null); + const submittedRevision = draftRevision.current; + const submittedPastes = cardsRef.current.map((card) => card.id); + const isDraftUnchanged = () => + editor.read( + () => + draftRevision.current === submittedRevision && + cardsRef.current.length === submittedPastes.length && + cardsRef.current.every( + (card, index) => card.id === submittedPastes[index], + ), + ); + const submittedAttachments = new Set( + stateRef.current.attachments.map((attachment) => attachment.id), + ); + submitting.current = true; + setIsSubmitting(true); + try { + if ( + (await stateRef.current.onSubmit?.({ + isDraftUnchanged, + text, + files, + mentions, + pastedTexts, + steer, + })) === false + ) { + return; + } + if (!stateRef.current.clearOnSubmit) return; + // A delayed acceptance must not erase a newer draft or its Lexical chips. + if (isDraftUnchanged()) { + historyNavigationRef.current?.reset(); + pasted.clear(); + editor.update(() => $getRoot().clear()); + } + setAttachments((previous) => + previous.filter((attachment) => { + if (!submittedAttachments.has(attachment.id)) return true; + releaseAttachment(attachment); + return false; + }), + ); + setPanel(null); + } catch { + // The caller owns error feedback. Keep the editor intact for manual retry. + } finally { + submitting.current = false; + setIsSubmitting(false); + } }; const submitRef = useRef(submit); submitRef.current = submit; @@ -582,7 +624,7 @@ export function ComposerBody({ if (event?.shiftKey || event?.isComposing || event?.keyCode === 229) return false; event?.preventDefault(); - submitRef.current({ + void submitRef.current({ steer: Boolean(event?.metaKey || event?.ctrlKey), }); return true; @@ -1136,10 +1178,11 @@ export function ComposerBody({ aria-label={t({ message: "Send message", })} - disabled={!canSend} - onClick={() => submit()} + disabled={!canSend || isSubmitting} + aria-busy={isSubmitting} + onClick={() => void submit()} className={ - canSend + canSend && !isSubmitting ? cn( FOOTER_BUTTON_CLASS, "cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90", diff --git a/packages/chat-ui/src/components/PromptInput/types.ts b/packages/chat-ui/src/components/PromptInput/types.ts index 2fc94015f2c..a7fdf2854e1 100644 --- a/packages/chat-ui/src/components/PromptInput/types.ts +++ b/packages/chat-ui/src/components/PromptInput/types.ts @@ -91,6 +91,7 @@ export type PromptInputAttachment = { }; export type PromptInputSubmitPayload = { + isDraftUnchanged?: () => boolean; text: string; files: File[]; mentions: ComposerChip[]; @@ -155,10 +156,11 @@ export type PromptInputProps = { // Spans of a stored draft that were chips before it was serialized, so // they come back as chips. Runs on the draft as read, never on typing. findChips?: (text: string) => ComposerChipMatch[]; - /** Returning `false` keeps the draft in the editor. */ + /** Clears only after acceptance. Returning `false` or rejecting keeps the draft. */ onSubmit?: ( payload: PromptInputSubmitPayload, - ) => false | void | Promise; + // biome-ignore lint/suspicious/noConfusingVoidType: existing async handlers resolve void; false explicitly declines submission. + ) => false | void | Promise; onStop?: () => void; stopOnEscape?: boolean; header?: ReactNode; diff --git a/packages/chat/src/client/trpcTransport/trpcTransport.ts b/packages/chat/src/client/trpcTransport/trpcTransport.ts index c5bdf472795..b19b59e5832 100644 --- a/packages/chat/src/client/trpcTransport/trpcTransport.ts +++ b/packages/chat/src/client/trpcTransport/trpcTransport.ts @@ -2,6 +2,9 @@ import type { ChatTransport } from "../sessionClient"; type Mutation = | "createSession" + | "createAccountSession" + | "recoverAccountSession" + | "switchAccountSession" | "prompt" | "removeQueuedPrompt" | "steerQueuedPrompt" @@ -14,10 +17,13 @@ type Mutation = | "setMode" | "setConfigOption" | "closeSession" + | "closeStoppedAccountSession" | "forkSession" | "rewindSession"; type Query = + | "accountCapabilities" + | "accountSessionByCommand" | "getSession" | "getQueue" | "listSessions" @@ -36,6 +42,13 @@ export type ChatTrpcClient = { /** Each app builds its own client (auth, links); the mapping is the same. */ export function chatTransportFromTrpc(client: ChatTrpcClient): ChatTransport { return { + accountCapabilities: (input) => client.accountCapabilities.query(input), + accountSessionByCommand: (input) => + client.accountSessionByCommand.query(input), + switchAccountSession: (input) => client.switchAccountSession.mutate(input), + createAccountSession: (input) => client.createAccountSession.mutate(input), + recoverAccountSession: (input) => + client.recoverAccountSession.mutate(input), createSession: (input) => client.createSession.mutate(input), prompt: (input) => client.prompt.mutate(input), removeQueuedPrompt: (input) => client.removeQueuedPrompt.mutate(input), @@ -49,6 +62,8 @@ export function chatTransportFromTrpc(client: ChatTrpcClient): ChatTransport { setMode: (input) => client.setMode.mutate(input), setConfigOption: (input) => client.setConfigOption.mutate(input), closeSession: (input) => client.closeSession.mutate(input), + closeStoppedAccountSession: (input) => + client.closeStoppedAccountSession.mutate(input), forkSession: (input) => client.forkSession.mutate(input), rewindSession: (input) => client.rewindSession.mutate(input), getSession: (input) => client.getSession.query(input), diff --git a/packages/chat/src/protocol/commands.ts b/packages/chat/src/protocol/commands.ts index fe398054911..758332ebee3 100644 --- a/packages/chat/src/protocol/commands.ts +++ b/packages/chat/src/protocol/commands.ts @@ -21,6 +21,58 @@ export const createSessionInputSchema = z.object({ }); export type CreateSessionInput = z.infer; +export const chatAccountSelectionSchema = z.strictObject({ + selection: z.string().nullable(), + identity: z.string().regex(/^[a-f0-9]{64}$/), +}); +export type ChatAccountSelection = z.infer; + +export const chatLaunchAccountSchema = chatAccountSelectionSchema.extend({ + agent: z.enum(["claude", "codex"]), + directory: z.string().min(1), +}); +export type ChatLaunchAccount = z.infer; + +export const chatLaunchContextSchema = z.strictObject({ + v: z.literal(1), + cwd: z.string().min(1), + terminalId: z.string().min(1), + account: chatLaunchAccountSchema, + initialModeId: z.string().optional(), + initialModelId: z.string().optional(), + forkOfSessionId: z.string().min(1).optional(), + switchOfSessionId: z.string().min(1).optional(), +}); +export type ChatLaunchContext = z.infer; + +export const createAccountSessionInputSchema = createSessionInputSchema + .omit({ resume: true, terminalId: true }) + .extend({ + harness: z.enum(["claude-acp", "codex-acp"]), + account: chatAccountSelectionSchema, + }) + .strict(); +export type CreateAccountSessionInput = z.infer< + typeof createAccountSessionInputSchema +>; + +export const switchAccountSessionInputSchema = z.strictObject({ + commandId: z.uuid(), + sessionId: z.string().min(1), + account: chatAccountSelectionSchema, +}); +export type SwitchAccountSessionInput = z.infer< + typeof switchAccountSessionInputSchema +>; + +export const recoverAccountSessionInputSchema = z.strictObject({ + commandId: z.uuid(), + sessionId: z.string().min(1), +}); +export type RecoverAccountSessionInput = z.infer< + typeof recoverAccountSessionInputSchema +>; + export const promptInputSchema = z.object({ ...commandBaseFields, clientId: z.string().min(1), @@ -136,6 +188,13 @@ export const closeSessionInputSchema = z.object({ }); export type CloseSessionInput = z.infer; +export const closeStoppedAccountSessionInputSchema = z.strictObject({ + sessionId: z.string().min(1), +}); +export type CloseStoppedAccountSessionInput = z.infer< + typeof closeStoppedAccountSessionInputSchema +>; + export const getSessionInputSchema = z.object({ sessionId: z.string().min(1) }); export type GetSessionInput = z.infer; diff --git a/packages/chat/src/protocol/envelope.ts b/packages/chat/src/protocol/envelope.ts index 1897abaacca..3e1f98d94af 100644 --- a/packages/chat/src/protocol/envelope.ts +++ b/packages/chat/src/protocol/envelope.ts @@ -75,6 +75,8 @@ export const sessionStateSchema = z.looseObject({ * session, and the caller has to know which one it ended up on. */ harnessSessionId: z.string().optional(), + /** Derived from negotiated harness capabilities; absent means unqualified. */ + exactResumeSupported: z.boolean().optional(), queuePaused: z.boolean().optional(), queueControls: z.boolean().optional(), backgroundTasks: z.array(backgroundTaskSchema).optional(), diff --git a/packages/cli/scripts/build-dist.ts b/packages/cli/scripts/build-dist.ts index 29ea80176cc..9550a073457 100644 --- a/packages/cli/scripts/build-dist.ts +++ b/packages/cli/scripts/build-dist.ts @@ -58,6 +58,7 @@ const RUNTIME_PACKAGES = [ "node-pty", "@parcel/watcher", "@xterm/headless", + "@superset/macos-process-metrics", ] as const; /** @@ -449,6 +450,20 @@ async function main(): Promise { console.log("[build-dist] fixing native binaries for Node runtime"); await fixNativeBinariesForNode(join(stagingRoot, "lib"), target); + // The macOS recovery verifier needs the kernel image, not a launcher path. + // Fail this matching-platform build if the copied N-API addon was skipped. + if (target.startsWith("darwin-")) { + await exec(join(stagingRoot, "lib", "node"), [ + "-e", + `const fs = require("node:fs"); +const metrics = require(${JSON.stringify(join(stagingRoot, "lib", "node_modules", "@superset", "macos-process-metrics"))}); +const actual = metrics.getExecutablePath(process.pid); +if (!actual || fs.realpathSync(actual) !== fs.realpathSync(process.execPath)) { + throw new Error("The macOS executable verifier is missing or built for another target"); +}`, + ]); + } + console.log("[build-dist] copying migrations"); const migrationsSrc = resolve(import.meta.dir, "../../host-service/drizzle"); cpSync(migrationsSrc, join(stagingRoot, "share", "migrations"), { diff --git a/packages/cli/scripts/smoke-test.sh b/packages/cli/scripts/smoke-test.sh index 2e24a76ab33..59a271774cc 100755 --- a/packages/cli/scripts/smoke-test.sh +++ b/packages/cli/scripts/smoke-test.sh @@ -33,10 +33,18 @@ fi # Native addon require() probes. Run from /tmp so Node's module resolution # doesn't walk up into a host repo's node_modules and shadow the bundle. ( cd /tmp && NODE_PATH="$DIST/lib/node_modules" "$DIST/lib/node" -e ' - for (const m of ["better-sqlite3", "node-pty", "@parcel/watcher"]) { + for (const m of ["better-sqlite3", "node-pty", "@parcel/watcher", "@superset/macos-process-metrics"]) { require(m); console.log("[smoke]", m, "OK"); } + if (process.platform === "darwin") { + const fs = require("node:fs"); + const metrics = require("@superset/macos-process-metrics"); + const actual = metrics.getExecutablePath(process.pid); + if (!actual || fs.realpathSync(actual) !== fs.realpathSync(process.execPath)) { + throw new Error("[smoke] bundled macOS executable verifier unavailable"); + } + } ' ) # node-pty must resolve from the bundled tree (not a leaked host copy), and a diff --git a/packages/host-service/build.ts b/packages/host-service/build.ts index 2fc56137489..137140354fc 100644 --- a/packages/host-service/build.ts +++ b/packages/host-service/build.ts @@ -26,6 +26,7 @@ const result = await Bun.build({ "better-sqlite3", "node-pty", "@parcel/watcher", + "@superset/macos-process-metrics", // Optional peer of webdriverio; the browser-driver code path never // executes at runtime, so these must not be bundled. "puppeteer-core", diff --git a/packages/host-service/drizzle/0039_terminal_account_provenance.sql b/packages/host-service/drizzle/0039_terminal_account_provenance.sql new file mode 100644 index 00000000000..65f185c3e14 --- /dev/null +++ b/packages/host-service/drizzle/0039_terminal_account_provenance.sql @@ -0,0 +1,2 @@ +ALTER TABLE `terminal_agent_bindings` ADD `account_json` text;--> statement-breakpoint +ALTER TABLE `terminal_agent_bindings` ADD `launch_id` text; \ No newline at end of file diff --git a/packages/host-service/drizzle/meta/0039_snapshot.json b/packages/host-service/drizzle/meta/0039_snapshot.json new file mode 100644 index 00000000000..dff2519b0d4 --- /dev/null +++ b/packages/host-service/drizzle/meta/0039_snapshot.json @@ -0,0 +1,1287 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "a11a7c16-adbd-4247-8f5f-5908feb5ae70", + "prevId": "b482bc32-9f2b-47ab-99b6-78b75a60e5a1", + "tables": { + "host_agent_configs": { + "name": "host_agent_configs", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "preset_id": { + "name": "preset_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "icon_id": { + "name": "icon_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "args_json": { + "name": "args_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "prompt_transport": { + "name": "prompt_transport", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "prompt_args_json": { + "name": "prompt_args_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "resume_args_json": { + "name": "resume_args_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "fork_args_json": { + "name": "fork_args_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "env_json": { + "name": "env_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'{}'" + }, + "display_order": { + "name": "display_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "host_agent_configs_display_order_idx": { + "name": "host_agent_configs_display_order_idx", + "columns": [ + "display_order" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "host_settings": { + "name": "host_settings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "worktree_base_dir": { + "name": "worktree_base_dir", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch_prefix_mode": { + "name": "branch_prefix_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch_prefix_custom": { + "name": "branch_prefix_custom", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_claude_config_dir": { + "name": "default_claude_config_dir", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "default_codex_home": { + "name": "default_codex_home", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "mobile_last_devices": { + "name": "mobile_last_devices", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "device_key": { + "name": "device_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "picked_at": { + "name": "picked_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "mobile_last_devices_workspace_id_workspaces_id_fk": { + "name": "mobile_last_devices_workspace_id_workspaces_id_fk", + "tableFrom": "mobile_last_devices", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "mobile_owned_devices": { + "name": "mobile_owned_devices", + "columns": { + "platform": { + "name": "platform", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "device_key": { + "name": "device_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "booted_at": { + "name": "booted_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "mobile_owned_devices_platform_device_key_pk": { + "columns": [ + "platform", + "device_key" + ], + "name": "mobile_owned_devices_platform_device_key_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "repo_path": { + "name": "repo_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repo_provider": { + "name": "repo_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repo_owner": { + "name": "repo_owner", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repo_name": { + "name": "repo_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "repo_url": { + "name": "repo_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "remote_name": { + "name": "remote_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "worktree_base_dir": { + "name": "worktree_base_dir", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch_prefix_mode": { + "name": "branch_prefix_mode", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "branch_prefix_custom": { + "name": "branch_prefix_custom", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sparse_checkout_paths": { + "name": "sparse_checkout_paths", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "naming_instructions": { + "name": "naming_instructions", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "deleted_at": { + "name": "deleted_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "deleted_by_user_id": { + "name": "deleted_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "projects_repo_path_idx": { + "name": "projects_repo_path_idx", + "columns": [ + "repo_path" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "pull_requests": { + "name": "pull_requests", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repo_provider": { + "name": "repo_provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repo_owner": { + "name": "repo_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "repo_name": { + "name": "repo_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_draft": { + "name": "is_draft", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "head_branch": { + "name": "head_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "head_sha": { + "name": "head_sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "review_decision": { + "name": "review_decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checks_status": { + "name": "checks_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'none'" + }, + "checks_json": { + "name": "checks_json", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "merged_at": { + "name": "merged_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_fetched_at": { + "name": "last_fetched_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "pull_requests_project_id_idx": { + "name": "pull_requests_project_id_idx", + "columns": [ + "project_id" + ], + "isUnique": false + }, + "pull_requests_repo_branch_idx": { + "name": "pull_requests_repo_branch_idx", + "columns": [ + "repo_provider", + "repo_owner", + "repo_name", + "head_branch" + ], + "isUnique": false + }, + "pull_requests_repo_pr_unique": { + "name": "pull_requests_repo_pr_unique", + "columns": [ + "repo_provider", + "repo_owner", + "repo_name", + "pr_number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "pull_requests_project_id_projects_id_fk": { + "name": "pull_requests_project_id_projects_id_fk", + "tableFrom": "pull_requests", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tag_folder_settings": { + "name": "tag_folder_settings", + "columns": { + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tab_order": { + "name": "tab_order", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "tag_folder_settings_scope_tag_created_by_user_id_pk": { + "columns": [ + "scope", + "tag", + "created_by_user_id" + ], + "name": "tag_folder_settings_scope_tag_created_by_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "terminal_agent_bindings": { + "name": "terminal_agent_bindings", + "columns": { + "terminal_id": { + "name": "terminal_id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent_id": { + "name": "agent_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "agent_session_id": { + "name": "agent_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "definition_id": { + "name": "definition_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "account_json": { + "name": "account_json", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "launch_id": { + "name": "launch_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_event_at": { + "name": "last_event_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_event_type": { + "name": "last_event_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resumed_into_terminal_id": { + "name": "resumed_into_terminal_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "transcript_path": { + "name": "transcript_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "terminal_agent_bindings_workspace_id_idx": { + "name": "terminal_agent_bindings_workspace_id_idx", + "columns": [ + "workspace_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "terminal_agent_bindings_terminal_id_terminal_sessions_id_fk": { + "name": "terminal_agent_bindings_terminal_id_terminal_sessions_id_fk", + "tableFrom": "terminal_agent_bindings", + "tableTo": "terminal_sessions", + "columnsFrom": [ + "terminal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "terminal_sessions": { + "name": "terminal_sessions", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "origin_workspace_id": { + "name": "origin_workspace_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'active'" + }, + "custom_title": { + "name": "custom_title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_attached_at": { + "name": "last_attached_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dispose_requested_at": { + "name": "dispose_requested_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "terminal_sessions_origin_workspace_id_idx": { + "name": "terminal_sessions_origin_workspace_id_idx", + "columns": [ + "origin_workspace_id" + ], + "isUnique": false + }, + "terminal_sessions_status_idx": { + "name": "terminal_sessions_status_idx", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "terminal_sessions_origin_workspace_id_workspaces_id_fk": { + "name": "terminal_sessions_origin_workspace_id_workspaces_id_fk", + "tableFrom": "terminal_sessions", + "tableTo": "workspaces", + "columnsFrom": [ + "origin_workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspace_pull_requests": { + "name": "workspace_pull_requests", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "pull_request_id": { + "name": "pull_request_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "linked_at": { + "name": "linked_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "workspace_pull_requests_workspace_idx": { + "name": "workspace_pull_requests_workspace_idx", + "columns": [ + "workspace_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "workspace_pull_requests_workspace_id_workspaces_id_fk": { + "name": "workspace_pull_requests_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_pull_requests", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspace_pull_requests_pull_request_id_pull_requests_id_fk": { + "name": "workspace_pull_requests_pull_request_id_pull_requests_id_fk", + "tableFrom": "workspace_pull_requests", + "tableTo": "pull_requests", + "columnsFrom": [ + "pull_request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_pull_requests_workspace_id_pull_request_id_pk": { + "columns": [ + "workspace_id", + "pull_request_id" + ], + "name": "workspace_pull_requests_workspace_id_pull_request_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspace_tags": { + "name": "workspace_tags", + "columns": { + "workspace_id": { + "name": "workspace_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "workspace_tags_tag_idx": { + "name": "workspace_tags_tag_idx", + "columns": [ + "tag" + ], + "isUnique": false + } + }, + "foreignKeys": { + "workspace_tags_workspace_id_workspaces_id_fk": { + "name": "workspace_tags_workspace_id_workspaces_id_fk", + "tableFrom": "workspace_tags", + "tableTo": "workspaces", + "columnsFrom": [ + "workspace_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "workspace_tags_workspace_id_tag_created_by_user_id_pk": { + "columns": [ + "workspace_id", + "tag", + "created_by_user_id" + ], + "name": "workspace_tags_workspace_id_tag_created_by_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "workspaces": { + "name": "workspaces", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "worktree_path": { + "name": "worktree_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "head_sha": { + "name": "head_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upstream_owner": { + "name": "upstream_owner", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upstream_repo": { + "name": "upstream_repo", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "upstream_branch": { + "name": "upstream_branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pull_request_id": { + "name": "pull_request_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "suppressed_pull_request_id": { + "name": "suppressed_pull_request_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'worktree'" + }, + "task_id": { + "name": "task_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "archived_at": { + "name": "archived_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "archive_reason": { + "name": "archive_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "workspaces_project_id_idx": { + "name": "workspaces_project_id_idx", + "columns": [ + "project_id" + ], + "isUnique": false + }, + "workspaces_archived_at_idx": { + "name": "workspaces_archived_at_idx", + "columns": [ + "archived_at" + ], + "isUnique": false + }, + "workspaces_upstream_ref_idx": { + "name": "workspaces_upstream_ref_idx", + "columns": [ + "upstream_owner", + "upstream_repo", + "upstream_branch" + ], + "isUnique": false + }, + "workspaces_pull_request_id_idx": { + "name": "workspaces_pull_request_id_idx", + "columns": [ + "pull_request_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "workspaces_project_id_projects_id_fk": { + "name": "workspaces_project_id_projects_id_fk", + "tableFrom": "workspaces", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "workspaces_pull_request_id_pull_requests_id_fk": { + "name": "workspaces_pull_request_id_pull_requests_id_fk", + "tableFrom": "workspaces", + "tableTo": "pull_requests", + "columnsFrom": [ + "pull_request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "workspaces_suppressed_pull_request_id_pull_requests_id_fk": { + "name": "workspaces_suppressed_pull_request_id_pull_requests_id_fk", + "tableFrom": "workspaces", + "tableTo": "pull_requests", + "columnsFrom": [ + "suppressed_pull_request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/host-service/drizzle/meta/_journal.json b/packages/host-service/drizzle/meta/_journal.json index 4beeb2da44d..3c1432ae96c 100644 --- a/packages/host-service/drizzle/meta/_journal.json +++ b/packages/host-service/drizzle/meta/_journal.json @@ -274,6 +274,13 @@ "when": 1792467855578, "tag": "0038_mobile_devices", "breakpoints": true + }, + { + "idx": 39, + "version": "6", + "when": 1792961718571, + "tag": "0039_terminal_account_provenance", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/host-service/package.json b/packages/host-service/package.json index fb532e76e85..f1156742195 100644 --- a/packages/host-service/package.json +++ b/packages/host-service/package.json @@ -66,7 +66,7 @@ "test": "bun test --pass-with-no-tests --parallel", "test:integration": "bun test --pass-with-no-tests test/integration", "test:integration:daemon": "node --experimental-strip-types --test src/terminal/DaemonClient/DaemonClient.node-test.ts src/daemon/DaemonSupervisor.node-test.ts", - "test:integration:terminal": "node --import tsx --test src/terminal/terminal.initial-command.node-test.ts src/terminal/terminal.ungated-launch.node-test.ts src/terminal/terminal.shell-ready-learning.node-test.ts src/terminal/terminal.fish-prompt-transport.node-test.ts src/terminal/terminal.send-snapshot.node-test.ts", + "test:integration:terminal": "node --import tsx --test src/terminal/terminal.initial-command.node-test.ts src/terminal/terminal.ungated-launch.node-test.ts src/terminal/terminal.shell-ready-learning.node-test.ts src/terminal/terminal.fish-prompt-transport.node-test.ts src/terminal/terminal.send-snapshot.node-test.ts src/trpc/router/usage/codex-quota-config.node-test.ts", "test:integration:ports": "node --experimental-strip-types --test src/ports/forward-mux-route.node-test.ts", "test:integration:workers": "node --experimental-strip-types --test src/workers/worker-termination.node-test.ts", "test:e2e": "bun run scripts/test-e2e.ts", @@ -85,6 +85,7 @@ "@superset/agent-setup": "workspace:*", "@superset/chat": "workspace:*", "@superset/chat-runtime": "workspace:*", + "@superset/macos-process-metrics": "workspace:*", "@superset/port-scanner": "workspace:*", "@superset/pty-daemon": "workspace:*", "@superset/shared": "workspace:*", @@ -105,6 +106,7 @@ "pi-acp": "0.0.34", "semver": "7.7.4", "simple-git": "4.0.2", + "smol-toml": "1.9.1", "superjson": "2.2.6", "tree-kill": "1.2.2", "zod": "4.6.5" diff --git a/packages/host-service/src/app.ts b/packages/host-service/src/app.ts index 5158acc6f72..e9f05005141 100644 --- a/packages/host-service/src/app.ts +++ b/packages/host-service/src/app.ts @@ -54,6 +54,7 @@ import { SqliteTerminalAgentBindingPersistence, TerminalAgentStore, } from "./terminal-agents"; +import { configureAttributionTokensForDatabase } from "./terminal-agents/attribution-token"; import { matchesAgentBinding } from "./terminal-agents/matches-agent-binding"; import { appRouter } from "./trpc/router"; import { gitStatusStore } from "./trpc/router/git/utils/git-status-store"; @@ -61,11 +62,15 @@ import { disposeLocalMobileDevices, startLocalMobileDeviceCleanup, } from "./trpc/router/mobile"; +import { disposeBackgroundSuccessorRefresh } from "./trpc/router/notifications/background-successor-adapter"; import { resumeCrashedAgentSessions, resumeSessionDepsFor, } from "./trpc/router/terminal-agents/terminal-agents"; import { provisionSelectedAccounts } from "./trpc/router/usage/account-provisioning"; +import { claudeQuotaPolling } from "./trpc/router/usage/claude-quota-polling"; +import { onNativeClaudeUsage } from "./trpc/router/usage/native-claude-usage"; +import { disposeUsageQuota, expireUsageQuota } from "./trpc/router/usage/usage"; import { execGh as defaultExecGh, type ExecGh, @@ -142,6 +147,10 @@ export function createApp(options: CreateAppOptions): CreateAppResult { options.api ?? createApiClient(config.cloudApiUrl, providers.auth, config.organizationId); const db = options.db ?? createDb(config.dbPath, config.migrationsFolder); + configureAttributionTokensForDatabase( + config.dbPath, + options.db !== undefined, + ); // A sandbox is provisioned for exactly one workspace, and the env says // which. Seeding it here rather than from the API keeps the schema in one // place and leaves provisioning with nothing to orchestrate. @@ -543,10 +552,28 @@ export function createApp(options: CreateAppOptions): CreateAppResult { }), ); + const disposeQuotaActivity = claudeQuotaPolling.register(() => + terminalAgentStore.list(), + ); + const disposeNativeUsage = onNativeClaudeUsage(() => { + expireUsageQuota("claude"); + eventBus.broadcastUsageChanged({ + provider: "claude", + occurredAt: Date.now(), + }); + }); const ownsDb = options.db === undefined; const dispose = async (): Promise => { + disposeBackgroundSuccessorRefresh(db); + disposeQuotaActivity(); + disposeNativeUsage(); if (projectPurgeTimer) clearInterval(projectPurgeTimer); await disposeWorkspaceTitleJobs(db); + try { + await disposeUsageQuota(); + } catch (err) { + console.warn("[host-service] usage quota disposal failed:", err); + } // Each step is best-effort and isolated: a throw in one cleanup must // not skip the others, otherwise a flaky `.stop()` could leak the // open SQLite handle for the rest of the process lifetime. diff --git a/packages/host-service/src/chat-v3/accountLaunch.test.ts b/packages/host-service/src/chat-v3/accountLaunch.test.ts new file mode 100644 index 00000000000..7cb9890b48f --- /dev/null +++ b/packages/host-service/src/chat-v3/accountLaunch.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, test } from "bun:test"; +import { + resolveProviderLaunchAccount, + withPinnedAccountEnv, +} from "../trpc/router/agents/launch-account"; +import type { SessionAccount } from "../trpc/router/usage/session-account/session-account"; +import { prepareChatAccount, sessionAccountForChat } from "./accountLaunch"; + +const account: SessionAccount = { + agent: "claude", + selection: "/fixture/claude", + directory: "/fixture/claude", + identity: "a".repeat(64), + credentialKind: "subscription", + email: "fixture@example.test", +}; +const choice = { selection: account.selection, identity: account.identity }; + +describe("native chat account launch", () => { + test("validates the selected profile and working folder, without changing a default", async () => { + const seen: unknown[] = []; + const selected = await prepareChatAccount( + { harness: "claude-acp", account: choice, cwd: "/fixture/work" }, + { + resolve: async (provider, input) => { + seen.push({ provider, input }); + return account; + }, + validateRouting: async (profile, cwd) => { + seen.push({ profile, cwd }); + }, + }, + ); + expect(seen).toEqual([ + { provider: "claude", input: choice }, + { profile: account, cwd: "/fixture/work" }, + ]); + expect(selected).toEqual({ + agent: account.agent, + ...choice, + directory: account.directory as string, + }); + expect(sessionAccountForChat(selected)).toMatchObject({ + pinned: true, + credentialKind: "subscription", + }); + }); + + test("refuses legacy or unknown harnesses before profile discovery", async () => { + for (const harness of ["claude-code", "codex", "custom"]) { + await expect( + prepareChatAccount( + { harness, account: choice, cwd: "/fixture/work" }, + { + resolve: async () => { + throw new Error("must not discover"); + }, + validateRouting: async () => {}, + }, + ), + ).rejects.toThrow("does not support explicit account"); + } + }); + + test("routing or identity failures never select another profile", async () => { + await expect( + prepareChatAccount( + { harness: "claude-acp", account: choice, cwd: "/fixture/work" }, + { + resolve: async () => account, + validateRouting: async () => { + throw new Error("conflicting routing"); + }, + }, + ), + ).rejects.toThrow("conflicting routing"); + await expect( + resolveProviderLaunchAccount( + "claude", + { ...choice, identity: "b".repeat(64) }, + async () => [account], + ), + ).rejects.toThrow(); + }); + + test("pinned Claude overrides inherited default and API auth without mutating ambient env", () => { + const ambient = { + SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR: "/wrong", + CLAUDE_CONFIG_DIR: "/wrong", + ANTHROPIC_API_KEY: "fixture-key", + ANTHROPIC_AUTH_TOKEN: "fixture-token", + ANTHROPIC_CUSTOM_HEADERS: "fixture-header", + PATH: "/bin", + CODEX_HOME: "/other-provider", + }; + const selected = withPinnedAccountEnv(account, ambient); + expect(selected.CLAUDE_CONFIG_DIR).toBe(account.directory); + expect(selected.SUPERSET_PINNED_ACCOUNT).toBe("CLAUDE_CONFIG_DIR"); + expect(selected.ANTHROPIC_API_KEY).toBeUndefined(); + expect(selected.ANTHROPIC_AUTH_TOKEN).toBeUndefined(); + expect(selected.ANTHROPIC_CUSTOM_HEADERS).toBeUndefined(); + expect(selected.SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR).toBeUndefined(); + expect(selected.CODEX_HOME).toBe("/other-provider"); + expect(ambient.CLAUDE_CONFIG_DIR).toBe("/wrong"); + }); + + test("system Claude selection leaves its config override unset; Codex pins its selected home", () => { + expect( + withPinnedAccountEnv( + { ...account, selection: null }, + { + CLAUDE_CONFIG_DIR: "/wrong", + SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR: "/wrong", + }, + ), + ).toEqual({ SUPERSET_PINNED_ACCOUNT: "CLAUDE_CONFIG_DIR" }); + const env = withPinnedAccountEnv( + { + ...account, + agent: "codex", + selection: "/fixture/codex", + directory: "/fixture/codex", + }, + { + CODEX_HOME: "/wrong", + SUPERSET_DEFAULT_CODEX_HOME: "/wrong", + OPENAI_API_KEY: "fixture-key", + OPENAI_BASE_URL: "https://example.test", + }, + ); + expect(env).toEqual({ + CODEX_HOME: "/fixture/codex", + SUPERSET_DEFAULT_CODEX_HOME: "/fixture/codex", + SUPERSET_PINNED_ACCOUNT: "CODEX_HOME", + }); + }); +}); diff --git a/packages/host-service/src/chat-v3/accountLaunch.ts b/packages/host-service/src/chat-v3/accountLaunch.ts new file mode 100644 index 00000000000..beb0e650269 --- /dev/null +++ b/packages/host-service/src/chat-v3/accountLaunch.ts @@ -0,0 +1,83 @@ +import { realpath } from "node:fs/promises"; +import type { + ChatAccountSelection, + ChatLaunchAccount, + ChatLaunchContext, +} from "@superset/chat/protocol"; +import { eq } from "drizzle-orm"; +import type { HostDb } from "../db"; +import { workspaces } from "../db/schema"; +import { validateAccountAuthRouting } from "../trpc/router/agents/account-auth-routing"; +import { resolveProviderLaunchAccount } from "../trpc/router/agents/launch-account"; +import type { SessionAccount } from "../trpc/router/usage/session-account/session-account"; + +export const ACCOUNT_CHAT_HARNESSES = ["claude-acp", "codex-acp"] as const; + +function providerForHarness(harness: string): "claude" | "codex" { + if (harness === "claude-acp") return "claude"; + if (harness === "codex-acp") return "codex"; + throw new Error( + "This chat agent does not support explicit account selection.", + ); +} + +export function sessionAccountForChat( + account: ChatLaunchAccount, +): SessionAccount { + return { ...account, credentialKind: "subscription", pinned: true }; +} + +export async function prepareChatAccount( + input: { harness: string; account: ChatAccountSelection; cwd: string }, + deps = { + resolve: resolveProviderLaunchAccount, + validateRouting: validateAccountAuthRouting, + }, +): Promise { + if (process.env.SUPERSET_HOST_RUN_MODE === "sandbox") + throw new Error( + "Explicit local accounts are not available in this cloud workspace.", + ); + const account = await deps.resolve( + providerForHarness(input.harness), + input.account, + ); + await deps.validateRouting(account, input.cwd); + if (!account.directory) + throw new Error("The selected account profile is unavailable."); + return { + agent: account.agent, + selection: account.selection, + identity: account.identity, + directory: account.directory, + }; +} + +export async function validateChatAccount( + db: HostDb, + context: ChatLaunchContext, + harness: string, + scopeId: string, +): Promise { + const workspace = db.query.workspaces + .findFirst({ where: eq(workspaces.id, scopeId) }) + .sync(); + if ( + !workspace || + workspace.archivedAt !== null || + (await realpath(workspace.worktreePath)) !== (await realpath(context.cwd)) + ) + throw new Error( + "The conversation's working folder is unavailable or changed.", + ); + const account = await prepareChatAccount({ + harness, + account: context.account, + cwd: context.cwd, + }); + if ( + account.agent !== context.account.agent || + account.directory !== context.account.directory + ) + throw new Error("The saved account profile changed. Nothing was launched."); +} diff --git a/packages/host-service/src/chat-v3/accountSwitch.test.ts b/packages/host-service/src/chat-v3/accountSwitch.test.ts new file mode 100644 index 00000000000..4925c571509 --- /dev/null +++ b/packages/host-service/src/chat-v3/accountSwitch.test.ts @@ -0,0 +1,139 @@ +import { expect, mock, test } from "bun:test"; +import type { ChatLaunchContext } from "@superset/chat/protocol"; +import type { HostDb } from "../db"; +import { prepareChatAccountSwitch } from "./accountSwitch"; + +const source: ChatLaunchContext = { + v: 1, + cwd: "/fixture/work", + terminalId: "pane", + account: { + agent: "claude", + directory: "/fixture/a", + selection: "/fixture/a", + identity: "a".repeat(64), + }, +}; +const target = { + ...source.account, + directory: "/fixture/b", + selection: "/fixture/b", + identity: "b".repeat(64), +}; +const input = { + harness: "claude-acp", + scopeId: "workspace", + cwd: source.cwd, + harnessSessionId: "native-session", + source, + account: target, +}; +function fixture() { + const evidence = { + path: "/shared/session.jsonl", + device: 1, + inode: 2, + size: 10, + modifiedAt: 1, + changedAt: 1, + sha256: "a".repeat(64), + }; + const release = mock(() => {}); + const deps = { + prepare: mock(async () => target), + validate: mock(async () => {}), + inspect: mock(async () => ({ ...evidence })), + assertCurrent: mock((_history: typeof evidence) => {}), + writers: mock(async () => {}), + claim: mock(() => release), + }; + return { evidence, release, deps }; +} + +test("refuses an inaccessible independent history before returning an exit plan", async () => { + const f = fixture(); + f.deps.inspect = mock(async () => { + throw new Error("independent histories"); + }); + await expect( + prepareChatAccountSwitch({} as HostDb, input, f.deps), + ).rejects.toThrow("independent histories"); + expect(f.release).toHaveBeenCalledTimes(1); + expect(f.deps.writers).not.toHaveBeenCalled(); +}); + +test("binds the exact source and target, then checkpoints final appended history", async () => { + const f = fixture(); + const plan = await prepareChatAccountSwitch({} as HostDb, input, f.deps); + f.deps.inspect = mock(async () => ({ + ...f.evidence, + size: 20, + sha256: "b".repeat(64), + })); + const ready = await plan.finish(); + expect(f.deps.inspect).toHaveBeenCalledWith( + expect.objectContaining({ previous: f.evidence }), + ); + expect(ready.account).toEqual(target); + expect(f.deps.writers).toHaveBeenCalledWith({ + sessionId: "native-session", + directories: ["/fixture/a", "/fixture/b"], + }); + ready.assertCurrent(); + expect(f.deps.assertCurrent.mock.calls.at(-1)?.[0]).toEqual({ + ...f.evidence, + size: 20, + sha256: "b".repeat(64), + }); + plan.release(); + expect(f.release).toHaveBeenCalledTimes(1); +}); + +test("a replaced transcript or changed destination refuses post-exit preparation", async () => { + for (const failure of ["inode", "identity"] as const) { + const f = fixture(); + const plan = await prepareChatAccountSwitch({} as HostDb, input, f.deps); + if (failure === "inode") + f.deps.inspect = mock(async () => ({ ...f.evidence, inode: 99 })); + else + f.deps.prepare = mock(async () => ({ + ...target, + identity: "c".repeat(64), + })); + await expect(plan.finish()).rejects.toThrow( + failure === "inode" ? "history moved" : "account changed", + ); + plan.release(); + } +}); + +test("a surviving native writer or changed final checkpoint refuses launch authorization", async () => { + const f = fixture(); + const plan = await prepareChatAccountSwitch({} as HostDb, input, f.deps); + f.deps.writers = mock(async () => { + throw new Error("writer remains"); + }); + await expect(plan.finish()).rejects.toThrow("writer remains"); + f.deps.writers = mock(async () => {}); + const ready = await plan.finish(); + f.deps.assertCurrent = mock(() => { + throw new Error("checkpoint changed"); + }); + expect(() => ready.assertCurrent()).toThrow("checkpoint changed"); + plan.release(); +}); + +for (const mutation of ["truncate", "rewrite"] as const) { + test(`the host refuses ${mutation} of admitted bytes even when the file identity is unchanged`, async () => { + const f = fixture(); + const plan = await prepareChatAccountSwitch({} as HostDb, input, f.deps); + f.deps.inspect = mock(async () => ({ + ...f.evidence, + size: mutation === "truncate" ? 5 : f.evidence.size, + sha256: "b".repeat(64), + })); + await expect(plan.finish()).rejects.toThrow("history moved"); + expect(f.deps.writers).not.toHaveBeenCalled(); + plan.release(); + }); +} diff --git a/packages/host-service/src/chat-v3/accountSwitch.ts b/packages/host-service/src/chat-v3/accountSwitch.ts new file mode 100644 index 00000000000..2ce49118a5e --- /dev/null +++ b/packages/host-service/src/chat-v3/accountSwitch.ts @@ -0,0 +1,103 @@ +import type { + ChatAccountSelection, + ChatLaunchContext, +} from "@superset/chat/protocol"; +import type { HostDb } from "../db"; +import { claimNativeSession } from "../terminal-agents/native-session-lease"; +import { + assertAccountResumeHistoryCurrent, + inspectAccountResumeHistory, +} from "../trpc/router/terminal-agents/account-resume-history"; +import { assertNoRecordedClaudeWriter } from "../trpc/router/terminal-agents/account-resume-processes"; +import { + prepareChatAccount, + sessionAccountForChat, + validateChatAccount, +} from "./accountLaunch"; + +interface SwitchInput { + harness: string; + account: ChatAccountSelection; + cwd: string; + scopeId: string; + harnessSessionId: string; + source: ChatLaunchContext; +} + +/** Verify access before closing; inspect the final native history after normal exit. */ +export async function prepareChatAccountSwitch( + db: HostDb, + input: SwitchInput, + deps = { + prepare: prepareChatAccount, + validate: validateChatAccount, + inspect: inspectAccountResumeHistory, + assertCurrent: assertAccountResumeHistoryCurrent, + writers: assertNoRecordedClaudeWriter, + claim: claimNativeSession, + }, +) { + const release = deps.claim( + input.source.account.agent, + input.harnessSessionId, + ); + try { + await deps.validate(db, input.source, input.harness, input.scopeId); + const target = await deps.prepare(input); + if (target.agent !== input.source.account.agent) + throw new Error("The selected account belongs to another provider."); + const historyInput = { + source: sessionAccountForChat(input.source.account), + target: sessionAccountForChat(target), + sessionId: input.harnessSessionId, + cwd: input.cwd, + }; + // This refuses independent histories before the source agent is touched. + const original = await deps.inspect(historyInput); + deps.assertCurrent(original); + return { + release, + finish: async () => { + await deps.validate(db, input.source, input.harness, input.scopeId); + const current = await deps.prepare(input); + if (JSON.stringify(current) !== JSON.stringify(target)) + throw new Error( + "The selected account changed. The saved conversation is intact.", + ); + const final = await deps.inspect({ + ...historyInput, + previous: original, + }); + if ( + final.path !== original.path || + final.device !== original.device || + final.inode !== original.inode || + final.size < original.size || + (final.size === original.size && final.sha256 !== original.sha256) + ) + throw new Error( + "The shared conversation history moved. Nothing else was started.", + ); + if (target.agent === "claude") + await deps.writers({ + sessionId: input.harnessSessionId, + directories: [input.source.account.directory, target.directory], + }); + // The provider launcher revalidates this identity again before spawning. + const verified = await deps.prepare(input); + if (JSON.stringify(verified) !== JSON.stringify(target)) + throw new Error( + "The selected account changed. The saved conversation is intact.", + ); + deps.assertCurrent(final); + return { + account: target, + assertCurrent: () => deps.assertCurrent(final), + }; + }, + }; + } catch (error) { + release(); + throw error; + } +} diff --git a/packages/host-service/src/chat-v3/acpHarnesses.ts b/packages/host-service/src/chat-v3/acpHarnesses.ts index 4aa0407db8d..05ad0351732 100644 --- a/packages/host-service/src/chat-v3/acpHarnesses.ts +++ b/packages/host-service/src/chat-v3/acpHarnesses.ts @@ -6,11 +6,13 @@ import { createAcpAdapter } from "@superset/chat-runtime"; import type { HostDb } from "../db"; import { resolveAttachmentPath } from "../trpc/router/attachments/storage"; import { captureSessionAccount } from "../trpc/router/usage/session-account/session-account"; +import { sessionAccountForChat, validateChatAccount } from "./accountLaunch"; import { ACP_HARNESSES } from "./acpCatalogue"; import { resolveAgentCli } from "./agentCli"; import { buildChatAgentEnv } from "./agentEnv"; import { storeAgentImage } from "./agentImages"; import type { ChatAgentBridge } from "./chatAgentBridge"; +import { createNativeClaudeChatFeed } from "./nativeClaudeUsage"; async function resolveAttachment(attachmentId: string) { const resolved = resolveAttachmentPath(attachmentId); @@ -45,18 +47,39 @@ export function acpHarnessFactory( } } - return (options) => - createAcpAdapter({ + return (options) => { + const launchContext = options.launchContext; + const nativeUsage = + process.env.SUPERSET_NATIVE_CLAUDE_USAGE === "1" && + entry.binary === "claude" && + launchContext + ? createNativeClaudeChatFeed() + : null; + return createAcpAdapter({ command: entry.binary, cwd: options.cwd, resolveAttachment, storeImage: storeAgentImage, + ...(launchContext + ? { + beforePrompt: () => + validateChatAccount( + db, + launchContext, + options.harness, + options.scopeId, + ), + } + : {}), ...(entry.fullAccessModeId ? { defaultModeId: entry.fullAccessModeId } : {}), ...(entry.clientApprovalModes ? { clientApprovalModes: true } : {}), ...(entry.forkAtMessage ? { forkAtMessage: true } : {}), onSpawn: (pid) => agents?.spawned(options.sessionId, pid), + onSessionId: (sessionId) => nativeUsage?.session(sessionId), + onClaudeRateLimit: (event) => nativeUsage?.event(event), + onDisposed: () => nativeUsage?.dispose(), launch: async () => { const cli = await resolveAgentCli({ binary: entry.binary, @@ -68,9 +91,22 @@ export function acpHarnessFactory( cwd: options.cwd, workspaceId: options.scopeId, terminalId: options.terminalId, + launchContext: options.launchContext, + harness: options.harness, }), }); const env = cli.env; + if (options.launchContext) + await validateChatAccount( + db, + options.launchContext, + options.harness, + options.scopeId, + ); + if (nativeUsage && launchContext) + await nativeUsage.launched( + sessionAccountForChat(launchContext.account), + ); void captureSessionAccount( entry.binary, (entry.binary === "codex" ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR) ?? @@ -104,6 +140,7 @@ export function acpHarnessFactory( }; }, }); + }; } export function acpHarnessEntries( diff --git a/packages/host-service/src/chat-v3/agentEnv.ts b/packages/host-service/src/chat-v3/agentEnv.ts index e3bbc527519..94c30c0a11b 100644 --- a/packages/host-service/src/chat-v3/agentEnv.ts +++ b/packages/host-service/src/chat-v3/agentEnv.ts @@ -1,10 +1,13 @@ import { delimiter } from "node:path"; import { getBinDir } from "@superset/agent-setup"; +import type { ChatLaunchContext } from "@superset/chat/protocol"; import { eq } from "drizzle-orm"; import type { HostDb } from "../db"; import { projects, workspaces } from "../db/schema"; import { buildHostLaunchEnv, waitForTerminalBaseEnv } from "../terminal/env"; +import { withPinnedAccountEnv } from "../trpc/router/agents/launch-account"; import { resolveDefaultAccountTerminalEnv } from "../trpc/router/usage/default-account"; +import { sessionAccountForChat, validateChatAccount } from "./accountLaunch"; function workspacePaths( db: HostDb, @@ -57,10 +60,12 @@ export async function buildChatAgentEnv(options: { cwd: string; workspaceId: string; terminalId?: string; + launchContext?: ChatLaunchContext; + harness?: string; }): Promise> { await waitForTerminalBaseEnv(); const paths = workspacePaths(options.db, options.workspaceId); - return withoutAmbientKeys( + const env = withoutAmbientKeys( withSupersetBinFirst({ ...buildHostLaunchEnv({ cwd: options.cwd, @@ -72,4 +77,15 @@ export async function buildChatAgentEnv(options: { ...resolveDefaultAccountTerminalEnv(options.db), }), ); + if (!options.launchContext) return env; + await validateChatAccount( + options.db, + options.launchContext, + options.harness ?? "", + options.workspaceId, + ); + return withPinnedAccountEnv( + sessionAccountForChat(options.launchContext.account), + env, + ); } diff --git a/packages/host-service/src/chat-v3/chatAgentBridge.test.ts b/packages/host-service/src/chat-v3/chatAgentBridge.test.ts index ce662931f9f..26d34736fe8 100644 --- a/packages/host-service/src/chat-v3/chatAgentBridge.test.ts +++ b/packages/host-service/src/chat-v3/chatAgentBridge.test.ts @@ -75,6 +75,51 @@ function setup() { } describe("createChatAgentBridge", () => { + it("retains a selected chat account and marks conflicting observed metadata", () => { + const { bridge, terminalAgentStore } = setup(); + const account = { + agent: "claude" as const, + selection: "/fixture/selected", + directory: "/fixture/selected", + identity: "a".repeat(64), + }; + bridge.started({ + sessionId: "bound-chat", + scopeId: WORKSPACE, + harness: "claude-acp", + cwd: "/fixture/work", + terminalId: TERMINAL, + launchContext: { + v: 1, + cwd: "/fixture/work", + terminalId: TERMINAL, + account, + }, + }); + try { + expect( + terminalAgentStore.listByWorkspace(WORKSPACE)[0]?.account, + ).toMatchObject({ ...account, pinned: true }); + bridge.accountCaptured("bound-chat", { + ...account, + credentialKind: "subscription", + }); + expect( + terminalAgentStore.listByWorkspace(WORKSPACE)[0]?.account?.conflict, + ).toBeUndefined(); + bridge.accountCaptured("bound-chat", { + ...account, + credentialKind: "subscription", + identity: "b".repeat(64), + }); + expect( + terminalAgentStore.listByWorkspace(WORKSPACE)[0]?.account, + ).toMatchObject({ ...account, pinned: true, conflict: true }); + } finally { + bridge.stopped("bound-chat"); + } + }); + it("lists the chat as the terminal's agent while it runs", () => { const { bridge, terminalAgentStore, start } = setup(); start("chat-1"); diff --git a/packages/host-service/src/chat-v3/chatAgentBridge.ts b/packages/host-service/src/chat-v3/chatAgentBridge.ts index c953d614ec2..cd130e3777a 100644 --- a/packages/host-service/src/chat-v3/chatAgentBridge.ts +++ b/packages/host-service/src/chat-v3/chatAgentBridge.ts @@ -18,6 +18,7 @@ import { chatPortTerminalIds, portManager } from "../ports/port-manager"; import { fanOutAgentLifecycle } from "../trpc/router/notifications/fan-out-agent-lifecycle"; import type { SessionAccount } from "../trpc/router/usage/session-account/session-account"; import type { HostServiceContext } from "../types"; +import { sessionAccountForChat } from "./accountLaunch"; import { ACP_HARNESSES } from "./acpCatalogue"; const LIFECYCLE_BY_STATUS: Partial< @@ -179,6 +180,9 @@ export function createChatAgentBridge( workspaceId: options.scopeId, agentId, queuedPrompts: 0, + ...(options.launchContext + ? { account: sessionAccountForChat(options.launchContext.account) } + : {}), ...(options.resume ? { agentSessionId: options.resume.harnessSessionId } : {}), @@ -201,6 +205,17 @@ export function createChatAgentBridge( accountCaptured(sessionId, account) { const chat = chats.get(sessionId); if (!chat) return; + if (chat.account?.pinned) { + if ( + chat.account.agent !== account.agent || + chat.account.selection !== account.selection || + chat.account.identity !== account.identity || + account.credentialKind !== "subscription" + ) + chat.account = { ...chat.account, conflict: true }; + if (current(sessionId)) attach(chat); + return; + } chat.account = account; if (current(sessionId)) attach(chat); }, diff --git a/packages/host-service/src/chat-v3/mount.ts b/packages/host-service/src/chat-v3/mount.ts index fc8de692202..b0d6ffffc59 100644 --- a/packages/host-service/src/chat-v3/mount.ts +++ b/packages/host-service/src/chat-v3/mount.ts @@ -23,6 +23,12 @@ import { import { HOST_CHAT_RESUME_MARKER_FILE } from "@superset/shared/host-version"; import type { Hono, MiddlewareHandler } from "hono"; import type { HostDb } from "../db"; +import { + ACCOUNT_CHAT_HARNESSES, + prepareChatAccount, + validateChatAccount, +} from "./accountLaunch"; +import { prepareChatAccountSwitch } from "./accountSwitch"; import { cliFloor } from "./acpCatalogue"; import { acpHarnessEntries } from "./acpHarnesses"; import { resolveAgentCli } from "./agentCli"; @@ -138,6 +144,8 @@ export function createChatV3Mount(options: { harnesses: harnessRegistry(options.db, options.agents), observer: options.agents, onSessionChanged: options.onSessionChanged, + validateAccountLaunch: (context, harness, scopeId) => + validateChatAccount(options.db, context, harness, scopeId), }); return built; }; @@ -184,7 +192,13 @@ export function registerChatV3Routes(options: { options.app.use(`${endpoint}/*`, (c, next) => { handler ??= trpcServer({ endpoint, - router: createChatRouter(options.mount.runtime(), { resolveCwd }), + router: createChatRouter(options.mount.runtime(), { + resolveCwd, + accountHarnesses: ACCOUNT_CHAT_HARNESSES, + prepareAccount: prepareChatAccount, + prepareAccountSwitch: (input) => + prepareChatAccountSwitch(options.db, input), + }), }); return handler(c, next); }); diff --git a/packages/host-service/src/chat-v3/nativeClaudeUsage.test.ts b/packages/host-service/src/chat-v3/nativeClaudeUsage.test.ts new file mode 100644 index 00000000000..f3849424cec --- /dev/null +++ b/packages/host-service/src/chat-v3/nativeClaudeUsage.test.ts @@ -0,0 +1,153 @@ +import { expect, test } from "bun:test"; +import type { NativeClaudeUsageDependencies } from "../trpc/router/usage/native-claude-binding"; +import { createNativeClaudeUsageStore } from "../trpc/router/usage/native-claude-usage"; +import { createNativeClaudeChatFeed } from "./nativeClaudeUsage"; + +function fixture() { + let now = 1_800_000_000_000; + let generation = "a".repeat(64); + let scope: string | null = null; + const account = { + agent: "claude" as const, + credentialKind: "subscription" as const, + pinned: true as const, + identity: "e".repeat(64), + selection: "/fixture/profile", + directory: "/fixture/profile", + }; + const store = createNativeClaudeUsageStore({ + persist: false, + now: () => now, + }); + const deps: NativeClaudeUsageDependencies = { + store, + validateAccount: async () => true, + captureGeneration: async () => generation, + resolveScope: async (_a, _d, _i, expected) => + expected === generation ? scope : null, + }; + const feed = createNativeClaudeChatFeed(deps, () => now); + const event = ( + responseCounter: number, + used = 0.2, + sessionId = "owned-session", + ) => ({ + sessionId, + responseCounter, + rateLimitInfo: { + rateLimitType: "five_hour", + utilization: used, + resetsAt: 1_800_000_300, + }, + }); + return { + feed, + account, + store, + deps, + event, + advance: (ms = 1000) => { + now += ms; + }, + time: () => now, + warm: () => { + scope = "b".repeat(64); + }, + rotate: () => { + generation = "c".repeat(64); + }, + }; +} +test("ACP first restored event is not fresh; later actual response and cold promotion preserve age", async () => { + const f = fixture(); + await f.feed.launched(f.account); + f.feed.session("owned-session"); + await f.feed.settled(); + f.feed.event(f.event(0)); + await f.feed.settled(); + f.advance(); + f.feed.event(f.event(1, 0.25)); + await f.feed.settled(); + expect(f.store.snapshot("b".repeat(64))).toEqual([]); + f.advance(); + f.warm(); + f.feed.event(f.event(1, 0.25)); + await f.feed.settled(); + expect(f.store.snapshot("b".repeat(64))[0]?.observedAt).toBe( + 1_800_000_001_000, + ); + f.advance(); + f.feed.event(f.event(1, 0.25)); + await f.feed.settled(); + expect(f.store.snapshot("b".repeat(64))[0]?.observedAt).toBe( + 1_800_000_001_000, + ); +}); +test("pre-spawn generation, foreign session, disposal and unpinned account guards hold", async () => { + const f = fixture(); + await f.feed.launched(f.account); + f.rotate(); + f.feed.session("owned-session"); + await f.feed.settled(); + f.warm(); + f.feed.event(f.event(1)); + await f.feed.settled(); + expect(f.store.snapshot("b".repeat(64))).toEqual([]); + const other = fixture(); + other.warm(); + await other.feed.launched(other.account); + other.feed.session("owned-session"); + await other.feed.settled(); + other.feed.event(other.event(1, 0.3, "foreign")); + await other.feed.settled(); + expect(other.store.snapshot("b".repeat(64))).toEqual([]); + other.feed.dispose(); + other.feed.event(other.event(1)); + await other.feed.settled(); + expect(other.store.snapshot("b".repeat(64))).toEqual([]); + const unpinned = fixture(); + unpinned.warm(); + await unpinned.feed.launched({ ...unpinned.account, pinned: undefined }); + unpinned.feed.session("owned-session"); + unpinned.feed.event(unpinned.event(1)); + await unpinned.feed.settled(); + expect(unpinned.store.snapshot("b".repeat(64))).toEqual([]); +}); + +test("ACP events retain arrival time while queued behind asynchronous validation", async () => { + const f = fixture(); + f.warm(); + await f.feed.launched(f.account); + f.feed.session("owned-session"); + await f.feed.settled(); + let release!: () => void; + let entered!: () => void; + const waiting = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + let block = true; + f.deps.validateAccount = async () => { + if (block) { + block = false; + entered(); + await gate; + } + return true; + }; + f.advance(); + f.feed.event(f.event(1, 0.25)); + await waiting; + f.advance(2000); + const receivedAt = f.time(); + f.feed.event(f.event(2, 0.4)); + f.advance(45_000); + release(); + await f.feed.settled(); + const window = f.store.snapshot("b".repeat(64))[0]; + expect(window?.usedPercent).toBe(40); + expect(window?.observedAt).toBe(receivedAt); + expect(window?.observedAt).not.toBe(f.time()); +}); diff --git a/packages/host-service/src/chat-v3/nativeClaudeUsage.ts b/packages/host-service/src/chat-v3/nativeClaudeUsage.ts new file mode 100644 index 00000000000..266793c42b6 --- /dev/null +++ b/packages/host-service/src/chat-v3/nativeClaudeUsage.ts @@ -0,0 +1,135 @@ +import { randomUUID } from "node:crypto"; +import { + captureNativeClaudeUsageGeneration, + resolveNativeClaudeUsageScope, +} from "../trpc/router/usage/claude"; +import { + ingestNativeClaudeBinding, + isNativeClaudeAccount, + type NativeClaudeAccount, + type NativeClaudeUsageDependencies, +} from "../trpc/router/usage/native-claude-binding"; +import { nativeClaudeUsage } from "../trpc/router/usage/native-claude-usage"; +import { validateSessionAccount } from "../trpc/router/usage/session-account/session-account"; + +const dependencies: NativeClaudeUsageDependencies = { + captureGeneration: captureNativeClaudeUsageGeneration, + resolveScope: resolveNativeClaudeUsageScope, + validateAccount: validateSessionAccount, + store: nativeClaudeUsage, +}; +export function createNativeClaudeChatFeed( + deps = dependencies, + now = Date.now, +) { + const launchId = randomUUID(); + let launched: (NativeClaudeAccount & { generation: string }) | undefined; + let sessionId: string | undefined; + let disposed = false; + let pending = Promise.resolve(); + let queued = 0; + const enqueue = (work: () => Promise) => { + if (queued >= 64) return; + queued++; + pending = pending + .then(work) + .then( + () => {}, + () => {}, + ) + .finally(() => { + queued--; + }); + }; + return { + async launched(account: NativeClaudeAccount | undefined): Promise { + if ( + disposed || + !isNativeClaudeAccount(account) || + !(await deps.validateAccount(account)) + ) + return; + const generation = await deps.captureGeneration( + account.selection, + account.directory, + account.identity, + ); + if (!disposed && generation) launched = { ...account, generation }; + }, + session(id: string): void { + if (disposed || !launched || sessionId) return; + const receivedAt = now(); + sessionId = id; + const account = launched; + enqueue(async () => { + const launch = { launchId, sessionId: id }; + const current = () => + !disposed && launched === account && sessionId === id; + if ( + !current() || + !deps.store.captureLaunch({ + ...launch, + generation: account.generation, + }) + ) + return; + // A restored rate-limit event at counter zero is only a baseline. + await ingestNativeClaudeBinding( + account, + launch, + { + source: "claude_sdk", + receivedAt, + responseCounter: 0, + payload: { + type: "rate_limit_event", + uuid: "native-baseline", + rate_limit_info: {}, + }, + }, + current, + deps, + ); + }); + }, + event(input: { + sessionId: string; + rateLimitInfo: unknown; + eventId?: string; + responseCounter: number; + }): void { + // Capture before the serial queue: proof work must not freshen this event. + const receivedAt = now(); + if (disposed || !launched || input.sessionId !== sessionId) return; + const account = launched; + enqueue(async () => { + await ingestNativeClaudeBinding( + account, + { launchId, sessionId: input.sessionId }, + { + source: "claude_sdk", + receivedAt, + responseCounter: input.responseCounter, + payload: { + type: "rate_limit_event", + uuid: input.eventId ?? "native-rate-limit", + session_id: input.sessionId, + rate_limit_info: input.rateLimitInfo, + }, + }, + () => + !disposed && launched === account && input.sessionId === sessionId, + deps, + ); + }); + }, + settled(): Promise { + return pending; + }, + dispose(): void { + disposed = true; + launched = undefined; + sessionId = undefined; + }, + }; +} diff --git a/packages/host-service/src/chat-v3/resumeAfterUpdate.test.ts b/packages/host-service/src/chat-v3/resumeAfterUpdate.test.ts index 6ccd38f63a0..4df52e26e3f 100644 --- a/packages/host-service/src/chat-v3/resumeAfterUpdate.test.ts +++ b/packages/host-service/src/chat-v3/resumeAfterUpdate.test.ts @@ -1,5 +1,11 @@ -import { describe, expect, test } from "bun:test"; -import { existsSync, mkdtempSync, writeFileSync } from "node:fs"; +import { afterEach, describe, expect, test } from "bun:test"; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { @@ -26,9 +32,13 @@ const UNFINISHED: UnfinishedSession = { pausedPrompts: [], }; -function fakeRuntime(unfinished: UnfinishedSession[]) { +function fakeRuntime(unfinished: UnfinishedSession[], accountBound = false) { const resumed: ResumeSessionInput[] = []; const runtime = { + sessions: { + get: () => (accountBound ? { launchContextJson: "saved-account" } : null), + list: () => [], + }, live: { unfinished: () => unfinished, supports: () => true }, commands: { resumeSession: (input: ResumeSessionInput) => { @@ -40,11 +50,15 @@ function fakeRuntime(unfinished: UnfinishedSession[]) { return { runtime, resumed }; } +const roots: string[] = []; +afterEach(() => { + for (const root of roots.splice(0)) + rmSync(root, { recursive: true, force: true }); +}); function markerIn(contents?: object): string { - const markerPath = join( - mkdtempSync(join(tmpdir(), "chat-resume-")), - "m.json", - ); + const root = mkdtempSync(join(tmpdir(), "chat-resume-")); + roots.push(root); + const markerPath = join(root, "m.json"); if (contents) writeFileSync(markerPath, JSON.stringify(contents)); return markerPath; } @@ -118,3 +132,19 @@ describe("resuming chats after an update", () => { expect(existsSync(markerPath)).toBe(false); }); }); + +test("an account-bound unfinished chat retains its replay marker for account-aware recovery", () => { + const marker = { requestedAt: 1_000, sessions: [UNFINISHED] }; + const markerPath = markerIn(marker); + const { runtime, resumed } = fakeRuntime([], true); + resumeUnfinishedChats({ + markerPath, + runtime: () => runtime, + resolveCwd: () => { + throw new Error("must not launch"); + }, + now: 2_000, + }); + expect(resumed).toEqual([]); + expect(JSON.parse(readFileSync(markerPath, "utf8"))).toEqual(marker); +}); diff --git a/packages/host-service/src/chat-v3/resumeAfterUpdate.ts b/packages/host-service/src/chat-v3/resumeAfterUpdate.ts index 4caef4a0a64..a33e01a8eff 100644 --- a/packages/host-service/src/chat-v3/resumeAfterUpdate.ts +++ b/packages/host-service/src/chat-v3/resumeAfterUpdate.ts @@ -15,6 +15,7 @@ export const CONTINUE_AFTER_UPDATE_PROMPT = "Paradev restarted to install an update, which stopped your work before it finished, including any commands running in the background. Continue where you left off."; const sessionSchema = z.object({ + sessionId: z.string().min(1).optional(), scopeId: z.string().min(1), harness: z.string().min(1), harnessSessionId: z.string().min(1), @@ -57,23 +58,69 @@ export function resumeUnfinishedChats(options: { }): void { if (!existsSync(options.markerPath)) return; const marker = markerSchema.safeParse(readMarker(options.markerPath)); - try { - unlinkSync(options.markerPath); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") { - console.warn("[chat-v3] could not remove the resume marker", error); - return; - } + const age = marker.success + ? (options.now ?? Date.now()) - marker.data.requestedAt + : Number.POSITIVE_INFINITY; + if ( + !marker.success || + !marker.data.sessions?.length || + age > RESUME_MARKER_MAX_AGE_MS + ) { + removeMarker(options.markerPath); + return; } - if (!marker.success || !marker.data.sessions?.length) return; - const age = (options.now ?? Date.now()) - marker.data.requestedAt; - if (age > RESUME_MARKER_MAX_AGE_MS) return; const runtime = options.runtime(); + const retained: unknown[] = []; + const resumable: Array> = []; + const savedSessions = runtime.sessions.list(); for (const entry of marker.data.sessions) { const parsed = sessionSchema.safeParse(entry); if (!parsed.success) continue; - const { interrupted, prompts, ...session } = parsed.data; + const { sessionId, interrupted, prompts, ...session } = parsed.data; + const saved = sessionId ? runtime.sessions.get(sessionId) : undefined; + const accountBound = + saved?.launchContextJson != null || + savedSessions.some( + (row) => + row.launchContextJson !== null && + row.scopeId === session.scopeId && + row.harness === session.harness && + row.harnessSessionId === session.harnessSessionId, + ); + if (accountBound) { + retained.push(entry); + continue; + } + resumable.push(parsed.data); + } + try { + if (retained.length) { + const pending = `${options.markerPath}.${process.pid}.tmp`; + try { + writeFileSync( + pending, + JSON.stringify({ ...marker.data, sessions: retained }), + { mode: 0o600 }, + ); + renameSync(pending, options.markerPath); + } finally { + if (existsSync(pending)) unlinkSync(pending); + } + } else if (!removeMarker(options.markerPath)) return; + } catch (error) { + console.warn( + "[chat-v3] could not preserve the account resume marker", + error, + ); + return; + } + for (const { + sessionId: _storedSessionId, + interrupted, + prompts, + ...session + } of resumable) { if (!runtime.live.supports(session.harness)) continue; try { runtime.commands.resumeSession({ @@ -92,6 +139,17 @@ export function resumeUnfinishedChats(options: { } } +function removeMarker(path: string): boolean { + try { + unlinkSync(path); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; + console.warn("[chat-v3] could not remove the resume marker", error); + return false; + } +} + function readMarker(markerPath: string): unknown { try { return JSON.parse(readFileSync(markerPath, "utf8")); diff --git a/packages/host-service/src/db/account-binding-migration.test.ts b/packages/host-service/src/db/account-binding-migration.test.ts new file mode 100644 index 00000000000..941715044bc --- /dev/null +++ b/packages/host-service/src/db/account-binding-migration.test.ts @@ -0,0 +1,85 @@ +import { Database } from "bun:sqlite"; +import { expect, test } from "bun:test"; +import { + copyFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { runMigrations } from "@superset/shared/sqlite-migrations"; +import { drizzle } from "drizzle-orm/bun-sqlite"; + +test("account migration preserves existing bindings and survives database reopen", () => { + const temp = mkdtempSync(join(tmpdir(), "account-binding-migration-")); + const folder = join(temp, "migrations"); + const source = resolve(import.meta.dir, "../../drizzle"); + const journal = JSON.parse( + readFileSync(join(source, "meta/_journal.json"), "utf8"), + ) as { + entries: { tag: string }[]; + }; + const index = journal.entries.findIndex( + (entry) => entry.tag === "0039_terminal_account_provenance", + ); + expect(index).toBeGreaterThan(0); + mkdirSync(join(folder, "meta"), { recursive: true }); + for (const entry of journal.entries.slice(0, index + 1)) { + copyFileSync( + join(source, `${entry.tag}.sql`), + join(folder, `${entry.tag}.sql`), + ); + } + const writeJournal = (count: number) => + writeFileSync( + join(folder, "meta/_journal.json"), + JSON.stringify({ ...journal, entries: journal.entries.slice(0, count) }), + ); + const dbPath = join(temp, "host.db"); + let sqlite = new Database(dbPath); + try { + writeJournal(index); + runMigrations(drizzle(sqlite), folder); + sqlite.exec( + "INSERT INTO terminal_sessions (id, status, created_at) VALUES ('old-terminal', 'active', 1)", + ); + sqlite.exec( + "INSERT INTO terminal_agent_bindings (terminal_id, workspace_id, agent_id, agent_session_id, started_at, last_event_at, last_event_type, transcript_path) VALUES ('old-terminal', 'workspace', 'claude', 'native-session', 1, 2, 'Stop', '/fixture/transcript.jsonl')", + ); + const original = sqlite + .query, []>( + "SELECT * FROM terminal_agent_bindings", + ) + .get(); + writeJournal(index + 1); + runMigrations(drizzle(sqlite), folder); + expect(sqlite.query("SELECT * FROM terminal_agent_bindings").get()).toEqual( + { ...original, account_json: null, launch_id: null }, + ); + + const account = JSON.stringify({ + agent: "claude", + selection: "review-account", + credentialKind: "subscription", + identity: "fixture-identity", + directory: "/fixture/profile", + }); + sqlite + .query( + "UPDATE terminal_agent_bindings SET account_json = ?, launch_id = ? WHERE terminal_id = ?", + ) + .run(account, "launch-1", "old-terminal"); + sqlite.close(); + sqlite = new Database(dbPath); + runMigrations(drizzle(sqlite), folder); + expect(sqlite.query("SELECT * FROM terminal_agent_bindings").get()).toEqual( + { ...original, account_json: account, launch_id: "launch-1" }, + ); + } finally { + sqlite.close(); + rmSync(temp, { recursive: true, force: true }); + } +}); diff --git a/packages/host-service/src/db/schema.ts b/packages/host-service/src/db/schema.ts index bed932e427f..c688f023fed 100644 --- a/packages/host-service/src/db/schema.ts +++ b/packages/host-service/src/db/schema.ts @@ -60,6 +60,10 @@ export const terminalAgentBindings = sqliteTable( agentId: text("agent_id").notNull().$type(), agentSessionId: text("agent_session_id"), definitionId: text("definition_id").$type(), + // Non-secret account identity and launch provenance. Nullable so existing + // bindings keep their original default-account behavior. + accountJson: text("account_json"), + launchId: text("launch_id"), startedAt: integer("started_at").notNull(), lastEventAt: integer("last_event_at").notNull(), lastEventType: text("last_event_type").notNull(), diff --git a/packages/host-service/src/events/event-bus.test.ts b/packages/host-service/src/events/event-bus.test.ts index 20de6c2cd95..a9b23d1b3d9 100644 --- a/packages/host-service/src/events/event-bus.test.ts +++ b/packages/host-service/src/events/event-bus.test.ts @@ -298,3 +298,19 @@ describe("EventBus fs:watch", () => { } }); }); + +it("broadcasts only an invalidation hint when usage changes", () => { + const eventBus = createEventBus(); + const sent: string[] = []; + eventBus.handleOpen({ + readyState: 1, + send: (message: string) => { + sent.push(message); + }, + close() {}, + }); + eventBus.broadcastUsageChanged({ provider: "claude", occurredAt: 123 }); + expect(sent.map((message) => JSON.parse(message))).toEqual([ + { type: "usage:changed", provider: "claude", occurredAt: 123 }, + ]); +}); diff --git a/packages/host-service/src/events/event-bus.ts b/packages/host-service/src/events/event-bus.ts index a052d4a0c8e..ff68d5a7a94 100644 --- a/packages/host-service/src/events/event-bus.ts +++ b/packages/host-service/src/events/event-bus.ts @@ -279,6 +279,12 @@ export class EventBus { return () => this.terminalLifecycleListeners.delete(listener); } + broadcastUsageChanged( + message: Omit, "type">, + ): void { + this.broadcast({ type: "usage:changed", ...message }); + } + broadcastChatSessionsChanged( message: Omit< Extract, diff --git a/packages/host-service/src/events/index.ts b/packages/host-service/src/events/index.ts index 762bb6523d8..56b8c1b0177 100644 --- a/packages/host-service/src/events/index.ts +++ b/packages/host-service/src/events/index.ts @@ -22,4 +22,5 @@ export type { PortChangedMessage, ServerMessage, TerminalLifecycleMessage, + UsageChangedMessage, } from "./types.ts"; diff --git a/packages/host-service/src/events/types.ts b/packages/host-service/src/events/types.ts index 9cd68c2a273..43dc7479d57 100644 --- a/packages/host-service/src/events/types.ts +++ b/packages/host-service/src/events/types.ts @@ -252,6 +252,12 @@ export interface ChatSessionsChangedMessage { occurredAt: number; } +export interface UsageChangedMessage { + type: "usage:changed"; + provider: "claude"; + occurredAt: number; +} + export type ServerMessage = | FsEventsMessage | GitChangedMessage @@ -266,6 +272,7 @@ export type ServerMessage = | TagFoldersChangedMessage | PageWatchChangedMessage | ChatSessionsChangedMessage + | UsageChangedMessage | EventBusErrorMessage; /** diff --git a/packages/host-service/src/terminal-agents/attribution-token.test.ts b/packages/host-service/src/terminal-agents/attribution-token.test.ts index 1bad37b84d6..8927635181a 100644 --- a/packages/host-service/src/terminal-agents/attribution-token.test.ts +++ b/packages/host-service/src/terminal-agents/attribution-token.test.ts @@ -1,6 +1,26 @@ +import { Database } from "bun:sqlite"; import { expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; import { + chmodSync, + linkSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative } from "node:path"; +import { + configureAttributionTokensForDatabase, issueAttributionToken, + openAttributionTokenAuthority, verifyAttributionToken, } from "./attribution-token"; @@ -18,3 +38,231 @@ test("attribution tokens authorize only their owning terminal", () => { expect(verifyAttributionToken("terminal-a", invalid)).toBe(false); } }); + +test("private authority preserves its issued tokens across restart and isolates another host", () => { + const root = mkdtempSync(join(tmpdir(), "native-attribution-")); + try { + const first = openAttributionTokenAuthority(join(root, "one")), + token = first.issue("terminal"); + expect( + openAttributionTokenAuthority(join(root, "one")).verify( + "terminal", + token, + ), + ).toBe(true); + expect( + openAttributionTokenAuthority(join(root, "two")).verify( + "terminal", + token, + ), + ).toBe(false); + expect( + openAttributionTokenAuthority(join(root, "one")).verify( + "terminal", + "b".repeat(64), + ), + ).toBe(false); + expect(statSync(join(root, "one/key")).mode & 0o777).toBe(0o600); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); +test("restart recovers a key publication interrupted after the hardlink without rotating its secret", () => { + const root = mkdtempSync(join(tmpdir(), "native-key-publication-")); + try { + const directory = join(root, "authority"); + const moduleUrl = new URL("./attribution-token.ts", import.meta.url).href; + const child = spawnSync( + "node", + [ + "--import", + import.meta.resolve("tsx"), + "--input-type=module", + "-e", + ` + import fs from "node:fs"; + import { syncBuiltinESMExports } from "node:module"; + const link = fs.linkSync; + fs.linkSync = (...args) => { link(...args); process.exit(86); }; + syncBuiltinESMExports(); + const { openAttributionTokenAuthority } = await import(${JSON.stringify(moduleUrl)}); + openAttributionTokenAuthority(${JSON.stringify(directory)}); + `, + ], + { + cwd: import.meta.dir, + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOME: root, + CFFIXED_USER_HOME: root, + TMPDIR: root, + SUPERSET_HOME_DIR: join(root, "superset"), + CLAUDE_CONFIG_DIR: join(root, "claude"), + CODEX_HOME: join(root, "codex"), + }, + }, + ); + expect(child.error).toBeUndefined(); + expect(child.status).toBe(86); + const key = join(directory, "key"), + before = readFileSync(key); + expect(statSync(key).nlink).toBe(2); + const restarted = openAttributionTokenAuthority(directory); + expect(readFileSync(key)).toEqual(before); + expect(statSync(key).nlink).toBe(1); + expect(readdirSync(directory)).toEqual(["key"]); + expect( + openAttributionTokenAuthority(directory).verify( + "terminal", + restarted.issue("terminal"), + ), + ).toBe(true); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); +test("key publication recovery refuses unrelated, multiple, permissive and corrupt aliases", () => { + for (const kind of [ + "unrelated", + "external", + "multiple", + "permissive", + "corrupt", + "symlink", + ]) { + if (kind === "permissive" && process.platform === "win32") continue; + const root = mkdtempSync(join(tmpdir(), "native-key-publication-")); + try { + const directory = join(root, "authority"); + openAttributionTokenAuthority(directory); + const key = join(directory, "key"), + before = readFileSync(key); + const temporary = join(directory, `key.${randomUUID()}.tmp`); + if (kind === "unrelated") linkSync(key, join(directory, "unrelated.tmp")); + else if (kind === "external") linkSync(key, join(root, "external")); + else { + linkSync(key, temporary); + if (kind === "multiple") + linkSync(key, join(directory, `key.${randomUUID()}.tmp`)); + if (kind === "permissive") chmodSync(key, 0o644); + if (kind === "corrupt") writeFileSync(key, "corrupt"); + if (kind === "symlink") { + unlinkSync(key); + symlinkSync(temporary, key); + } + } + expect(() => openAttributionTokenAuthority(directory)).toThrow(); + if (kind !== "corrupt") expect(readFileSync(key)).toEqual(before); + } finally { + rmSync(root, { recursive: true, force: true }); + } + } +}); + +test("relative database filenames select the same persisted authority on a child restart, while injected and anonymous databases are exempt", () => { + const root = mkdtempSync(join(tmpdir(), "native-relative-database-")); + try { + const database = join(root, "data", "host.db"); + mkdirSync(join(root, "data")); + const path = relative(process.cwd(), database); + const sqlite = new Database(path); + sqlite.exec("CREATE TABLE synthetic_fixture (id INTEGER PRIMARY KEY)"); + sqlite.close(); + for (const anonymous of ["", ":memory:", " :memory: "]) + configureAttributionTokensForDatabase(anonymous); + configureAttributionTokensForDatabase(database, true); + expect(readdirSync(join(root, "data"))).toEqual(["host.db"]); + configureAttributionTokensForDatabase(path); + expect(readdirSync(join(root, "data"))).toContain(".native-attribution"); + const tokenHash = createHash("sha256") + .update(issueAttributionToken("terminal")) + .digest("hex"); + const moduleUrl = new URL("./attribution-token.ts", import.meta.url).href; + const child = spawnSync( + "node", + [ + "--import", + import.meta.resolve("tsx"), + "--input-type=module", + "-e", + ` + import { createHash } from "node:crypto"; + const { configureAttributionTokensForDatabase, issueAttributionToken } = await import(${JSON.stringify(moduleUrl)}); + configureAttributionTokensForDatabase(${JSON.stringify(path)}); + console.log(createHash("sha256").update(issueAttributionToken("terminal")).digest("hex")); + `, + ], + { + cwd: process.cwd(), + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOME: root, + CFFIXED_USER_HOME: root, + TMPDIR: root, + SUPERSET_HOME_DIR: join(root, "superset"), + CLAUDE_CONFIG_DIR: join(root, "claude"), + CODEX_HOME: join(root, "codex"), + }, + }, + ); + expect(child.error).toBeUndefined(); + expect(child.status).toBe(0); + expect(child.stdout.trim()).toBe(tokenHash); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("unsafe attribution storage uses an isolated temporary authority without rotating the stored key", () => { + const root = mkdtempSync(join(tmpdir(), "native-unavailable-authority-")); + try { + const moduleUrl = new URL("./attribution-token.ts", import.meta.url).href; + const child = spawnSync( + "node", + [ + "--import", + import.meta.resolve("tsx"), + "--input-type=module", + "-e", + ` + import assert from "node:assert/strict"; + import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; + import { join } from "node:path"; + const { configureAttributionTokensForDatabase, issueAttributionToken, verifyAttributionToken } = await import(${JSON.stringify(moduleUrl)}); + const root = ${JSON.stringify(root)}; + const database = join(root, "host.db"); + configureAttributionTokensForDatabase(database); + const prior = issueAttributionToken("owned"); + const key = join(root, ".native-attribution", "key"); + writeFileSync(key, "malformed"); + configureAttributionTokensForDatabase(database); + const temporary = issueAttributionToken("owned"); + assert.equal(verifyAttributionToken("owned", prior), false); + assert.equal(verifyAttributionToken("owned", temporary), true); + assert.equal(verifyAttributionToken("other", temporary), false); + assert.equal(readFileSync(key, "utf8"), "malformed"); + configureAttributionTokensForDatabase(database); + assert.equal(verifyAttributionToken("owned", temporary), true); + assert.throws(() => configureAttributionTokensForDatabase(join(root, "other", "host.db")), /scope changed/); + assert.equal(verifyAttributionToken("owned", temporary), true); + `, + ], + { + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOME: root, + CFFIXED_USER_HOME: root, + TMPDIR: root, + }, + }, + ); + expect(child.error).toBeUndefined(); + expect(child.status).toBe(0); + expect(child.stderr).toContain("host-scoped temporary authority"); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/packages/host-service/src/terminal-agents/attribution-token.ts b/packages/host-service/src/terminal-agents/attribution-token.ts index c7cb6eff935..c3ceb75b482 100644 --- a/packages/host-service/src/terminal-agents/attribution-token.ts +++ b/packages/host-service/src/terminal-agents/attribution-token.ts @@ -1,18 +1,223 @@ -import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { + createHmac, + randomBytes, + randomUUID, + timingSafeEqual, +} from "node:crypto"; +import { + closeSync, + constants, + fstatSync, + fsyncSync, + linkSync, + lstatSync, + mkdirSync, + openSync, + readdirSync, + readFileSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { dirname, join, resolve } from "node:path"; -const secret = randomBytes(32); +function missing(error: unknown) { + return (error as NodeJS.ErrnoException)?.code === "ENOENT"; +} +function secureFile(file: string, limit: number, links = 1): Buffer { + const fd = openSync( + file, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const st = fstatSync(fd); + if ( + !st.isFile() || + st.nlink !== links || + st.size > limit || + (process.platform !== "win32" && + ((st.mode & 0o077) !== 0 || st.uid !== process.getuid?.())) + ) + throw new Error("Unsafe native attribution storage"); + const data = readFileSync(fd); + if (data.length > limit) + throw new Error("Oversized native attribution storage"); + return data; + } finally { + closeSync(fd); + } +} +function writePrivate(file: string, value: Buffer) { + const temporary = `${file}.${randomUUID()}.tmp`; + try { + const fd = openSync( + temporary, + constants.O_WRONLY | + constants.O_CREAT | + constants.O_EXCL | + constants.O_NOFOLLOW, + 0o600, + ); + try { + writeFileSync(fd, value); + fsyncSync(fd); + } finally { + closeSync(fd); + } + linkSync(temporary, file); + } catch (error) { + try { + unlinkSync(temporary); + } catch {} + throw error; + } + try { + unlinkSync(temporary); + } catch (error) { + if (!missing(error)) throw error; + } +} -export function issueAttributionToken(terminalId: string): string { - return createHmac("sha256", secret).update(terminalId).digest("hex"); +export class AttributionTokenAuthority { + constructor( + private readonly secret: Buffer, + readonly directory?: string, + ) {} + issue(terminalId: string): string { + return createHmac("sha256", this.secret).update(terminalId).digest("hex"); + } + verify(terminalId: string, token: string | undefined): boolean { + return ( + typeof token === "string" && + /^[a-f0-9]{64}$/.test(token) && + timingSafeEqual( + Buffer.from(token, "hex"), + Buffer.from(this.issue(terminalId), "hex"), + ) + ); + } +} + +function recoverPublishedKey(directory: string, key: string): void { + let original: ReturnType; + try { + original = lstatSync(key); + } catch (error) { + if (missing(error)) return; + throw error; + } + if (original.nlink !== 2) return; + const raw = secureFile(key, 65, 2); + if (!/^[a-f0-9]{64}\n$/.test(raw.toString("utf8"))) + throw new Error("Invalid native attribution key; refusing to rotate it"); + const aliases = readdirSync(directory).filter((name) => { + if (name === "key") return false; + const candidate = lstatSync(join(directory, name)); + return candidate.dev === original.dev && candidate.ino === original.ino; + }); + const aliasName = aliases[0]; + if ( + aliases.length !== 1 || + !aliasName || + !/^key\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/.test( + aliasName, + ) + ) + throw new Error("Unsafe native attribution storage"); + const alias = join(directory, aliasName); + if (!secureFile(alias, 65, 2).equals(raw)) + throw new Error("Unsafe native attribution storage"); + for (const file of [key, alias]) { + const current = lstatSync(file); + if ( + current.dev !== original.dev || + current.ino !== original.ino || + current.nlink !== 2 + ) + throw new Error("Native attribution storage changed during recovery"); + } + unlinkSync(alias); } +export function openAttributionTokenAuthority( + directory: string, +): AttributionTokenAuthority { + const root = resolve(directory); + try { + mkdirSync(root, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") throw error; + } + const stat = lstatSync(root); + if ( + !stat.isDirectory() || + stat.isSymbolicLink() || + (process.platform !== "win32" && + ((stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())) + ) + throw new Error("Unsafe native attribution directory"); + const path = join(root, "key"); + recoverPublishedKey(root, path); + let raw: Buffer; + try { + raw = secureFile(path, 65); + } catch (error) { + if (!missing(error)) throw error; + try { + writePrivate(path, Buffer.from(`${randomBytes(32).toString("hex")}\n`)); + } catch (createError) { + if ((createError as NodeJS.ErrnoException)?.code !== "EEXIST") + throw createError; + } + raw = secureFile(path, 65); + } + if (!/^[a-f0-9]{64}\n$/.test(raw.toString("utf8"))) + throw new Error("Invalid native attribution key; refusing to rotate it"); + return new AttributionTokenAuthority( + Buffer.from(raw.toString("utf8").trim(), "hex"), + root, + ); +} +let authority = new AttributionTokenAuthority(randomBytes(32)); +let temporaryDirectory: string | undefined; +export function configureAttributionTokens(directory: string): void { + const next = resolve(directory); + if (authority.directory && authority.directory !== next) + throw new Error("Native attribution host scope changed"); + authority = openAttributionTokenAuthority(next); + temporaryDirectory = undefined; +} +export function issueAttributionToken(terminalId: string): string { + return authority.issue(terminalId); +} export function verifyAttributionToken( terminalId: string, token: string | undefined, ): boolean { - if (!token || !/^[a-f0-9]{64}$/.test(token)) return false; - return timingSafeEqual( - Buffer.from(token, "hex"), - Buffer.from(issueAttributionToken(terminalId), "hex"), - ); + return authority.verify(terminalId, token); +} + +export function configureAttributionTokensForDatabase( + dbPath: string, + injectedDatabase = false, +): void { + const filename = dbPath.trim(); + if (injectedDatabase || filename === "" || filename === ":memory:") return; + const directory = join(dirname(resolve(filename)), ".native-attribution"); + if (authority.directory && authority.directory !== directory) + throw new Error("Native attribution host scope changed"); + if (temporaryDirectory === directory) return; + try { + configureAttributionTokens(directory); + } catch (error) { + authority = new AttributionTokenAuthority(randomBytes(32), directory); + temporaryDirectory = directory; + console.warn( + "[native-attribution] Private storage is unavailable; using a host-scoped temporary authority. Existing launch tokens cannot be restored.", + { + code: + (error as NodeJS.ErrnoException | null)?.code ?? "INVALID_STORAGE", + directory, + }, + ); + } } diff --git a/packages/host-service/src/terminal-agents/background-adoption.test.ts b/packages/host-service/src/terminal-agents/background-adoption.test.ts new file mode 100644 index 00000000000..54f2221fd59 --- /dev/null +++ b/packages/host-service/src/terminal-agents/background-adoption.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "bun:test"; +import { + backgroundAdoptionLaunchId, + backgroundWorkerBirthHash, + parseBackgroundAdoptionLaunchId, +} from "./background-adoption"; + +test("an adoption grant binds only its exact source launch, account, worktree and worker incarnation", () => { + const input = { + source: { + terminalId: "old", + workspaceId: "workspace", + launchId: "original-launch", + sessionId: "native-session", + account: { + pinned: true as const, + agent: "claude" as const, + selection: "/profile", + directory: "/profile", + identity: "a".repeat(64), + credentialKind: "subscription" as const, + }, + definitionId: "claude", + startedAt: 10, + }, + terminalId: "new", + cwd: "/project", + adoptedAt: 20, + worker: { pid: 123, birthHash: backgroundWorkerBirthHash("birth") }, + }; + const grant = backgroundAdoptionLaunchId(input); + expect(grant.length).toBeLessThanOrEqual(128); + expect(parseBackgroundAdoptionLaunchId(grant)).toEqual(input.worker); + for (const changed of [ + { ...input, terminalId: "other" }, + { ...input, cwd: "/other" }, + { ...input, adoptedAt: 21 }, + { ...input, source: { ...input.source, launchId: "new-launch" } }, + { + ...input, + source: { + ...input.source, + account: { ...input.source.account, identity: "b".repeat(64) }, + }, + }, + { + ...input, + worker: { + ...input.worker, + birthHash: backgroundWorkerBirthHash("reused"), + }, + }, + ]) + expect(backgroundAdoptionLaunchId(changed)).not.toBe(grant); + expect(parseBackgroundAdoptionLaunchId("unrelated-new-launch")).toBeNull(); +}); diff --git a/packages/host-service/src/terminal-agents/background-adoption.ts b/packages/host-service/src/terminal-agents/background-adoption.ts new file mode 100644 index 00000000000..b37fa9b1aaa --- /dev/null +++ b/packages/host-service/src/terminal-agents/background-adoption.ts @@ -0,0 +1,65 @@ +import { createHash } from "node:crypto"; +import type { SessionAccount } from "../trpc/router/usage/session-account/session-account"; +export interface BackgroundAdoptionSource { + terminalId: string; + workspaceId: string; + launchId: string; + sessionId: string; + account: SessionAccount; + definitionId: string | null; + startedAt: number; +} +export interface BackgroundAdoptionGrantInput { + source: BackgroundAdoptionSource; + terminalId: string; + cwd: string; + adoptedAt: number; + worker: { pid: number; birthHash: string }; +} +function hash(value: unknown) { + return createHash("sha256").update(JSON.stringify(value)).digest("hex"); +} +export function backgroundWorkerBirthHash(birth: string) { + return hash(birth).slice(0, 32); +} +export function backgroundAdoptionLaunchId( + input: BackgroundAdoptionGrantInput, +): string { + const a = input.source.account; + const scope = [ + a.agent, + a.selection, + a.directory, + a.identity, + a.credentialKind, + a.pinned === true, + a.conflict === true, + ]; + const digest = hash([ + "background-adoption-v1", + input.source.terminalId, + input.source.workspaceId, + input.source.launchId, + input.source.sessionId, + input.source.definitionId, + input.source.startedAt, + scope, + input.terminalId, + input.cwd, + input.adoptedAt, + input.worker.pid, + input.worker.birthHash, + ]); + return `bg1:${input.worker.pid}:${input.worker.birthHash}:${digest}`; +} +export function parseBackgroundAdoptionLaunchId( + launchId: string | null | undefined, +) { + const match = /^bg1:([1-9]\d{0,9}):([a-f0-9]{32}):[a-f0-9]{64}$/.exec( + launchId ?? "", + ); + const pid = Number(match?.[1]); + return match && Number.isSafeInteger(pid) && pid <= 2_147_483_647 + ? { pid, birthHash: match[2] as string } + : null; +} diff --git a/packages/host-service/src/terminal-agents/claude-background-session.test.ts b/packages/host-service/src/terminal-agents/claude-background-session.test.ts new file mode 100644 index 00000000000..d42a4cb4127 --- /dev/null +++ b/packages/host-service/src/terminal-agents/claude-background-session.test.ts @@ -0,0 +1,398 @@ +import { expect, test } from "bun:test"; +import { + type ClaudeBackgroundSession, + type ClaudeBackgroundSessionDeps, + type ClaudeBackgroundSessionTarget, + type ClaudeBackgroundWorkerProof, + discoverClaudeBackgroundSession, + liveClaudeAttachmentName, + parseClaudeBackgroundSessions, +} from "./claude-background-session"; + +const sessionId = "11111111-2222-4333-8444-555555555555"; +const backgroundId = "aabbccdd"; +const target: ClaudeBackgroundSessionTarget = { + sessionId, + configDir: "/fixture/profile", + worktreePath: "/fixture/project", +}; +const row = { + kind: "background", + id: backgroundId, + sessionId, + cwd: target.worktreePath, + startedAt: 100, + state: "working", + pid: 101, + status: "busy", +}; +const worker: ClaudeBackgroundWorkerProof = { + pid: 101, + birth: "1000000:123456", + executable: "/fixture/claude/2.1.301", + configDir: target.configDir, + worktreePath: target.worktreePath, + sessionId, + backgroundId, +}; +function fixture(rows: unknown[] = [row]) { + let runs = 0, + validations = 0, + proofs = 0; + const deps: ClaudeBackgroundSessionDeps = { + runDiscovery: async (request) => { + runs++; + expect(request.args).toEqual([ + "agents", + "--json", + "--cwd", + target.worktreePath, + ]); + expect(request.configDir).toBe(target.configDir); + expect(request.cwd).toBe(target.worktreePath); + expect(request.timeoutMs).toBe(1500); + expect(request.maxBuffer).toBe(256 * 1024); + expect(request.signal.aborted).toBe(false); + return JSON.stringify(rows); + }, + validateScope: async () => { + validations++; + return true; + }, + verifyWorker: async (expected, signal) => { + proofs++; + expect(expected).toEqual({ ...target, pid: row.pid, backgroundId }); + expect(signal.aborted).toBe(false); + return { ...worker }; + }, + canonicalize: async (value) => value, + now: () => 200, + }; + return { deps, counts: () => ({ runs, validations, proofs }) }; +} + +test("the parser keeps supported background facts and optional names, excluding private prompt fields and interactive rows", () => { + expect( + parseClaudeBackgroundSessions( + JSON.stringify([ + { kind: "interactive" }, + { ...row, name: "untrusted title", waitingFor: "private prompt" }, + ]), + ), + ).toEqual([ + { + id: backgroundId, + name: "untrusted title", + sessionId, + cwd: target.worktreePath, + startedAt: 100, + state: "working", + pid: 101, + status: "busy", + }, + ]); +}); + +for (const version of [ + "2.1.290 (Claude Code)", + "2.1.302 (Claude Code)", + "2.1.303 (Claude Code)", + "2.1.310 (Claude Code)", +]) { + test(`live-only attachment on ${version} requires a unique full-profile name`, () => { + const named = { + ...row, + state: "working", + status: "busy", + name: "Medusa fixture", + } satisfies ClaudeBackgroundSession; + expect( + liveClaudeAttachmentName( + JSON.stringify([ + named, + { + ...row, + id: "other", + sessionId: "11111111-2222-4333-8444-666666666666", + cwd: "/other", + name: "unrelated", + }, + ]), + named, + `${version}\n`, + ), + ).toBe("Medusa fixture"); + for (const other of [ + { ...row, id: "other", name: "MEDUSA FIXTURE secondary", cwd: "/other" }, + { + ...row, + id: "other", + name: "Medusa fixture", + state: "stopped", + cwd: "/other", + }, + { kind: "interactive", name: "Medusa fixture" }, + { ...row, id: "other" }, + ]) + expect(() => + liveClaudeAttachmentName( + JSON.stringify([named, other]), + named, + version, + ), + ).toThrow("could not be verified"); + for (const name of [ + "cf9dc1cc", + "cf9dc1cc-3d55-4149-8a3b-c16be579690b", + "dead", + "--help", + " Medusa fixture", + "Medusa\nfixture", + ]) + expect(() => + liveClaudeAttachmentName( + JSON.stringify([{ ...row, name }]), + { ...named, name }, + version, + ), + ).toThrow("could not be verified"); + }); +} + +test("live-only attachment refuses unqualified and unknown native versions", () => { + const named = { + ...row, + state: "working", + status: "busy", + name: "Medusa fixture", + } satisfies ClaudeBackgroundSession; + for (const version of [ + "2.1.289 (Claude Code)", + "2.1.311 (Claude Code)", + "2.1.302", + "2.1.303", + "garbage", + ]) + expect(() => + liveClaudeAttachmentName(JSON.stringify([named]), named, version), + ).toThrow("could not be verified"); +}); + +test("malformed or oversized discovery output is refused without leaking its content", () => { + for (const stdout of [ + "private invalid output", + "{}", + JSON.stringify([{ ...row, id: "--dangerous-option" }]), + JSON.stringify([{ ...row, pid: 0 }]), + JSON.stringify([{ ...row, state: "new-unsupported-state" }]), + JSON.stringify([row, row]), + JSON.stringify( + Array.from({ length: 1025 }, () => ({ kind: "interactive" })), + ), + " ".repeat(256 * 1024 + 1), + ]) + expect(() => parseClaudeBackgroundSessions(stdout)).toThrow( + "could not be verified", + ); +}); + +test("an exact live background session yields only its attach argv and two stable worker proofs", async () => { + const f = fixture(); + const result = await discoverClaudeBackgroundSession( + { ...target, backgroundId }, + f.deps, + ); + expect(result?.attachArgs).toEqual(["attach", backgroundId]); + expect(result?.workerBefore).toEqual(worker); + expect(result?.workerAfter).toEqual(worker); + expect(result?.target).toEqual({ ...target, backgroundId }); + expect(result?.observedAt).toBe(200); + expect(result?.nonAtomicAttach).toBe(true); + expect(f.counts()).toEqual({ runs: 1, validations: 2, proofs: 2 }); +}); + +for (const [state, status] of [ + ["blocked", "waiting"], + ["done", "idle"], +]) { + test(`a live ${state} worker remains attachable without starting a new turn`, async () => { + const f = fixture([{ ...row, state, status }]); + expect( + (await discoverClaudeBackgroundSession(target, f.deps))?.attachArgs, + ).toEqual(["attach", backgroundId]); + }); +} + +test("names, matching prefixes and latest timestamps cannot select a different session", async () => { + const f = fixture([ + { + ...row, + sessionId: "11111111-2222-4333-8444-666666666666", + name: sessionId, + startedAt: Number.MAX_SAFE_INTEGER, + }, + ]); + expect(await discoverClaudeBackgroundSession(target, f.deps)).toBeNull(); + expect(f.counts()).toEqual({ runs: 1, validations: 2, proofs: 0 }); +}); + +test("ambiguous exact-session rows are refused unless the caller already knows the exact background ID", async () => { + const f = fixture([row, { ...row, id: "otherid" }]); + await expect(discoverClaudeBackgroundSession(target, f.deps)).rejects.toThrow( + "could not be verified", + ); + expect( + (await discoverClaudeBackgroundSession({ ...target, backgroundId }, f.deps)) + ?.attachArgs, + ).toEqual(["attach", backgroundId]); + await expect( + discoverClaudeBackgroundSession( + { ...target, backgroundId: "absent" }, + f.deps, + ), + ).rejects.toThrow("could not be verified"); +}); + +for (const [name, patch] of [ + ["stopped", { state: "stopped" }], + ["failed", { state: "failed" }], + ["exited without pid", { pid: undefined }], + ["not confirmed alive", { status: undefined }], + ["wrong worktree", { cwd: "/fixture/other" }], +] as const) { + test(`a ${name} row never produces attach or a resume fallback`, async () => { + const f = fixture([{ ...row, ...patch }]); + await expect( + discoverClaudeBackgroundSession(target, f.deps), + ).rejects.toThrow("could not be verified"); + expect(f.counts().proofs).toBe(0); + }); +} + +for (const [name, patch] of [ + ["dead worker", null], + ["wrong pid", { pid: 999 }], + ["wrong session", { sessionId: "99999999-2222-4333-8444-555555555555" }], + ["wrong background id", { backgroundId: "otherid" }], + ["wrong profile", { configDir: "/fixture/other-profile" }], + ["wrong cwd", { worktreePath: "/fixture/other-project" }], + ["unproven birth", { birth: "" }], +] as const) { + test(`independent ${name} evidence is refused`, async () => { + const f = fixture(); + f.deps.verifyWorker = async () => + patch === null ? null : { ...worker, ...patch }; + await expect( + discoverClaudeBackgroundSession(target, f.deps), + ).rejects.toThrow("could not be verified"); + }); +} + +test("PID reuse or executable replacement between proof snapshots is refused", async () => { + for (const patch of [ + { birth: "new birth" }, + { executable: "/fixture/claude/2.1.302" }, + ]) { + const f = fixture(); + let checks = 0; + f.deps.verifyWorker = async () => + ++checks === 1 ? { ...worker } : { ...worker, ...patch }; + await expect( + discoverClaudeBackgroundSession(target, f.deps), + ).rejects.toThrow("could not be verified"); + } +}); + +test("a profile identity change during verification prevents attach", async () => { + const f = fixture(); + let validations = 0; + f.deps.validateScope = async () => ++validations === 1; + await expect(discoverClaudeBackgroundSession(target, f.deps)).rejects.toThrow( + "could not be verified", + ); + expect(f.counts().proofs).toBe(1); +}); + +test("canonical aliases remain scoped and mutating the caller cannot retarget discovery", async () => { + const f = fixture([{ ...row, cwd: "/fixture/project-alias" }]); + const mutable = { ...target, configDir: "/fixture/profile-alias" }; + f.deps.canonicalize = async (value) => value.replace(/-alias$/, ""); + const run = f.deps.runDiscovery; + f.deps.runDiscovery = async (request) => { + mutable.configDir = "/fixture/attacker"; + mutable.sessionId = "99999999-2222-4333-8444-555555555555"; + return run(request); + }; + expect( + (await discoverClaudeBackgroundSession(mutable, f.deps))?.target, + ).toEqual(target); +}); + +test("a manually fired deadline cancels discovery and late results cannot trigger worker checks", async () => { + const f = fixture(); + let fire!: () => void; + let finish!: (value: string) => void; + let seenSignal: AbortSignal | undefined; + let cleaned = false; + f.deps.schedule = (callback, delay) => { + expect(delay).toBe(1500); + fire = callback; + return () => { + cleaned = true; + }; + }; + f.deps.runDiscovery = async ({ signal }) => { + seenSignal = signal; + return new Promise((resolve) => { + finish = resolve; + }); + }; + const result = discoverClaudeBackgroundSession(target, f.deps).catch( + (error: Error) => error.message, + ); + for (let step = 0; step < 16; step++) await Promise.resolve(); + fire(); + expect(await result).toContain("could not be verified"); + expect(seenSignal?.aborted).toBe(true); + expect(cleaned).toBe(true); + finish(JSON.stringify([row])); + for (let step = 0; step < 16; step++) await Promise.resolve(); + expect(f.counts().proofs).toBe(0); +}); + +test("a caller abort or failed scope check cannot launch discovery", async () => { + const f = fixture(); + const controller = new AbortController(); + controller.abort(); + f.deps.signal = controller.signal; + await expect(discoverClaudeBackgroundSession(target, f.deps)).rejects.toThrow( + "could not be verified", + ); + expect(f.counts().runs).toBe(0); + f.deps.signal = undefined; + f.deps.validateScope = async () => false; + await expect(discoverClaudeBackgroundSession(target, f.deps)).rejects.toThrow( + "could not be verified", + ); + expect(f.counts().runs).toBe(0); +}); + +test("only documented non-private waiting reason categories enter the status reader", () => { + expect( + parseClaudeBackgroundSessions( + JSON.stringify([ + { + ...row, + state: "blocked", + status: "waiting", + waitingFor: "input needed", + }, + ]), + )[0]?.waitingFor, + ).toBe("input needed"); + expect( + parseClaudeBackgroundSessions( + JSON.stringify([{ ...row, waitingFor: "private free-text question" }]), + )[0]?.waitingFor, + ).toBeUndefined(); +}); diff --git a/packages/host-service/src/terminal-agents/claude-background-session.ts b/packages/host-service/src/terminal-agents/claude-background-session.ts new file mode 100644 index 00000000000..92815c40029 --- /dev/null +++ b/packages/host-service/src/terminal-agents/claude-background-session.ts @@ -0,0 +1,376 @@ +import { realpath } from "node:fs/promises"; +import { isAbsolute } from "node:path"; + +const MAX_BYTES = 256 * 1024; +const MAX_ROWS = 1024; +const TIMEOUT_MS = 1500; +const SESSION_ID = + /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +const BACKGROUND_ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/; + +export interface ClaudeBackgroundSession { + id: string; + name?: string; + sessionId?: string; + cwd: string; + startedAt: number; + state: "working" | "blocked" | "done" | "failed" | "stopped"; + pid?: number; + status?: "busy" | "waiting" | "idle"; + waitingFor?: string; +} +export interface ClaudeBackgroundSessionTarget { + sessionId: string; + configDir: string; + worktreePath: string; + backgroundId?: string; +} +export interface ClaudeBackgroundWorkerProof { + pid: number; + birth: string; + executable: string; + configDir: string; + worktreePath: string; + sessionId: string; + backgroundId: string; +} +export interface ClaudeBackgroundDiscoveryRequest { + args: readonly ["agents", "--json", "--cwd", string]; + configDir: string; + cwd: string; + timeoutMs: number; + maxBuffer: number; + signal: AbortSignal; +} +export interface ClaudeBackgroundSessionDeps { + runDiscovery: (request: ClaudeBackgroundDiscoveryRequest) => Promise; + validateScope: ( + target: Readonly, + signal: AbortSignal, + ) => Promise; + verifyWorker: ( + expected: Readonly< + ClaudeBackgroundSessionTarget & { backgroundId: string; pid: number } + >, + signal: AbortSignal, + ) => Promise; + canonicalize?: (path: string) => Promise; + now?: () => number; + signal?: AbortSignal; + schedule?: (callback: () => void, delay: number) => () => void; +} +export interface ClaudeBackgroundAttachProof { + candidate: Readonly; + target: Readonly; + workerBefore: Readonly; + workerAfter: Readonly; + attachArgs: readonly ["attach", string]; + observedAt: number; + nonAtomicAttach: true; +} +function refuse(): never { + throw new Error( + "The live Claude background session could not be verified. Nothing was attached.", + ); +} +function hasControlCharacters(value: string) { + return [...value].some((character) => { + const code = character.charCodeAt(0); + return code < 32 || code === 127; + }); +} +function path(value: unknown): value is string { + return ( + typeof value === "string" && + value.length <= 4096 && + isAbsolute(value) && + !hasControlCharacters(value) + ); +} +function pid(value: unknown): value is number { + return ( + typeof value === "number" && + Number.isSafeInteger(value) && + value > 0 && + value <= 2_147_483_647 + ); +} +function record(value: unknown): value is Record { + return !!value && typeof value === "object" && !Array.isArray(value); +} +export function parseClaudeBackgroundSessions( + stdout: string, +): ClaudeBackgroundSession[] { + if (Buffer.byteLength(stdout, "utf8") > MAX_BYTES) return refuse(); + let rows: unknown; + try { + rows = JSON.parse(stdout); + } catch { + return refuse(); + } + if (!Array.isArray(rows) || rows.length > MAX_ROWS) return refuse(); + const result: ClaudeBackgroundSession[] = []; + const ids = new Set(); + for (const row of rows) { + if (!record(row)) return refuse(); + if (row.kind === "interactive") continue; + if ( + row.kind !== "background" || + typeof row.id !== "string" || + !BACKGROUND_ID.test(row.id) || + ids.has(row.id) || + !path(row.cwd) || + !Number.isSafeInteger(row.startedAt) || + (row.startedAt as number) < 0 || + !["working", "blocked", "done", "failed", "stopped"].includes( + row.state as string, + ) + ) + return refuse(); + if ( + row.sessionId != null && + (typeof row.sessionId !== "string" || !SESSION_ID.test(row.sessionId)) + ) + return refuse(); + if (row.pid != null && !pid(row.pid)) return refuse(); + if ( + row.status != null && + !["busy", "waiting", "idle"].includes(row.status as string) + ) + return refuse(); + if ( + row.name != null && + (typeof row.name !== "string" || + !row.name.trim() || + row.name.length > 256 || + hasControlCharacters(row.name)) + ) + return refuse(); + ids.add(row.id); + result.push({ + id: row.id, + ...(row.name == null ? {} : { name: row.name as string }), + cwd: row.cwd, + startedAt: row.startedAt as number, + state: row.state as ClaudeBackgroundSession["state"], + ...(typeof row.waitingFor === "string" && + [ + "permission prompt", + "input needed", + "sandbox request", + "worker request", + "dialog open", + ].includes(row.waitingFor) + ? { waitingFor: row.waitingFor } + : {}), + ...(row.sessionId == null ? {} : { sessionId: row.sessionId as string }), + ...(row.pid == null ? {} : { pid: row.pid as number }), + ...(row.status == null + ? {} + : { status: row.status as ClaudeBackgroundSession["status"] }), + }); + } + return result; +} + +export function supportsLiveClaudeAttachment(version: string): boolean { + const match = /^2\.1\.(\d+) \(Claude Code\)$/.exec(version.trim()); + const patch = Number(match?.[1]); + return !!match && patch >= 290 && patch <= 310; +} + +/** Names use the provider's live-only lookup; IDs are never substituted. */ +export function liveClaudeAttachmentName( + stdout: string, + target: Readonly, + version: string, +): string { + if (!supportsLiveClaudeAttachment(version)) return refuse(); + const rows = parseClaudeBackgroundSessions(stdout); + const found = rows.filter((row) => row.id === target.id); + const current = found[0]; + if ( + found.length !== 1 || + !current || + current.sessionId !== target.sessionId || + current.pid !== target.pid || + current.cwd !== target.cwd || + current.startedAt !== target.startedAt || + current.state === "failed" || + current.state === "stopped" || + !current.status || + !current.name || + current.name !== current.name.trim() || + current.name.startsWith("-") || + /^[a-f0-9-]+$/i.test(current.name) || + /^[a-f0-9]{8}/i.test(current.name) + ) + return refuse(); + const name = current.name; + const rawRows: unknown = JSON.parse(stdout); + if (!Array.isArray(rawRows)) return refuse(); + const matches = rawRows.filter((row) => { + if (record(row) && row.kind === "interactive" && row.name == null) + return false; + if ( + !record(row) || + typeof row.name !== "string" || + !row.name.trim() || + hasControlCharacters(row.name) + ) + return refuse(); + return row.name.toLowerCase().includes(name.toLowerCase()); + }); + if ( + matches.length !== 1 || + !record(matches[0]) || + matches[0].id !== current.id + ) + return refuse(); + return name; +} + +export async function discoverClaudeBackgroundSession( + input: ClaudeBackgroundSessionTarget, + deps: ClaudeBackgroundSessionDeps, +): Promise { + const original = Object.freeze({ ...input }); + if ( + !SESSION_ID.test(original.sessionId) || + !path(original.configDir) || + !path(original.worktreePath) || + (original.backgroundId !== undefined && + !BACKGROUND_ID.test(original.backgroundId)) + ) + return refuse(); + const controller = new AbortController(); + const signal = deps.signal + ? AbortSignal.any([controller.signal, deps.signal]) + : controller.signal; + const schedule = + deps.schedule ?? + ((callback: () => void, delay: number) => { + const timer = setTimeout(callback, delay); + return () => clearTimeout(timer); + }); + let cancelTimer: (() => void) | undefined; + let onAbort: (() => void) | undefined; + try { + signal.throwIfAborted(); + return await Promise.race([ + (async () => { + const canonicalize = deps.canonicalize ?? realpath; + const [configDir, worktreePath] = await Promise.all([ + canonicalize(original.configDir), + canonicalize(original.worktreePath), + ]); + if (!path(configDir) || !path(worktreePath)) return refuse(); + const target = Object.freeze({ ...original, configDir, worktreePath }); + signal.throwIfAborted(); + if (!(await deps.validateScope(target, signal))) return refuse(); + signal.throwIfAborted(); + const rows = parseClaudeBackgroundSessions( + await deps.runDiscovery({ + args: ["agents", "--json", "--cwd", worktreePath], + configDir, + cwd: worktreePath, + timeoutMs: TIMEOUT_MS, + maxBuffer: MAX_BYTES, + signal, + }), + ); + signal.throwIfAborted(); + const matchingSession = rows.filter( + (row) => row.sessionId === target.sessionId, + ); + const matches = target.backgroundId + ? matchingSession.filter((row) => row.id === target.backgroundId) + : matchingSession; + if (matches.length === 0) { + if (matchingSession.length) return refuse(); + if (!(await deps.validateScope(target, signal))) return refuse(); + signal.throwIfAborted(); + return null; + } + if (matches.length !== 1) return refuse(); + const candidate = matches[0]; + if ( + !candidate || + !pid(candidate.pid) || + !candidate.status || + candidate.state === "failed" || + candidate.state === "stopped" || + (await canonicalize(candidate.cwd)) !== worktreePath + ) + return refuse(); + const expected = Object.freeze({ + ...target, + backgroundId: candidate.id, + pid: candidate.pid, + }); + async function verify() { + signal.throwIfAborted(); + const observed = await deps.verifyWorker(expected, signal); + signal.throwIfAborted(); + if ( + !observed || + observed.pid !== candidate?.pid || + observed.sessionId !== target.sessionId || + observed.backgroundId !== candidate?.id || + typeof observed.birth !== "string" || + !observed.birth.trim() || + observed.birth.length > 256 || + hasControlCharacters(observed.birth) || + !path(observed.executable) || + (await canonicalize(observed.configDir)) !== configDir || + (await canonicalize(observed.worktreePath)) !== worktreePath + ) + return refuse(); + const executable = await canonicalize(observed.executable); + if (!path(executable)) return refuse(); + signal.throwIfAborted(); + return Object.freeze({ + pid: observed.pid, + birth: observed.birth, + executable, + configDir, + worktreePath, + sessionId: observed.sessionId, + backgroundId: observed.backgroundId, + }); + } + const workerBefore = await verify(); + signal.throwIfAborted(); + if (!(await deps.validateScope(target, signal))) return refuse(); + const workerAfter = await verify(); + if ( + workerBefore.birth !== workerAfter.birth || + workerBefore.executable !== workerAfter.executable + ) + return refuse(); + signal.throwIfAborted(); + return Object.freeze({ + candidate: Object.freeze({ ...candidate, cwd: worktreePath }), + target, + workerBefore, + workerAfter, + attachArgs: Object.freeze(["attach", candidate.id] as const), + observedAt: (deps.now ?? Date.now)(), + nonAtomicAttach: true as const, + }); + })(), + new Promise((_, reject) => { + onAbort = () => + reject(new Error("Claude background discovery was cancelled.")); + signal.addEventListener("abort", onAbort, { once: true }); + cancelTimer = schedule(() => controller.abort(), TIMEOUT_MS); + }), + ]); + } catch { + return refuse(); + } finally { + cancelTimer?.(); + if (onAbort) signal.removeEventListener("abort", onAbort); + controller.abort(); + } +} diff --git a/packages/host-service/src/terminal-agents/claude-session-writers.test.ts b/packages/host-service/src/terminal-agents/claude-session-writers.test.ts new file mode 100644 index 00000000000..34e8c687bce --- /dev/null +++ b/packages/host-service/src/terminal-agents/claude-session-writers.test.ts @@ -0,0 +1,347 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { randomUUID } from "node:crypto"; +import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + findClaudeSessionWriterDetails, + findClaudeSessionWriters, + inspectClaudeWriterOwner, + readProcessStarts, +} from "./claude-session-writers"; + +const homes: string[] = []; +const start = "Thu Oct 1 01:41:15 2026"; +const normalized = "Thu Oct 1 01:41:15 2026"; + +afterEach(async () => { + await Promise.all( + homes.splice(0).map((home) => rm(home, { recursive: true, force: true })), + ); +}); + +async function fixture() { + const home = await mkdtemp(join(tmpdir(), "claude-writer-test-")); + homes.push(home); + await mkdir(join(home, "sessions")); + const sessionId = randomUUID(); + return { + home, + input: { sessionId, directories: [home] }, + write: (pid: number, extra: Record = {}) => + writeFile( + join(home, "sessions", `${pid}.json`), + JSON.stringify({ + pid, + procStart: start, + pidDomain: "darwin", + sessionId, + ...extra, + }), + ), + }; +} + +describe("native Claude writer evidence", () => { + test("preserves owner details without changing the numeric writer API", async () => { + const f = await fixture(); + await f.write(101, { entrypoint: "claude-desktop", kind: "interactive" }); + const processStarts = async () => new Map([[101, normalized]]); + expect( + await findClaudeSessionWriters(f.input, { + platform: "darwin", + processStarts, + }), + ).toEqual([101]); + expect( + await findClaudeSessionWriterDetails(f.input, { + platform: "darwin", + processStarts, + owner: async () => "claude-desktop", + }), + ).toEqual([ + { + pid: 101, + procStart: normalized, + entrypoint: "claude-desktop", + kind: "interactive", + owner: "claude-desktop", + }, + ]); + }); + test("does not return an owner for a PID reused during inspection", async () => { + const f = await fixture(); + await f.write(101); + let reads = 0; + expect( + await findClaudeSessionWriterDetails(f.input, { + platform: "darwin", + processStarts: async () => + new Map([ + [101, ++reads === 1 ? normalized : "Thu Oct 1 01:42:15 2026"], + ]), + owner: async () => "claude-desktop", + }), + ).toEqual([]); + }); + test("bounds expensive owner inspection while retaining every blocking writer", async () => { + const f = await fixture(); + await Promise.all( + Array.from({ length: 9 }, (_, index) => f.write(101 + index)), + ); + const result = await findClaudeSessionWriterDetails(f.input, { + platform: "darwin", + processStarts: async (pids) => + new Map(pids.map((pid) => [pid, normalized])), + owner: async () => { + throw new Error("Must not inspect an already ambiguous writer set"); + }, + }); + expect(result).toHaveLength(9); + expect(result.every(({ owner }) => owner === "unknown")).toBe(true); + }); + test("matches the exact session and process incarnation", async () => { + const f = await fixture(); + await f.write(101); + await f.write(102, { sessionId: randomUUID() }); + await f.write(103); + expect( + await findClaudeSessionWriters(f.input, { + platform: "darwin", + processStarts: async (pids) => { + expect(pids.sort()).toEqual([101, 103]); + return new Map([[101, normalized]]); + }, + }), + ).toEqual([101]); + }); + test("ignores a reused PID with a different start fingerprint", async () => { + const f = await fixture(); + await f.write(101); + expect( + await findClaudeSessionWriters(f.input, { + platform: "darwin", + processStarts: async () => new Map([[101, "Thu Oct 1 01:42:15 2026"]]), + }), + ).toEqual([]); + }); + test("deduplicates shared registry symlinks and repeated profile paths", async () => { + const f = await fixture(); + await f.write(101); + const alias = join(f.home, "alias"); + await mkdir(alias); + await symlink(join(f.home, "sessions"), join(alias, "sessions")); + expect( + await findClaudeSessionWriters( + { ...f.input, directories: [f.home, alias, f.home] }, + { + platform: "darwin", + processStarts: async (pids) => { + expect(pids).toEqual([101]); + return new Map([[101, normalized]]); + }, + }, + ), + ).toEqual([101]); + }); + test("does not create missing registry folders or claim a writer", async () => { + const f = await fixture(); + expect( + await findClaudeSessionWriters( + { ...f.input, directories: [join(f.home, "missing")] }, + { + platform: "darwin", + processStarts: async (pids) => { + expect(pids).toEqual([]); + return new Map(); + }, + }, + ), + ).toEqual([]); + }); + for (const change of [ + { procStart: "future-format" }, + { pidDomain: "linux" }, + { pid: 102 }, + { pid: -1 }, + ]) { + test(`refuses uncertain matching process identity ${JSON.stringify(change)}`, async () => { + const f = await fixture(); + await f.write(101, change); + await expect( + findClaudeSessionWriters(f.input, { platform: "darwin" }), + ).rejects.toThrow("could not be verified"); + }); + } + test("refuses malformed or oversized records instead of treating them as absent", async () => { + const f = await fixture(); + for (const value of ["{", " ".repeat(65537)]) { + await writeFile(join(f.home, "sessions", "101.json"), value); + await expect( + findClaudeSessionWriters(f.input, { platform: "darwin" }), + ).rejects.toThrow("could not be read"); + } + }); + test("does not follow a record symlink", async () => { + const f = await fixture(); + await symlink( + join(f.home, "outside"), + join(f.home, "sessions", "101.json"), + ); + await expect( + findClaudeSessionWriters(f.input, { platform: "darwin" }), + ).rejects.toThrow("unreadable record"); + }); + test("bounds directory traversal", async () => { + const f = await fixture(); + await Promise.all( + Array.from({ length: 1025 }, (_, i) => + writeFile(join(f.home, "sessions", `entry-${i}`), ""), + ), + ); + await expect( + findClaudeSessionWriters(f.input, { platform: "darwin" }), + ).rejects.toThrow("too large"); + }); + test("propagates process observation failures", async () => { + const f = await fixture(); + await f.write(101); + await expect( + findClaudeSessionWriters(f.input, { + platform: "darwin", + processStarts: async () => { + throw new Error("Process lookup unavailable"); + }, + }), + ).rejects.toThrow("Process lookup unavailable"); + }); + test("does not infer support on an unqualified operating system", async () => { + const f = await fixture(); + await f.write(101); + expect( + await findClaudeSessionWriters(f.input, { + platform: "win32", + processStarts: async () => { + throw new Error("Must not run"); + }, + }), + ).toEqual([]); + }); + test("detects an owned real process and ignores its record after exit", async () => { + if (process.platform !== "darwin" && process.platform !== "linux") return; + const f = await fixture(); + const child = Bun.spawn( + [process.execPath, "-e", "setInterval(() => {}, 1000)"], + { stdout: "ignore", stderr: "ignore" }, + ); + try { + const starts = await readProcessStarts([child.pid]); + expect(starts.has(child.pid)).toBe(true); + await f.write(child.pid, { + procStart: starts.get(child.pid), + pidDomain: process.platform, + }); + expect(await findClaudeSessionWriters(f.input)).toEqual([child.pid]); + child.kill(); + await child.exited; + expect(await findClaudeSessionWriters(f.input)).toEqual([]); + } finally { + if (child.exitCode === null) child.kill(); + await child.exited; + } + }); +}); + +describe("Claude Desktop writer ownership", () => { + const home = "/fixture"; + const cli = `${home}/Library/Application Support/Claude/claude-code/2.1.299/4fa9694b7975/claude.app/Contents/MacOS/claude`; + const parent = "/Applications/Claude.app/Contents/Helpers/disclaimer"; + const desktop = "/Applications/Claude.app/Contents/MacOS/Claude"; + function processFixture( + changes: { + child?: string; + parent?: string; + desktop?: string; + mapped?: boolean; + } = {}, + ) { + const processes = new Map([ + [101, { parent: 102, path: changes.child ?? cli }], + [102, { parent: 103, path: changes.parent ?? parent }], + [103, { parent: 1, path: changes.desktop ?? desktop }], + ]); + return async (file: string, args: string[]) => { + const pid = Number(args[args.indexOf("-p") + 1]); + const process = processes.get(pid); + if (!process) throw new Error("Unknown fixture process"); + return file === "/bin/ps" + ? `${pid} ${process.parent} ${start} ${process.path}\n` + : `p${pid}\nn${changes.mapped === false ? "/other/executable" : process.path}\n`; + }; + } + test("requires mapped executable and both stable Desktop ancestors", async () => { + expect( + await inspectClaudeWriterOwner( + { + pid: 101, + procStart: normalized, + entrypoint: "claude-desktop", + kind: "interactive", + }, + { + platform: "darwin", + home, + run: processFixture(), + }, + ), + ).toBe("claude-desktop"); + }); + for (const changes of [ + { child: "/fake/claude" }, + { parent: "/other/disclaimer" }, + { desktop: "/other/Claude" }, + { mapped: false }, + ]) + test(`does not trust a Desktop entrypoint alone ${JSON.stringify(changes)}`, async () => { + expect( + await inspectClaudeWriterOwner( + { pid: 101, procStart: normalized, entrypoint: "claude-desktop" }, + { + platform: "darwin", + home, + run: processFixture(changes), + }, + ), + ).toBe("unknown"); + }); + test("does not attribute a different process incarnation to Desktop", async () => { + expect( + await inspectClaudeWriterOwner( + { + pid: 101, + procStart: "Thu Oct 1 01:42:15 2026", + entrypoint: "claude-desktop", + }, + { + platform: "darwin", + home, + run: processFixture(), + }, + ), + ).toBe("unknown"); + }); + test("labels a mapped native background worker separately from an attached terminal", async () => { + expect( + await inspectClaudeWriterOwner( + { pid: 101, procStart: normalized, kind: "background" }, + { + platform: "darwin", + home, + run: processFixture({ + child: `${home}/.local/share/claude/versions/2.1.303`, + }), + }, + ), + ).toBe("background"); + }); +}); diff --git a/packages/host-service/src/terminal-agents/claude-session-writers.ts b/packages/host-service/src/terminal-agents/claude-session-writers.ts new file mode 100644 index 00000000000..c489ef3cb5b --- /dev/null +++ b/packages/host-service/src/terminal-agents/claude-session-writers.ts @@ -0,0 +1,335 @@ +import { execFile } from "node:child_process"; +import { constants } from "node:fs"; +import { open, opendir, realpath } from "node:fs/promises"; +import { homedir } from "node:os"; +import { isAbsolute, join } from "node:path"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); +const MAX_RECORDS = 1024; +const MAX_RECORD_BYTES = 64 * 1024; + +interface WriterRecord { + pid: number; + procStart: string; + entrypoint?: string; + kind?: string; +} + +export type ClaudeSessionWriterOwner = + | "claude-desktop" + | "background" + | "terminal" + | "unknown"; + +export interface ClaudeSessionWriter extends WriterRecord { + owner: ClaudeSessionWriterOwner; +} + +interface WriterDeps { + platform?: NodeJS.Platform; + processStarts?: typeof readProcessStarts; +} + +function missing(error: unknown) { + return (error as NodeJS.ErrnoException)?.code === "ENOENT"; +} + +export function processStartFingerprint(value: unknown): string | null { + if (typeof value !== "string") return null; + const normalized = value.trim().replace(/\s+/g, " "); + return /^[A-Z][a-z]{2} [A-Z][a-z]{2} \d{1,2} \d{2}:\d{2}:\d{2} \d{4}$/.test( + normalized, + ) + ? normalized + : null; +} + +export async function readProcessStarts( + pids: number[], +): Promise> { + if (pids.length === 0) return new Map(); + let stdout: string; + try { + ({ stdout } = await execFileAsync( + "/bin/ps", + ["-p", pids.join(","), "-o", "pid=,lstart="], + { + env: { ...process.env, TZ: "UTC", LC_ALL: "C" }, + timeout: 2000, + maxBuffer: 256 * 1024, + }, + )); + } catch (error) { + const failed = error as { + code?: unknown; + stdout?: string; + stderr?: string; + }; + if (failed.code === 1 && !failed.stdout?.trim() && !failed.stderr?.trim()) + return new Map(); + throw new Error("The native session processes could not be checked."); + } + const result = new Map(); + for (const line of stdout.split("\n")) { + if (!line.trim()) continue; + const match = /^\s*(\d+)\s+(.+)$/.exec(line); + const start = processStartFingerprint(match?.[2]); + if (!match || !start) + throw new Error("The native session process format was not recognized."); + result.set(Number(match[1]), start); + } + return result; +} + +/** Native records are positive writer evidence, not an exclusive lock. Older + * CLI versions can omit them; an empty result never proves global absence. */ +async function liveWriterRecords( + input: { sessionId: string; directories: string[] }, + deps: WriterDeps, +): Promise { + const platform = deps.platform ?? process.platform; + if (platform !== "darwin" && platform !== "linux") return []; + const roots = new Set(); + const records: WriterRecord[] = []; + let visited = 0; + for (const directory of new Set(input.directories)) { + let root: string; + try { + root = await realpath(join(directory, "sessions")); + } catch (error) { + if (missing(error)) continue; + throw new Error("The native session registry could not be checked."); + } + if (roots.has(root)) continue; + roots.add(root); + for await (const entry of await opendir(root)) { + if (++visited > MAX_RECORDS) + throw new Error( + "The native session registry is too large to check safely.", + ); + if (!/^\d+\.json$/.test(entry.name)) continue; + if (!entry.isFile()) + throw new Error( + "The native session registry contains an unreadable record.", + ); + let record: Record; + try { + const handle = await open( + join(root, entry.name), + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const metadata = await handle.stat(); + if (!metadata.isFile() || metadata.size > MAX_RECORD_BYTES) + throw new Error("Invalid session record"); + const buffer = Buffer.alloc(MAX_RECORD_BYTES + 1); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0); + if (bytesRead > MAX_RECORD_BYTES) + throw new Error("Oversized session record"); + record = JSON.parse(buffer.subarray(0, bytesRead).toString("utf8")); + } finally { + await handle.close(); + } + } catch (error) { + if (missing(error)) continue; + throw new Error( + "The native session registry could not be read. Retry after the agent is idle.", + ); + } + if ( + !record || + typeof record !== "object" || + Array.isArray(record) || + typeof record.sessionId !== "string" || + !record.sessionId + ) + throw new Error( + "The native session registry format was not recognized.", + ); + if (record.sessionId !== input.sessionId) continue; + const pid = record.pid; + const start = processStartFingerprint(record.procStart); + if ( + !Number.isSafeInteger(pid) || + typeof pid !== "number" || + pid <= 0 || + pid > 2_147_483_647 || + entry.name !== `${pid}.json` || + !start || + record.pidDomain !== platform + ) + throw new Error( + "The conversation's native process identity could not be verified.", + ); + records.push({ + pid, + procStart: start, + ...(typeof record.entrypoint === "string" + ? { entrypoint: record.entrypoint } + : {}), + ...(typeof record.kind === "string" ? { kind: record.kind } : {}), + }); + } + } + const starts = await (deps.processStarts ?? readProcessStarts)([ + ...new Set(records.map((record) => record.pid)), + ]); + return records.filter( + (record) => starts.get(record.pid) === record.procStart, + ); +} + +export async function findClaudeSessionWriters( + input: { sessionId: string; directories: string[] }, + deps: WriterDeps = {}, +): Promise { + return [ + ...new Set((await liveWriterRecords(input, deps)).map(({ pid }) => pid)), + ]; +} + +interface OwnerProcess { + pid: number; + parentPid: number; + procStart: string; + executable: string; +} + +type OwnerRun = (file: string, args: string[]) => Promise; + +function ownerRun(): OwnerRun { + const signal = AbortSignal.timeout(4000); + return async (file, args) => + ( + await execFileAsync(file, args, { + env: { ...process.env, TZ: "UTC", LC_ALL: "C" }, + signal, + timeout: 1500, + maxBuffer: 256 * 1024, + }) + ).stdout; +} + +async function ownerProcess(pid: number, run: OwnerRun): Promise { + const read = async () => { + const output = await run("/bin/ps", [ + "-ww", + "-p", + String(pid), + "-o", + "pid=,ppid=,lstart=,comm=", + ]); + const match = + /^\s*(\d+)\s+(\d+)\s+([A-Z][a-z]{2} [A-Z][a-z]{2}\s+\d{1,2} \d{2}:\d{2}:\d{2} \d{4})\s+([^\r\n]+)\s*$/.exec( + output, + ); + if (!match || Number(match[1]) !== pid || !isAbsolute(match[4] ?? "")) + throw new Error("Unknown process owner"); + return { + pid, + parentPid: Number(match[2]), + procStart: processStartFingerprint(match[3]) ?? "", + executable: match[4]?.trim() ?? "", + }; + }; + const before = await read(); + const mapped = await run("/usr/sbin/lsof", [ + "-nP", + "-a", + "-p", + String(pid), + "-d", + "txt", + "-Fpn", + ]); + if ( + !mapped.split("\n").includes(`p${pid}`) || + !mapped.split("\n").includes(`n${before.executable}`) || + JSON.stringify(await read()) !== JSON.stringify(before) + ) + throw new Error("Unknown process owner"); + return before; +} + +export async function inspectClaudeWriterOwner( + record: WriterRecord, + deps: { platform?: NodeJS.Platform; run?: OwnerRun; home?: string } = {}, +): Promise { + if ((deps.platform ?? process.platform) !== "darwin") return "unknown"; + try { + const run = deps.run ?? ownerRun(); + const child = await ownerProcess(record.pid, run); + if (child.procStart !== record.procStart) return "unknown"; + if (record.entrypoint === "claude-desktop") { + const root = join( + deps.home ?? homedir(), + "Library/Application Support/Claude/claude-code", + ); + if ( + !child.executable.startsWith(`${root}/`) || + !/^\d+\.\d+\.\d+\/[a-f0-9]+\/claude\.app\/Contents\/MacOS\/claude$/.test( + child.executable.slice(root.length + 1), + ) + ) + return "unknown"; + const parent = await ownerProcess(child.parentPid, run); + const desktop = await ownerProcess(parent.parentPid, run); + return parent.executable === + "/Applications/Claude.app/Contents/Helpers/disclaimer" && + desktop.executable === + "/Applications/Claude.app/Contents/MacOS/Claude" && + JSON.stringify(await ownerProcess(child.pid, run)) === + JSON.stringify(child) && + JSON.stringify(await ownerProcess(parent.pid, run)) === + JSON.stringify(parent) && + JSON.stringify(await ownerProcess(desktop.pid, run)) === + JSON.stringify(desktop) + ? "claude-desktop" + : "unknown"; + } + const root = join(deps.home ?? homedir(), ".local/share/claude/versions"); + if ( + !child.executable.startsWith(`${root}/`) || + !/^\d+\.\d+\.\d+$/.test(child.executable.slice(root.length + 1)) + ) + return "unknown"; + return record.kind === "background" + ? "background" + : record.kind === "interactive" + ? "terminal" + : "unknown"; + } catch { + return "unknown"; + } +} + +export async function findClaudeSessionWriterDetails( + input: { sessionId: string; directories: string[] }, + deps: WriterDeps & { + owner?: typeof inspectClaudeWriterOwner; + } = {}, +): Promise { + const records = await liveWriterRecords(input, deps); + const detailed = await Promise.all( + records.map(async (record) => ({ + ...record, + owner: + records.length > 8 + ? ("unknown" as const) + : await (deps.owner ?? inspectClaudeWriterOwner)(record, { + platform: deps.platform, + }), + })), + ); + const starts = await (deps.processStarts ?? readProcessStarts)([ + ...new Set(detailed.map(({ pid }) => pid)), + ]); + return [ + ...new Map( + detailed + .filter(({ pid, procStart }) => starts.get(pid) === procStart) + .map((writer) => [writer.pid, writer]), + ).values(), + ]; +} diff --git a/packages/host-service/src/terminal-agents/harness-session-ref.test.ts b/packages/host-service/src/terminal-agents/harness-session-ref.test.ts index cc82b8076ff..dbefd2bb6a6 100644 --- a/packages/host-service/src/terminal-agents/harness-session-ref.test.ts +++ b/packages/host-service/src/terminal-agents/harness-session-ref.test.ts @@ -1,6 +1,7 @@ import { Database } from "bun:sqlite"; import { describe, expect, it } from "bun:test"; import { resolve } from "node:path"; +import { eq } from "drizzle-orm"; import { drizzle } from "drizzle-orm/bun-sqlite"; import { migrate } from "drizzle-orm/bun-sqlite/migrator"; import type { HostDb } from "../db"; @@ -59,6 +60,39 @@ function seed(db: HostDb, config: { presetId: string; envJson: string }) { } describe("terminalHarnessSession", () => { + it("looks in the persisted selected profile after the default/config changes", () => { + const db = createTestDb(); + seed(db, { + presetId: "claude", + envJson: JSON.stringify({ CLAUDE_CONFIG_DIR: "/later/default" }), + }); + db.update(schema.terminalAgentBindings) + .set({ + accountJson: JSON.stringify({ + agent: "claude", + selection: "/selected/profile", + directory: "/selected/profile", + credentialKind: "subscription", + identity: "a".repeat(64), + pinned: true, + }), + }) + .where(eq(schema.terminalAgentBindings.terminalId, "t-1")) + .run(); + expect(terminalHarnessSession(db, "t-1")?.ref.env).toEqual({ + CLAUDE_CONFIG_DIR: "/selected/profile", + }); + }); + + it("does not read default-account history for an unreadable persisted pin", () => { + const db = createTestDb(); + seed(db, { presetId: "claude", envJson: "{}" }); + db.update(schema.terminalAgentBindings) + .set({ accountJson: "broken" }) + .where(eq(schema.terminalAgentBindings.terminalId, "t-1")) + .run(); + expect(terminalHarnessSession(db, "t-1")).toBeNull(); + }); it("names the harness that wrote the session, not the config's preset", () => { const db = createTestDb(); seed(db, { diff --git a/packages/host-service/src/terminal-agents/harness-session-ref.ts b/packages/host-service/src/terminal-agents/harness-session-ref.ts index 39bbf2835b2..1645d6dfb50 100644 --- a/packages/host-service/src/terminal-agents/harness-session-ref.ts +++ b/packages/host-service/src/terminal-agents/harness-session-ref.ts @@ -1,7 +1,9 @@ import { eq } from "drizzle-orm"; import type { HostDb } from "../db"; import { terminalAgentBindings, workspaces } from "../db/schema"; +import { pinnedAccountEnv } from "../trpc/router/agents/launch-account"; import { resolveDefaultAccountEnv } from "../trpc/router/usage/default-account"; +import { parsePersistedSessionAccount } from "../trpc/router/usage/session-account/session-account"; import { agentLaunchEnv, resolveHostAgentConfig } from "./agent-config"; import type { HarnessSessionRef } from "./harness-sessions"; @@ -25,6 +27,7 @@ export function terminalHarnessSession( workspaceId: terminalAgentBindings.workspaceId, transcriptPath: terminalAgentBindings.transcriptPath, endedAt: terminalAgentBindings.endedAt, + accountJson: terminalAgentBindings.accountJson, }) .from(terminalAgentBindings) .where(eq(terminalAgentBindings.terminalId, terminalId)) @@ -39,15 +42,19 @@ export function terminalHarnessSession( db, binding.definitionId ?? binding.agentId, ); + const account = parsePersistedSessionAccount(binding.accountJson); + if (account === null) return null; return { ref: { agentId: binding.agentId, sessionId: binding.agentSessionId, worktreePath, reportedPath: binding.transcriptPath, - env: config - ? agentLaunchEnv(db, config) - : resolveDefaultAccountEnv(db, binding.agentId), + env: account?.pinned + ? pinnedAccountEnv(account) + : config + ? agentLaunchEnv(db, config) + : resolveDefaultAccountEnv(db, binding.agentId), }, endedAt: binding.endedAt, }; diff --git a/packages/host-service/src/terminal-agents/native-claude-process.test.ts b/packages/host-service/src/terminal-agents/native-claude-process.test.ts new file mode 100644 index 00000000000..04967746f66 --- /dev/null +++ b/packages/host-service/src/terminal-agents/native-claude-process.test.ts @@ -0,0 +1,536 @@ +import { describe, expect, test } from "bun:test"; +import { + findNativeClaudeAttachClient, + findNativeClaudeTerminalClient, + type NativeClaudeProcessIO, + type NativeClaudeProcessOptions, + observeNativeClaudeProcess, + resolveTrustedNativeClaudeExecutable, +} from "./native-claude-process"; + +const home = "/home/test"; +const executable = `${home}/.local/share/claude/versions/2.1.302`; +const alias = `${home}/.local/bin/claude`; +const profile = `${home}/.claude-work`; +const cwd = `${home}/project`; +const birth = "Sun Oct 18 01:02:03 2026"; +const command = `${alias} attach cf9dc1cc`; +const metadata = (pid = 101, parent = 100, extra = "") => + `${pid} ${parent} 501 S ${birth} ${alias}\n${extra}`; +const root = `100 1 501 S Sun Oct 18 01:01:00 2026 /bin/zsh\n`; +const environment = `${command} HOME=${home} PATH=/bin:/an app/bin CLAUDE_CONFIG_DIR=${profile}`; +const lsof = `p101\0u501\0\nfcwd\0D1\0i2\0n${cwd}\0\nftxt\0D1\0i3\0n${executable}\0\n`; + +function fixture() { + const calls: { file: string; args: string[] }[] = []; + const files = new Map(); + const links = new Map([[alias, executable]]); + const overrides = new Map(); + let headerReads = 0; + let tableReads = 0; + let imageReads = 0; + const io: NativeClaudeProcessIO = { + async mainImagePath() { + imageReads++; + return ( + (overrides.get(`image${imageReads}`) ?? + overrides.get("image") ?? + executable) || + null + ); + }, + async executableFile(path) { + const file = await io.stat(path); + if (!file.isFile()) throw new Error("Not a synthetic executable file"); + return { + uid: file.uid, + mode: file.mode, + ino: file.ino, + dev: file.dev, + size: 100, + links: 2, + mtimeNs: "1", + ctimeNs: "2", + }; + }, + async run(file, args, options) { + calls.push({ file, args }); + expect(options.timeout).toBe(1500); + expect(options.maxBuffer).toBe(512 * 1024); + expect(options.signal.aborted).toBe(false); + if (file === "/usr/sbin/lsof") return overrides.get("lsof") ?? lsof; + expect(file).toBe("/bin/ps"); + if (args.includes("-U")) { + tableReads++; + return ( + overrides.get(`table${tableReads}`) ?? + overrides.get("table") ?? + root + metadata() + ); + } + if (args.at(-1) === "pid=,ppid=,uid=,state=,lstart=,comm=") { + headerReads++; + return ( + overrides.get(`header${headerReads}`) ?? + overrides.get("header") ?? + metadata() + ); + } + return args.includes("-E") + ? (overrides.get("environment") ?? environment) + : (overrides.get("command") ?? command); + }, + async read(path, signal) { + expect(signal.aborted).toBe(false); + const value = files.get(path); + if (value === undefined) throw new Error("Missing synthetic file"); + return Buffer.from(value); + }, + async realpath(path) { + return links.get(path) ?? path; + }, + async readlink(path) { + const value = links.get(path); + if (value === undefined) throw new Error("Missing synthetic link"); + return value; + }, + async stat(path) { + return { + uid: 501, + mode: path === executable ? 0o100755 : 0o40700, + dev: 1, + ino: path === executable ? 3 : 2, + isFile: () => path === executable, + isDirectory: () => path !== executable, + }; + }, + }; + const options: NativeClaudeProcessOptions = { + platform: "darwin", + home, + uid: 501, + io, + }; + return { io, options, calls, files, links, overrides }; +} + +describe("native Claude process observation", () => { + test("uses the retained301 main image after the launcher rotates to303", async () => { + const f = fixture(); + const retained = `${home}/.local/share/claude/versions/2.1.301`; + const newer = `${home}/.local/share/claude/versions/2.1.303`; + const retainedFile = await f.io.stat(executable); + const originalStat = f.io.stat; + f.io.stat = async (path) => + path === retained + ? retainedFile + : path === newer + ? { ...retainedFile, ino: 4 } + : originalStat(path); + f.links.set(alias, newer); + f.overrides.set("image", retained); + f.overrides.set("lsof", lsof.replace(executable, retained)); + expect((await observeNativeClaudeProcess(101, f.options)).executable).toBe( + retained, + ); + expect( + (await findNativeClaudeTerminalClient(100, f.options))?.executable, + ).toBe(retained); + }); + + test("accepts only an exact version hardlink to the retained trusted main-image vnode", async () => { + for (const version of ["2.1.301", "2.1.302"]) { + const retained = `${home}/.local/share/claude/versions/${version}`; + const hardlink = `/private/task/native-hold/${version}`; + for (const mappedName of [retained, hardlink]) { + const f = fixture(); + const file = await f.io.stat(executable); + const originalStat = f.io.stat; + f.io.stat = async (path) => + [retained, hardlink].includes(path) ? file : originalStat(path); + f.links.set(alias, `${home}/.local/share/claude/versions/2.1.303`); + f.overrides.set("image", hardlink); + f.overrides.set("lsof", lsof.replace(executable, mappedName)); + expect( + (await observeNativeClaudeProcess(101, f.options)).executable, + ).toBe(retained); + let images = 0; + f.io.mainImagePath = async () => (++images === 1 ? hardlink : retained); + expect( + (await observeNativeClaudeProcess(101, f.options)).executable, + ).toBe(retained); + } + } + }); + + test("refuses mismatched retained inode, unknown alias names, or changing hardlink metadata", async () => { + for (const failure of [ + "inode", + "restored300", + "name", + "metadata", + "symlink", + ]) { + const f = fixture(); + const version = failure === "restored300" ? "2.1.300" : "2.1.302"; + const retained = `${home}/.local/share/claude/versions/${version}`; + const hardlink = `/private/task/native-hold/${failure === "name" ? "claude" : version}`; + const file = await f.io.stat(executable); + const originalStat = f.io.stat; + f.io.stat = async (path) => + path === hardlink + ? { ...file, ino: failure === "inode" ? 4 : file.ino } + : path === retained + ? { ...file, ino: failure === "restored300" ? 4 : file.ino } + : originalStat(path); + f.overrides.set("image", hardlink); + if (failure === "symlink") f.links.set(hardlink, executable); + const snapshot = f.io.executableFile; + let reads = 0; + f.io.executableFile = async (path) => { + const value = await snapshot(path); + if (path === hardlink && failure === "metadata" && ++reads > 1) + return { ...value, ctimeNs: "changed" }; + return value; + }; + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + } + }); + + test("refuses ambiguous or replaced mapped images even with kernel authority", async () => { + for (const mapped of [ + `${lsof}ftxt\0D1\0i3\0n${executable}\0\n`, + lsof.replace("i3\0", "i4\0"), + ]) { + const f = fixture(); + f.overrides.set("lsof", mapped); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + } + }); + + test("never falls back to a launcher or mapped library when main-image authority fails", async () => { + for (const image of ["", "/tmp/foreign-main-image"]) { + const f = fixture(); + f.overrides.set("image", image); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + } + const f = fixture(); + f.overrides.set("image2", `${home}/.local/share/claude/versions/2.1.303`); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + }); + test("corroborates macOS executable, incarnation, profile, cwd and exact attach argv", async () => { + const f = fixture(); + expect(await observeNativeClaudeProcess(101, f.options)).toEqual({ + pid: 101, + parentPid: 100, + uid: 501, + birth, + executable, + configDir: profile, + cwd, + args: ["attach", "cf9dc1cc"], + }); + expect( + f.calls.every((call) => + ["/bin/ps", "/usr/sbin/lsof"].includes(call.file), + ), + ).toBe(true); + expect(await resolveTrustedNativeClaudeExecutable(alias, f.options)).toBe( + executable, + ); + }); + + test("rejects command extras and does not expose prompts or secret values", async () => { + const f = fixture(); + f.overrides.set("command", `${command} --print private-prompt`); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + expect(f.calls.some((call) => call.file === "/usr/sbin/lsof")).toBe(false); + f.overrides.delete("command"); + f.overrides.set( + "environment", + `${environment} CLAUDE_CODE_OAUTH_TOKEN=private-token`, + ); + try { + await observeNativeClaudeProcess(101, f.options); + throw new Error("Expected refusal"); + } catch (error) { + expect(String(error)).not.toContain("private-token"); + expect(String(error)).toContain("could not be verified"); + } + }); + + test("rejects ambiguous, duplicate, unavailable and redirected account environments", async () => { + const f = fixture(); + for (const value of [ + `${command} HOME=${home} PATH=/bin CLAUDE_CONFIG_DIR=${profile} other`, + `${environment} CLAUDE_CONFIG_DIR=${profile}`, + `${environment} `, + command, + `${environment} ANTHROPIC_BASE_URL=https://other.example`, + `${environment} CLAUDE_CODE_USE_BEDROCK=1`, + ]) { + f.overrides.set("environment", value); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + } + }); + + test("rejects mapped executable replacement and PID reuse", async () => { + const f = fixture(); + f.overrides.set("lsof", lsof.replace("i3\0", "i4\0")); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + f.overrides.delete("lsof"); + f.overrides.set("header3", metadata().replace("01:02:03", "01:02:04")); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + }); + + test("refuses duplicate or malformed mapped-file fields", async () => { + for (const value of [ + lsof.replace("D1\0", "D1invalid\0"), + lsof.replace(`n${executable}\0`, `n/tmp/other\0n${executable}\0`), + ]) { + const f = fixture(); + f.overrides.set("lsof", value); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + } + }); + + test("refuses foreign, stopped and unsupported executables", async () => { + for (const header of [ + metadata().replace("501", "502"), + metadata().replace("501 S", "501 T"), + metadata().replace(alias, "/tmp/claude"), + ]) { + const f = fixture(); + f.overrides.set("header", header); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + } + }); + + test("finds one current client under the exact root without blocking on unrelated stopped processes", async () => { + const f = fixture(); + f.overrides.set( + "table", + `${root}${metadata()}102 1 501 T Sun Oct 18 01:00:00 2026 /bin/zsh\n`, + ); + const found = await findNativeClaudeAttachClient(100, f.options); + expect(found?.backgroundId).toBe("cf9dc1cc"); + expect(found?.ancestors).toEqual([ + { pid: 100, parentPid: 1, uid: 501, birth: "Sun Oct 18 01:01:00 2026" }, + ]); + const g = fixture(); + g.overrides.set( + "table2", + root.replace("01:01:00", "01:01:01") + metadata(), + ); + await expect(findNativeClaudeAttachClient(100, g.options)).rejects.toThrow( + "could not be verified", + ); + }); + + test("returns absence only when the root has no native Claude descendant", async () => { + const f = fixture(); + f.overrides.set( + "table", + root + metadata().replace(alias, "/usr/bin/sleep"), + ); + expect(await findNativeClaudeAttachClient(100, f.options)).toBeNull(); + expect(f.calls).toHaveLength(1); + expect(f.calls[0]?.args).toContain("-U"); + expect(await findNativeClaudeTerminalClient(100, f.options)).toBeNull(); + }); + + for (const currentCommand of [ + alias, + executable, + "claude", + `${alias} --resume cf9dc1cc-3d55-4149-8a3b-c16be579690b`, + `${alias} agents`, + ]) { + test(`refuses a live unresolved native client instead of reporting absence: ${currentCommand}`, async () => { + const f = fixture(); + f.overrides.set("command", currentCommand); + f.overrides.set( + "environment", + `${currentCommand} HOME=${home} PATH=/bin CLAUDE_CONFIG_DIR=${profile}`, + ); + const observed = await observeNativeClaudeProcess(101, f.options); + expect(observed).toMatchObject({ + pid: 101, + birth, + executable, + cwd, + configDir: profile, + args: [], + }); + const native = await findNativeClaudeTerminalClient(100, f.options); + expect(native).toEqual({ + ...observed, + ancestors: [ + { + pid: 100, + parentPid: 1, + uid: 501, + birth: "Sun Oct 18 01:01:00 2026", + }, + ], + }); + expect(native).not.toHaveProperty("backgroundId"); + expect(native).not.toHaveProperty("currentSessionId"); + await expect( + findNativeClaudeAttachClient(100, f.options), + ).rejects.toThrow("could not be verified"); + }); + } + + test("does not choose a known attachment beside another unresolved native client", async () => { + const f = fixture(); + f.overrides.set("table", root + metadata() + metadata(102)); + const original = f.io.run; + f.io.run = async (file, args, options) => { + const value = await original(file, args, options); + if (!args.includes("102")) return value; + if (file === "/bin/ps" && args.at(-1) === "command=") + return args.includes("-E") + ? `${alias} HOME=${home} PATH=/bin CLAUDE_CONFIG_DIR=${profile}` + : alias; + return value.replaceAll("101", "102"); + }; + await expect(findNativeClaudeAttachClient(100, f.options)).rejects.toThrow( + "could not be verified", + ); + await expect( + findNativeClaudeTerminalClient(100, f.options), + ).rejects.toThrow("could not be verified"); + }); + test("observes a name-based native attachment without claiming its selected session", async () => { + const f = fixture(); + const namedCommand = `${alias} attach Medusa account test`; + f.overrides.set("command", namedCommand); + f.overrides.set( + "environment", + `${namedCommand} HOME=${home} PATH=/bin CLAUDE_CONFIG_DIR=${profile}`, + ); + const observed = await findNativeClaudeTerminalClient(100, f.options); + expect(observed).toMatchObject({ + pid: 101, + birth, + executable, + cwd, + configDir: profile, + args: [], + }); + expect(observed).not.toHaveProperty("backgroundId"); + await expect(findNativeClaudeAttachClient(100, f.options)).rejects.toThrow( + "could not be verified", + ); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + }); + + test("refuses ambiguous multiple attachments and a changed parent chain", async () => { + const f = fixture(); + const original = f.io.run; + f.io.run = async (file, args, options) => { + const value = await original(file, args, options); + return args.includes("102") || + (file === "/usr/sbin/lsof" && args.includes("102")) + ? value.replaceAll("101", "102") + : value; + }; + f.overrides.set("table", root + metadata() + metadata(102)); + await expect(findNativeClaudeAttachClient(100, f.options)).rejects.toThrow( + "could not be verified", + ); + const g = fixture(); + g.overrides.set("table2", root + metadata(101, 1)); + await expect(findNativeClaudeAttachClient(100, g.options)).rejects.toThrow( + "could not be verified", + ); + }); + + test("rejects oversized command output and aborts pending inspection without waiting", async () => { + const f = fixture(); + f.overrides.set("command", "x".repeat(512 * 1024 + 1)); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + const controller = new AbortController(); + f.options.signal = controller.signal; + f.io.run = async (_file, _args, options) => { + expect(options.signal.aborted).toBe(false); + queueMicrotask(() => controller.abort()); + return new Promise(() => {}); + }; + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + }); + + test("reads Linux NUL-delimited argv and environment with exact start ticks", async () => { + const f = fixture(); + f.options.platform = "linux"; + f.links.set("/proc/101/exe", executable); + f.links.set("/proc/101/cwd", cwd); + const fields = ["S", "100", ...Array(17).fill("0"), "12345", "0"]; + f.files.set("/proc/101/stat", `101 (claude) ${fields.join(" ")}\n`); + f.files.set( + "/proc/101/status", + "Name:\tclaude\nUid:\t501\t501\t501\t501\n", + ); + f.files.set("/proc/101/cmdline", `${alias}\0attach\0cf9dc1cc\0`); + f.files.set( + "/proc/101/environ", + `HOME=${home}\0PATH=/bin\0CLAUDE_CONFIG_DIR=${profile}\0`, + ); + expect(await observeNativeClaudeProcess(101, f.options)).toEqual({ + pid: 101, + parentPid: 100, + uid: 501, + birth: "proc-start:12345", + executable, + cwd, + configDir: profile, + args: ["attach", "cf9dc1cc"], + }); + expect(f.calls).toEqual([]); + f.files.set("/proc/101/cmdline", `${alias}\0attach\0cf9dc1cc\0--print\0`); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + }); + + test("refuses unsupported platforms and pre-aborted requests before process reads", async () => { + const f = fixture(); + f.options.platform = "win32"; + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + f.options.platform = "darwin"; + f.options.signal = AbortSignal.abort(); + await expect(observeNativeClaudeProcess(101, f.options)).rejects.toThrow( + "could not be verified", + ); + expect(f.calls).toEqual([]); + }); +}); diff --git a/packages/host-service/src/terminal-agents/native-claude-process.ts b/packages/host-service/src/terminal-agents/native-claude-process.ts new file mode 100644 index 00000000000..d409f139b6b --- /dev/null +++ b/packages/host-service/src/terminal-agents/native-claude-process.ts @@ -0,0 +1,792 @@ +import { execFile } from "node:child_process"; +import { type BigIntStats, constants } from "node:fs"; +import { lstat, open, readlink, realpath, stat } from "node:fs/promises"; +import { homedir } from "node:os"; +import { basename, dirname, isAbsolute, join, normalize } from "node:path"; +import { promisify } from "node:util"; +import { getExecutablePath } from "@superset/macos-process-metrics"; + +const execFileAsync = promisify(execFile); +const MAX_BYTES = 512 * 1024; +const MAX_PROCESSES = 8192; +const MAX_DESCENDANTS = 128; +const MAX_DEPTH = 32; +const VERSION = /^\d+\.\d+\.\d+(?:[-.][a-zA-Z0-9]+)*$/; +const BACKGROUND_ID = + /^(?:[a-f0-9]{8}|[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/; +const FAILURE = "The native Claude process identity could not be verified."; + +interface FileIdentity { + uid: number; + mode: number; + ino: number; + dev: number; + isFile(): boolean; + isDirectory(): boolean; +} + +interface ExecutableFileIdentity { + uid: number; + mode: number; + ino: number; + dev: number; + size: number; + links: number; + mtimeNs: string; + ctimeNs: string; +} + +export interface NativeClaudeProcessIO { + /** Kernel main image; never the current launcher target or an arbitrary mapping. */ + mainImagePath(pid: number): Promise; + /** No-follow opened file and current name must match throughout this observation. */ + executableFile(path: string): Promise; + run( + file: string, + args: string[], + options: { signal: AbortSignal; timeout: number; maxBuffer: number }, + ): Promise; + read(path: string, signal: AbortSignal): Promise; + realpath(path: string): Promise; + readlink(path: string): Promise; + stat(path: string): Promise; +} + +export interface NativeClaudeProcessOptions { + platform?: NodeJS.Platform; + uid?: number; + home?: string; + allowedExecutables?: readonly string[]; + signal?: AbortSignal; + io?: NativeClaudeProcessIO; +} + +export interface NativeProcessIncarnation { + pid: number; + parentPid: number; + birth: string; + uid: number; +} + +export interface NativeClaudeProcess extends NativeProcessIncarnation { + executable: string; + cwd: string; + configDir: string; + /** Only a strictly parsed attachment command is returned; other argv is private. */ + args: string[]; +} + +export interface NativeClaudeTerminalClient extends NativeClaudeProcess { + ancestors: NativeProcessIncarnation[]; +} + +export interface NativeClaudeAttachClient extends NativeClaudeTerminalClient { + backgroundId: string; +} + +interface ProcessRow extends NativeProcessIncarnation { + command: string; + state: string; +} + +interface Context { + platform: "darwin" | "linux"; + uid: number; + home: string; + allowedExecutables: readonly string[]; + signal: AbortSignal; + io: NativeClaudeProcessIO; +} + +function refuse(): never { + throw new Error(FAILURE); +} + +function check(signal: AbortSignal) { + if (signal.aborted) refuse(); +} + +function bounded(signal: AbortSignal, operation: () => Promise) { + check(signal); + return new Promise((resolve, reject) => { + const abort = () => reject(new Error(FAILURE)); + signal.addEventListener("abort", abort, { once: true }); + operation() + .then(resolve, reject) + .finally(() => { + signal.removeEventListener("abort", abort); + }); + }); +} + +function validPid(pid: number) { + return Number.isSafeInteger(pid) && pid > 0 && pid <= 2_147_483_647; +} + +function hasControl(value: string) { + return [...value].some((character) => { + const code = character.charCodeAt(0); + return code < 32 || code === 127; + }); +} + +function canonicalPath(value: string) { + if (!isAbsolute(value) || value !== normalize(value) || hasControl(value)) + refuse(); + return value; +} + +function sameImageFile(a: ExecutableFileIdentity, b: ExecutableFileIdentity) { + return ( + [ + "uid", + "mode", + "ino", + "dev", + "size", + "links", + "mtimeNs", + "ctimeNs", + ] as const + ).every((key) => a[key] === b[key]); +} + +function imageFileFacts(info: BigIntStats): ExecutableFileIdentity { + if (!info.isFile()) refuse(); + const value = { + uid: Number(info.uid), + mode: Number(info.mode), + ino: Number(info.ino), + dev: Number(info.dev), + size: Number(info.size), + links: Number(info.nlink), + mtimeNs: info.mtimeNs.toString(), + ctimeNs: info.ctimeNs.toString(), + }; + if ( + ![ + value.uid, + value.mode, + value.ino, + value.dev, + value.size, + value.links, + ].every(Number.isSafeInteger) + ) + refuse(); + return value; +} + +const defaultIO: NativeClaudeProcessIO = { + async mainImagePath(pid) { + return getExecutablePath(pid); + }, + async executableFile(path) { + const file = await open( + path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const before = imageFileFacts(await file.stat({ bigint: true })); + const named = imageFileFacts(await lstat(path, { bigint: true })); + const after = imageFileFacts(await file.stat({ bigint: true })); + if (!sameImageFile(before, named) || !sameImageFile(before, after)) + refuse(); + return after; + } finally { + await file.close(); + } + }, + async run(file, args, options) { + const { stdout } = await execFileAsync(file, args, { + ...options, + env: { ...process.env, TZ: "UTC", LC_ALL: "C" }, + encoding: "utf8", + }); + return stdout; + }, + async read(path, signal) { + check(signal); + const file = await open( + path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + if (!(await file.stat()).isFile()) refuse(); + const buffer = Buffer.alloc(MAX_BYTES + 1); + let size = 0; + while (size < buffer.length) { + check(signal); + const { bytesRead } = await file.read( + buffer, + size, + buffer.length - size, + size, + ); + if (bytesRead === 0) break; + size += bytesRead; + } + check(signal); + if (size > MAX_BYTES) refuse(); + return buffer.subarray(0, size); + } finally { + await file.close(); + } + }, + realpath, + readlink, + stat, +}; + +async function context(options: NativeClaudeProcessOptions): Promise { + const platform = options.platform ?? process.platform; + const uid = options.uid ?? process.getuid?.(); + if ( + (platform !== "darwin" && platform !== "linux") || + uid === undefined || + !Number.isSafeInteger(uid) || + uid < 0 + ) + refuse(); + const signal = options.signal + ? AbortSignal.any([options.signal, AbortSignal.timeout(5000)]) + : AbortSignal.timeout(5000); + check(signal); + const original = options.io ?? defaultIO; + const io: NativeClaudeProcessIO = { + mainImagePath: (pid) => bounded(signal, () => original.mainImagePath(pid)), + executableFile: (path) => + bounded(signal, () => original.executableFile(path)), + run: (file, args, runOptions) => + bounded(signal, () => original.run(file, args, runOptions)), + read: (path, readSignal) => + bounded(signal, () => original.read(path, readSignal)), + realpath: (path) => bounded(signal, () => original.realpath(path)), + readlink: (path) => bounded(signal, () => original.readlink(path)), + stat: (path) => bounded(signal, () => original.stat(path)), + }; + const home = canonicalPath(await io.realpath(options.home ?? homedir())); + check(signal); + return { + platform, + uid, + home, + allowedExecutables: options.allowedExecutables ?? [], + signal, + io, + }; +} + +async function run(ctx: Context, file: string, args: string[]) { + check(ctx.signal); + const value = await ctx.io.run(file, args, { + signal: ctx.signal, + timeout: 1500, + maxBuffer: MAX_BYTES, + }); + check(ctx.signal); + if (Buffer.byteLength(value) > MAX_BYTES || value.includes("\0")) refuse(); + return value; +} + +async function processTable(ctx: Context, pid?: number) { + const output = await run(ctx, "/bin/ps", [ + "-ww", + ...(pid === undefined ? ["-U", String(ctx.uid)] : ["-p", String(pid)]), + "-o", + "pid=,ppid=,uid=,state=,lstart=,comm=", + ]); + const rows = new Map(); + let count = 0; + for (const line of output.split("\n")) { + if (!line.trim()) continue; + if (++count > MAX_PROCESSES) refuse(); + const match = + /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+([A-Z][a-z]{2} [A-Z][a-z]{2}\s+\d{1,2} \d{2}:\d{2}:\d{2} \d{4})\s+(.+?)\s*$/.exec( + line, + ); + if (!match) refuse(); + const [, pidText, parentText, uidText, state, birth, command] = match; + if (!pidText || !parentText || !uidText || !state || !birth || !command) + refuse(); + const row: ProcessRow = { + pid: Number(pidText), + parentPid: Number(parentText), + uid: Number(uidText), + birth: birth.replace(/\s+/g, " "), + command, + state, + }; + if ( + !validPid(row.pid) || + !Number.isSafeInteger(row.parentPid) || + row.parentPid < 0 || + rows.has(row.pid) + ) + refuse(); + if (row.uid !== ctx.uid) continue; + rows.set(row.pid, row); + } + if (pid !== undefined && (rows.size !== 1 || !rows.has(pid))) refuse(); + return rows; +} + +function active(row: ProcessRow) { + return /^[RISUD]/.test(row.state) && !/[TZXE]/.test(row.state); +} + +function sameProcess( + a: NativeProcessIncarnation, + b?: NativeProcessIncarnation, +) { + return ( + b?.pid === a.pid && + b.parentPid === a.parentPid && + b.uid === a.uid && + b.birth === a.birth + ); +} + +async function trustedExecutable(ctx: Context, path: string) { + const executable = canonicalPath(await ctx.io.realpath(canonicalPath(path))); + const file = await ctx.io.stat(executable); + if ( + !file.isFile() || + file.uid !== ctx.uid || + (file.mode & 0o022) !== 0 || + (file.mode & 0o111) === 0 + ) + refuse(); + const nativeRoot = await ctx.io + .realpath(join(ctx.home, ".local/share/claude/versions")) + .catch(() => null); + if ( + nativeRoot && + dirname(executable) === nativeRoot && + VERSION.test(basename(executable)) + ) + return { executable, file }; + for (const allowed of [ + join(ctx.home, ".local/bin/claude"), + ...ctx.allowedExecutables, + ]) { + if ((await ctx.io.realpath(allowed).catch(() => null)) === executable) + return { executable, file }; + } + return refuse(); +} + +function attachmentArgs( + command: string, + executable: string, + aliases: string[], + allowUnresolvedAttach = false, +) { + const prefixes = [...new Set([executable, ...aliases, "claude"])]; + for (const prefix of prefixes) { + if (command === prefix) return []; + if (!command.startsWith(`${prefix} `)) continue; + const suffix = command.slice(prefix.length + 1); + if (!suffix.startsWith("attach")) return []; + const match = /^attach ([a-f0-9-]+)$/.exec(suffix); + const id = match?.[1]; + if (!id || !BACKGROUND_ID.test(id)) { + if (allowUnresolvedAttach) return []; + return refuse(); + } + return ["attach", id]; + } + return refuse(); +} + +function environmentProfile(entries: [string, string][], ctx: Context) { + const selected = new Map(); + for (const [key, value] of entries) { + if ( + key.startsWith("ANTHROPIC_") || + key === "CLAUDE_CODE_OAUTH_TOKEN" || + key === "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" || + key.startsWith("CLAUDE_CODE_USE_") + ) { + if (value) refuse(); + } + if (key !== "HOME" && key !== "CLAUDE_CONFIG_DIR" && key !== "PATH") + continue; + if (selected.has(key)) refuse(); + selected.set(key, value); + } + if (selected.get("HOME") !== ctx.home || !selected.get("PATH")) refuse(); + const path = selected.get("CLAUDE_CONFIG_DIR") || join(ctx.home, ".claude"); + if (!/^\/[a-zA-Z0-9_./@+-]+$/.test(path)) refuse(); + return canonicalPath(path); +} + +function macEnvironment(command: string, output: string, ctx: Context) { + const value = output.replace(/\n$/, ""); + if (!value.startsWith(`${command} `) || hasControl(value)) refuse(); + const environment = value.slice(command.length + 1); + const matches = [ + ...environment.matchAll(/(?:^| )([a-zA-Z_][a-zA-Z0-9_]*)=/g), + ]; + if (matches[0]?.index !== 0) refuse(); + const entries: [string, string][] = matches.map((match, index) => { + const start = (match.index ?? 0) + match[0].length; + const end = matches[index + 1]?.index ?? environment.length; + const key = match[1]; + if (!key) refuse(); + return [key, environment.slice(start, end)]; + }); + return environmentProfile(entries, ctx); +} + +async function canonicalDirectory(ctx: Context, path: string) { + const canonical = canonicalPath(await ctx.io.realpath(path)); + const file = await ctx.io.stat(canonical); + if (!file.isDirectory() || file.uid !== ctx.uid) refuse(); + return canonical; +} + +async function macMainImage(ctx: Context, pid: number) { + const observed = await ctx.io.mainImagePath(pid); + if (!observed) refuse(); + const imagePath = canonicalPath(observed); + if ((await ctx.io.realpath(imagePath)) !== imagePath) refuse(); + const imageFile = await ctx.io.executableFile(imagePath); + let trusted: Awaited>; + try { + trusted = await trustedExecutable(ctx, imagePath); + } catch { + // A kernel-reported version hardlink must prove the same retained vendor vnode. + // No path scanning, private-path exception, or arbitrary mapped-library fallback. + if (!VERSION.test(basename(imagePath))) refuse(); + trusted = await trustedExecutable( + ctx, + join(ctx.home, ".local/share/claude/versions", basename(imagePath)), + ); + } + const canonicalFile = await ctx.io.executableFile(trusted.executable); + if ( + !sameImageFile(imageFile, canonicalFile) || + canonicalFile.uid !== trusted.file.uid || + canonicalFile.mode !== trusted.file.mode || + canonicalFile.ino !== trusted.file.ino || + canonicalFile.dev !== trusted.file.dev + ) + refuse(); + return { ...trusted, imagePath, imageFile, canonicalFile }; +} + +async function observeMac( + ctx: Context, + pid: number, + allowUnresolvedAttach = false, +) { + const before = (await processTable(ctx, pid)).get(pid); + if (!before || !active(before)) refuse(); + const { executable, file, imagePath, imageFile, canonicalFile } = + await macMainImage(ctx, pid); + const command = ( + await run(ctx, "/bin/ps", ["-ww", "-p", String(pid), "-o", "command="]) + ).replace(/\n$/, ""); + if (!command || hasControl(command)) refuse(); + const args = attachmentArgs( + command, + executable, + [before.command], + allowUnresolvedAttach, + ); + const config = macEnvironment( + command, + await run(ctx, "/bin/ps", [ + "-E", + "-ww", + "-p", + String(pid), + "-o", + "command=", + ]), + ctx, + ); + check(ctx.signal); + const mapped = await ctx.io.run( + "/usr/sbin/lsof", + ["-nP", "-a", "-p", String(pid), "-d", "cwd,txt", "-F0pufnDi"], + { signal: ctx.signal, timeout: 1500, maxBuffer: MAX_BYTES }, + ); + check(ctx.signal); + if (Buffer.byteLength(mapped) > MAX_BYTES) refuse(); + let owner: number | undefined; + let observedPid: number | undefined; + const files: { fd: string; name?: string; ino?: number; dev?: number }[] = []; + for (const raw of mapped.split("\0")) { + const field = raw.replace(/^\n/, ""); + if (!field) continue; + const key = field[0]; + const value = field.slice(1); + const current = files.at(-1); + if (key === "p" && observedPid === undefined) observedPid = Number(value); + else if (key === "u" && owner === undefined) owner = Number(value); + else if (key === "f") files.push({ fd: value }); + else if (key === "n" && current && current.name === undefined) + current.name = value; + else if ( + key === "i" && + current && + current.ino === undefined && + /^\d+$/.test(value) + ) + current.ino = Number(value); + else if ( + key === "D" && + current && + current.dev === undefined && + /^(?:0x)?[a-fA-F0-9]+$/.test(value) + ) + current.dev = Number.parseInt(value, 16); + else refuse(); + } + const cwdRows = files.filter((item) => item.fd === "cwd"); + const cwdRow = cwdRows[0]; + if ( + observedPid !== pid || + owner !== ctx.uid || + cwdRows.length !== 1 || + !cwdRow + ) + refuse(); + const cwd = await canonicalDirectory(ctx, cwdRow.name ?? ""); + const texts = files.filter( + (item) => + item.fd === "txt" && + (item.name === executable || item.name === imagePath), + ); + const text = texts[0]; + if ( + texts.length !== 1 || + !text || + text.ino !== file.ino || + text.dev !== file.dev + ) + refuse(); + const configDir = await canonicalDirectory(ctx, config); + const afterImagePath = await ctx.io.mainImagePath(pid); + if ( + (afterImagePath !== imagePath && afterImagePath !== executable) || + (await ctx.io.realpath(imagePath)) !== imagePath || + (await ctx.io.realpath(executable)) !== executable || + !sameImageFile(imageFile, await ctx.io.executableFile(imagePath)) || + !sameImageFile(canonicalFile, await ctx.io.executableFile(executable)) + ) + refuse(); + const after = (await processTable(ctx, pid)).get(pid); + if ( + !sameProcess(before, after) || + !after || + !active(after) || + after.command !== before.command + ) + refuse(); + return { ...incarnation(before), executable, cwd, configDir, args }; +} + +function incarnation(row: NativeProcessIncarnation): NativeProcessIncarnation { + return { + pid: row.pid, + parentPid: row.parentPid, + birth: row.birth, + uid: row.uid, + }; +} + +async function linuxHeader(ctx: Context, pid: number) { + const raw = (await ctx.io.read(`/proc/${pid}/stat`, ctx.signal)).toString( + "utf8", + ); + const end = raw.lastIndexOf(") "); + if (end < 0 || !raw.startsWith(`${pid} (`)) refuse(); + const fields = raw + .slice(end + 2) + .trim() + .split(/\s+/); + const state = fields[0]; + const parent = fields[1]; + const birth = fields[19]; + if ( + !state || + !parent || + !birth || + !/^[RSDI]$/.test(state) || + !/^\d+$/.test(parent) || + !/^\d+$/.test(birth) + ) + refuse(); + const status = ( + await ctx.io.read(`/proc/${pid}/status`, ctx.signal) + ).toString("utf8"); + const ids = /^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*$/m.exec(status); + if (!ids || ids.slice(1).some((id) => Number(id) !== ctx.uid)) refuse(); + const directory = await ctx.io.stat(`/proc/${pid}`); + if (directory.uid !== ctx.uid || !directory.isDirectory()) refuse(); + return { + pid, + parentPid: Number(parent), + uid: ctx.uid, + birth: `proc-start:${birth}`, + }; +} + +async function observeLinux( + ctx: Context, + pid: number, + allowUnresolvedAttach = false, +) { + const before = await linuxHeader(ctx, pid); + const { executable } = await trustedExecutable( + ctx, + await ctx.io.readlink(`/proc/${pid}/exe`), + ); + const rawArgs = ( + await ctx.io.read(`/proc/${pid}/cmdline`, ctx.signal) + ).toString("utf8"); + if (!rawArgs.endsWith("\0")) refuse(); + const argv = rawArgs.slice(0, -1).split("\0"); + if (!argv[0] || argv.some((arg) => hasControl(arg))) refuse(); + let args: string[] = []; + if (argv[1] === "attach") { + const id = argv[2]; + if (argv.length !== 3 || !id || !BACKGROUND_ID.test(id)) { + if (!allowUnresolvedAttach) refuse(); + } else args = ["attach", id]; + } + const rawEnvironment = ( + await ctx.io.read(`/proc/${pid}/environ`, ctx.signal) + ).toString("utf8"); + if (!rawEnvironment.endsWith("\0")) refuse(); + const entries: [string, string][] = rawEnvironment + .slice(0, -1) + .split("\0") + .map((entry) => { + const split = entry.indexOf("="); + if (split < 1) refuse(); + return [entry.slice(0, split), entry.slice(split + 1)]; + }); + const configDir = await canonicalDirectory( + ctx, + environmentProfile(entries, ctx), + ); + const cwd = await canonicalDirectory( + ctx, + await ctx.io.readlink(`/proc/${pid}/cwd`), + ); + check(ctx.signal); + if (!sameProcess(before, await linuxHeader(ctx, pid))) refuse(); + check(ctx.signal); + return { ...before, executable, cwd, configDir, args }; +} + +async function observe( + ctx: Context, + pid: number, + allowUnresolvedAttach = false, +) { + if (!validPid(pid)) refuse(); + return ctx.platform === "darwin" + ? observeMac(ctx, pid, allowUnresolvedAttach) + : observeLinux(ctx, pid, allowUnresolvedAttach); +} + +export async function observeNativeClaudeProcess( + pid: number, + options: NativeClaudeProcessOptions = {}, +): Promise { + try { + return await observe(await context(options), pid); + } catch { + return refuse(); + } +} + +export async function resolveTrustedNativeClaudeExecutable( + path: string, + options: NativeClaudeProcessOptions = {}, +): Promise { + try { + return (await trustedExecutable(await context(options), path)).executable; + } catch { + return refuse(); + } +} + +export async function findNativeClaudeTerminalClient( + rootPid: number, + options: NativeClaudeProcessOptions = {}, +): Promise { + try { + if (!validPid(rootPid)) refuse(); + const ctx = await context(options); + const table = await processTable(ctx); + const root = table.get(rootPid); + if (!root || !active(root)) refuse(); + const descendants = new Set([rootPid]); + for (let depth = 0; depth < MAX_DEPTH; depth++) { + const previous = descendants.size; + for (const row of table.values()) { + if (descendants.has(row.parentPid)) descendants.add(row.pid); + } + if (descendants.size > MAX_DESCENDANTS) refuse(); + if (previous === descendants.size) break; + if (depth === MAX_DEPTH - 1) refuse(); + } + const clients: NativeClaudeProcess[] = []; + for (const pid of descendants) { + if (pid === rootPid) continue; + const command = table.get(pid)?.command ?? ""; + if (basename(command) !== "claude" && !VERSION.test(basename(command))) + continue; + const observed = await observe(ctx, pid, true); + clients.push(observed); + } + if (clients.length > 1) refuse(); + if (!clients[0]) return null; + const client = clients[0]; + const ancestors: NativeProcessIncarnation[] = []; + let next = table.get(client.pid)?.parentPid; + for (let depth = 0; next !== undefined && depth < MAX_DEPTH; depth++) { + const ancestor = table.get(next); + if (!ancestor || ancestors.some((item) => item.pid === next)) refuse(); + ancestors.push(incarnation(ancestor)); + if (next === rootPid) break; + next = ancestor.parentPid; + } + if (ancestors.at(-1)?.pid !== rootPid) refuse(); + const after = await processTable(ctx); + for (const old of [table.get(client.pid), ...ancestors]) { + const current = old && after.get(old.pid); + if (!old || !current || !active(current) || !sameProcess(old, current)) + refuse(); + } + if (after.get(client.pid)?.command !== table.get(client.pid)?.command) + refuse(); + return { ...client, ancestors }; + } catch { + return refuse(); + } +} + +export async function findNativeClaudeAttachClient( + rootPid: number, + options: NativeClaudeProcessOptions = {}, +): Promise { + const client = await findNativeClaudeTerminalClient(rootPid, options); + if (!client) return null; + // A live Claude client can rewrite argv or switch views. These arguments + // describe launch intent, not the currently selected conversation. + const backgroundId = client.args[1]; + if ( + client.args[0] !== "attach" || + !backgroundId || + !BACKGROUND_ID.test(backgroundId) + ) + return refuse(); + return { ...client, backgroundId }; +} diff --git a/packages/host-service/src/terminal-agents/native-session-lease.ts b/packages/host-service/src/terminal-agents/native-session-lease.ts new file mode 100644 index 00000000000..93464ac3a64 --- /dev/null +++ b/packages/host-service/src/terminal-agents/native-session-lease.ts @@ -0,0 +1,18 @@ +/** In-process ownership across terminal and chat launch paths. Native process + * registries/locks remain necessary for other apps and other host processes. */ +const owners = new Map(); +export function claimNativeSession( + provider: string, + sessionId: string, +): () => void { + const key = JSON.stringify([provider, sessionId]); + if (owners.has(key)) + throw new Error( + "This conversation is already opening or running in this host. Open its existing chat instead.", + ); + const owner = Symbol(); + owners.set(key, owner); + return () => { + if (owners.get(key) === owner) owners.delete(key); + }; +} diff --git a/packages/host-service/src/terminal-agents/persistence.test.ts b/packages/host-service/src/terminal-agents/persistence.test.ts index 74a533592d7..651f5e1c758 100644 --- a/packages/host-service/src/terminal-agents/persistence.test.ts +++ b/packages/host-service/src/terminal-agents/persistence.test.ts @@ -59,6 +59,96 @@ function seedSession( } describe("SqliteTerminalAgentBindingPersistence live reads", () => { + it("retains account selection and launch identity across a new store and resume read", () => { + const db = createTestDb(); + seedSession(db, { id: "pinned", status: "active", workspaceId: "ws-1" }); + const account = { + agent: "claude" as const, + selection: "/fixture/profile", + directory: "/fixture/profile", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + email: "fixture@example.test", + pinned: true as const, + }; + const persistence = new SqliteTerminalAgentBindingPersistence(db); + const original = new TerminalAgentStore(persistence); + original.recordEvent({ + terminalId: "pinned", + workspaceId: "ws-1", + agentId: "claude", + agentSessionId: "exact-native-id", + launchId: "launch-one", + account, + eventType: "Attached", + occurredAt: 3, + }); + const recovered = new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ); + expect(recovered.listByWorkspace("ws-1")[0]?.account).toEqual(account); + expect(recovered.get("pinned")?.launchId).toBe("launch-one"); + markTerminalAgentBindingEnded(db, "pinned", "terminal-exited", 4); + expect(findResumeCandidateBinding(db, "ws-1", "pinned")?.account).toEqual( + account, + ); + }); + + it("does not downgrade malformed saved account context to the default account", () => { + const db = createTestDb(); + seedSession(db, { id: "invalid", status: "active", workspaceId: "ws-1" }); + db.update(terminalAgentBindings) + .set({ accountJson: '{"pinned":true}' }) + .where(eq(terminalAgentBindings.terminalId, "invalid")) + .run(); + const store = new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ); + expect(store.get("invalid")?.accountInvalid).toBe(true); + store.recordEvent({ + terminalId: "invalid", + workspaceId: "ws-1", + agentId: "claude", + eventType: "Stop", + occurredAt: 3, + }); + expect( + new SqliteTerminalAgentBindingPersistence(db).load()[0]?.accountInvalid, + ).toBe(true); + }); + it("persists a positively replaced account after restoring invalid context", () => { + const db = createTestDb(); + seedSession(db, { id: "replaced", status: "active", workspaceId: "ws-1" }); + db.update(terminalAgentBindings) + .set({ accountJson: '{"pinned":true}' }) + .where(eq(terminalAgentBindings.terminalId, "replaced")) + .run(); + const store = new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ); + const account = { + agent: "claude" as const, + selection: "/fixture", + directory: "/fixture", + credentialKind: "subscription" as const, + identity: "alice", + pinned: true as const, + }; + store.recordEvent({ + terminalId: "replaced", + workspaceId: "ws-1", + agentId: "claude", + agentSessionId: "verified", + account, + eventType: "Attached", + occurredAt: 3, + }); + const restored = new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ).get("replaced"); + expect(restored?.accountInvalid).toBeUndefined(); + expect(restored?.account).toEqual(account); + }); it("hides bindings whose session is not active or workspace-less", () => { const db = createTestDb(); // The workspaces FK on originWorkspaceId is nullable and unenforced in @@ -653,3 +743,94 @@ describe("recordTerminalAgentTranscriptPath", () => { ); }); }); + +describe("durable account provenance after ended-row recreation", () => { + const account = { + agent: "claude" as const, + selection: "/fixture/profile", + directory: "/fixture/profile", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + pinned: true as const, + }; + const attach = { + terminalId: "durable", + workspaceId: "ws-1", + agentId: "claude" as const, + agentSessionId: "native-session", + launchId: "native-launch", + eventType: "Attached", + occurredAt: 3, + }; + function seeded( + reason: "detached" | "terminal-exited" | "resumed" | "disposed", + ) { + const db = createTestDb(); + seedSession(db, { id: "durable", status: "active", workspaceId: "ws-1" }); + new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ).recordEvent({ ...attach, account }); + markTerminalAgentBindingEnded(db, "durable", reason, 4); + const original = db.query.terminalAgentBindings.findFirst().sync(); + if (!original) throw new Error("Missing synthetic binding"); + return { + db, + startedAt: original.startedAt, + store: new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ), + }; + } + it("preserves exact native-launch account and start time after detached or terminal-exited recreation", () => { + for (const reason of ["detached", "terminal-exited"] as const) { + const { db, store, startedAt } = seeded(reason); + store.recordEvent({ ...attach, occurredAt: 5 }); + expect(store.get("durable")?.account).toEqual(account); + expect(store.get("durable")?.startedAt).toBe(startedAt); + expect( + new SqliteTerminalAgentBindingPersistence(db).load()[0]?.account, + ).toEqual(account); + } + }); + it("does not revive consumed or deliberately disposed native launches", () => { + for (const reason of ["resumed", "disposed"] as const) { + const { db, store } = seeded(reason); + store.recordEvent({ ...attach, occurredAt: 5 }); + expect(store.get("durable")).toBeUndefined(); + expect(db.query.terminalAgentBindings.findFirst().sync()?.endReason).toBe( + reason, + ); + } + }); + it("permits a fresh launch-less native session after a consumed launch without inheriting its account", () => { + for (const reason of ["resumed", "disposed"] as const) { + const { db, store } = seeded(reason); + store.recordEvent({ ...attach, launchId: undefined, occurredAt: 5 }); + expect(store.get("durable")).toBeUndefined(); + store.recordEvent({ + ...attach, + launchId: undefined, + agentSessionId: "fresh-native-session", + occurredAt: 6, + }); + expect(store.get("durable")?.agentSessionId).toBe("fresh-native-session"); + expect(store.get("durable")?.account).toBeUndefined(); + expect( + db.query.terminalAgentBindings.findFirst().sync()?.endReason, + ).toBeNull(); + } + }); + it("does not transfer saved account provenance to a different workspace, provider, native session or launch", () => { + for (const change of [ + { workspaceId: "ws-2" }, + { agentId: "codex" as const }, + { agentSessionId: "other-native" }, + { launchId: "other-launch" }, + { launchId: undefined }, + ]) { + const { store } = seeded("detached"); + store.recordEvent({ ...attach, ...change, occurredAt: 5 }); + expect(store.get("durable")?.account).toBeUndefined(); + } + }); +}); diff --git a/packages/host-service/src/terminal-agents/persistence.ts b/packages/host-service/src/terminal-agents/persistence.ts index 01e74de4799..f988d2c35a2 100644 --- a/packages/host-service/src/terminal-agents/persistence.ts +++ b/packages/host-service/src/terminal-agents/persistence.ts @@ -12,6 +12,7 @@ import { } from "drizzle-orm"; import type { HostDb } from "../db"; import { terminalAgentBindings, terminalSessions } from "../db/schema.ts"; +import { parsePersistedSessionAccount } from "../trpc/router/usage/session-account/session-account"; import type { TerminalAgentBindingListFilter, TerminalAgentBindingPersistence, @@ -28,6 +29,8 @@ const bindingColumns = { agentId: terminalAgentBindings.agentId, agentSessionId: terminalAgentBindings.agentSessionId, definitionId: terminalAgentBindings.definitionId, + accountJson: terminalAgentBindings.accountJson, + launchId: terminalAgentBindings.launchId, startedAt: terminalAgentBindings.startedAt, lastEventAt: terminalAgentBindings.lastEventAt, lastEventType: terminalAgentBindings.lastEventType, @@ -41,6 +44,8 @@ interface BindingRow { agentId: TerminalAgentId; agentSessionId: string | null; definitionId: AgentDefinitionId | null; + accountJson: string | null; + launchId: string | null; startedAt: number; lastEventAt: number; lastEventType: string; @@ -49,12 +54,19 @@ interface BindingRow { } function rowToBinding(row: BindingRow): TerminalAgentBinding { + const account = parsePersistedSessionAccount(row.accountJson); return { terminalId: row.terminalId, workspaceId: row.workspaceId, agentId: row.agentId, ...(row.agentSessionId ? { agentSessionId: row.agentSessionId } : {}), ...(row.definitionId ? { definitionId: row.definitionId } : {}), + ...(account === null + ? { accountInvalid: true as const } + : account + ? { account } + : {}), + ...(row.launchId !== null ? { launchId: row.launchId } : {}), startedAt: row.startedAt, lastEventAt: row.lastEventAt, lastEventType: row.lastEventType, @@ -563,6 +575,10 @@ export class SqliteTerminalAgentBindingPersistence return markTerminalAgentBindingEnded(this.db, terminalId, reason, endedAt); } + getProvenance(terminalId: string): TerminalAgentBinding | undefined { + return getTerminalAgentBinding(this.db, terminalId); + } + getEnded( terminalId: string, ): { endedAt: number; agentSessionId?: string } | undefined { @@ -582,6 +598,11 @@ export class SqliteTerminalAgentBindingPersistence } upsert(binding: TerminalAgentBinding): void { + const accountJson = binding.accountInvalid + ? '{"invalid":true}' + : binding.account + ? JSON.stringify(binding.account) + : null; // A fresh event for the terminal revives an ended row: a new agent // session started there, so the old resume candidate is superseded. this.db @@ -592,6 +613,8 @@ export class SqliteTerminalAgentBindingPersistence agentId: binding.agentId, agentSessionId: binding.agentSessionId ?? null, definitionId: binding.definitionId ?? null, + accountJson, + launchId: binding.launchId ?? null, startedAt: binding.startedAt, lastEventAt: binding.lastEventAt, lastEventType: binding.lastEventType, @@ -605,6 +628,8 @@ export class SqliteTerminalAgentBindingPersistence agentId: binding.agentId, agentSessionId: binding.agentSessionId ?? null, definitionId: binding.definitionId ?? null, + accountJson, + launchId: binding.launchId ?? null, startedAt: binding.startedAt, lastEventAt: binding.lastEventAt, lastEventType: binding.lastEventType, diff --git a/packages/host-service/src/terminal-agents/saved-conversations/README.md b/packages/host-service/src/terminal-agents/saved-conversations/README.md new file mode 100644 index 00000000000..f54607f8d2f --- /dev/null +++ b/packages/host-service/src/terminal-agents/saved-conversations/README.md @@ -0,0 +1,52 @@ +# Saved conversation identity foundation + +The pure native validator checks supplied snapshots. It does not discover files, +import records, read credentials, launch providers or authorize a resume. The +ended-terminal account-resume path combines it with independent store, writer, +account and launch-claim guards. Synthetic tests exercise supported native shapes. + +`validateNativeConversation` checks complete Claude or Codex JSONL against an +explicit provider, native UUID and canonical working folder. It returns a digest +and record counts without returning message content. It rejects ambiguous copies, +mixed identities, worker transcripts, missing folder evidence and malformed +records. The caller must obtain a stable, strictly UTF-8-decoded complete snapshot +and enumerate all matching paths in the selected store. A partial search is not +proof of uniqueness. Reads above 64 MiB, records above 8 MiB, and more than 100,000 +records are unsupported here; no truncation is accepted. + +This is structural identity evidence, not transcript replay or a guarantee that +the provider will restore every item. Unknown record types remain in the digest. +Claude sessions with changed working folders or mixed compaction-session identities +are refused pending a qualified lineage adapter. Multiple Codex rollout revisions +are refused pending authoritative revision selection. No newest-file heuristic is +used. Matching names, folders, timestamps or text never merge conversations. + +## Integration boundary + +A future discovery/import service must validate source schema and read consistency, +canonicalize paths, bind a selected account/store, verify all writers, back up saved +history, persist a launch claim and confirm the launched native ID through provider +events. Its reference can populate the existing `HarnessSessionRef` fields +`agentId`, `sessionId`, `worktreePath` and `reportedPath`; account environment must +come from the account service, not source metadata. Never use `--continue`, `--last`, +a title or an app-thread ID as a substitute for an exact native UUID. + +Original import provenance and confirmed local continuation must be stored +separately. Reopening a locally continued conversation must validate its current +local transcript. A changed or missing original archive cannot justify replaying +that archive over newer local work. An imported catalog row alone does not prove +local adoption. Those persistence, launch and UI paths are follow-up work. + +## Official evidence checked October 9, 2026 + +- [Claude sessions](https://code.claude.com/docs/en/sessions) documents exact-ID + resume, cross-project duplicate refusal and limits of restored background work. + JSONL remains internal and needs versioned fixtures. +- [Anthropic's session reader, b6e9d12](https://github.com/anthropics/claude-agent-sdk-python/blob/b6e9d12fe1cc98dde988ab7b7713c1feeee50c6c/src/claude_agent_sdk/_internal/sessions.py) + distinguishes session ownership, worker records and message-chain reconstruction. + This module checks identity and does not duplicate that chain reconstruction. +- [Codex CLI commands](https://learn.chatgpt.com/docs/developer-commands?surface=cli) + documents exact-ID resume and working-folder selection. +- [Codex protocol, 4bad6d7](https://github.com/openai/codex/blob/4bad6d78e9b50f9fa8bd941f1db012ed491ad2da/codex-rs/protocol/src/protocol.rs) + defines `SessionMeta.id` as the thread identity; `session_id` can identify its root. + Creator account metadata is historical, not the account used for this launch. diff --git a/packages/host-service/src/terminal-agents/saved-conversations/index.ts b/packages/host-service/src/terminal-agents/saved-conversations/index.ts new file mode 100644 index 00000000000..e6039e36d84 --- /dev/null +++ b/packages/host-service/src/terminal-agents/saved-conversations/index.ts @@ -0,0 +1,9 @@ +export { validateNativeConversation } from "./native"; +export type { + NativeConversationEvidence, + NativeConversationReference, + SavedConversationIssue, + SavedConversationProvider, + SavedConversationResult, + TranscriptSnapshot, +} from "./types"; diff --git a/packages/host-service/src/terminal-agents/saved-conversations/inspect-native-history.test.ts b/packages/host-service/src/terminal-agents/saved-conversations/inspect-native-history.test.ts new file mode 100644 index 00000000000..c1a0541e9e2 --- /dev/null +++ b/packages/host-service/src/terminal-agents/saved-conversations/inspect-native-history.test.ts @@ -0,0 +1,218 @@ +import { afterEach, expect, test } from "bun:test"; +import { + appendFile, + mkdir, + mkdtemp, + open, + realpath, + rename, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { + assertNativeResumeHistoryCurrent, + inspectNativeResumeHistory, + inspectNativeResumeHistoryWithReader, +} from "./inspect-native-history"; + +const roots: string[] = []; +const sessionId = "11111111-2222-3333-4444-555555555555"; +afterEach(async () => { + await Promise.all( + roots.splice(0).map((root) => rm(root, { recursive: true, force: true })), + ); +}); + +async function fixture(provider: "claude" | "codex" = "claude") { + const temporary = await mkdtemp(join(tmpdir(), "resume-checkpoint-")); + roots.push(temporary); + const root = await realpath(temporary); + const cwd = join(root, "workspace"); + const shared = join(root, "history"); + const sourceDirectory = join(root, "source"); + const targetDirectory = join(root, "target"); + const lockRoot = join(root, "locks"); + await Promise.all( + [cwd, shared, sourceDirectory, targetDirectory, lockRoot].map((path) => + mkdir(path), + ), + ); + const storeName = provider === "claude" ? "projects" : "sessions"; + for (const directory of [sourceDirectory, targetDirectory]) { + await symlink(shared, join(directory, storeName)); + if (provider === "codex") + await symlink(lockRoot, join(directory, "thread-writer-locks")); + } + const project = join(shared, "project"); + await mkdir(project); + const path = join( + project, + provider === "claude" + ? `${sessionId}.jsonl` + : `rollout-2026-10-25T10-10-10-${sessionId}.jsonl`, + ); + const content = + provider === "claude" + ? `${JSON.stringify({ type: "user", sessionId, cwd, uuid: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", message: { role: "user", content: "synthetic saved history" } })}\n` + : `${JSON.stringify({ type: "session_meta", payload: { id: sessionId, cwd } })}\n${JSON.stringify({ type: "response_item", payload: { type: "message", role: "user", content: [{ type: "input_text", text: "synthetic saved history" }] } })}\n`; + await writeFile(path, content); + return { + root, + path, + content, + input: { provider, sourceDirectory, targetDirectory, sessionId, cwd }, + }; +} + +function afterRead(action: () => Promise): typeof open { + return async (path, flags, mode) => { + const file = await open(path, flags, mode); + let changed = false; + return new Proxy(file, { + get(target, property) { + if (property === "read") + return async ( + buffer: Buffer, + offset: number, + length: number, + position: number, + ) => { + const result = await target.read(buffer, offset, length, position); + if (!changed) { + changed = true; + await action(); + } + return result; + }; + const value = Reflect.get(target, property, target); + return typeof value === "function" ? value.bind(target) : value; + }, + }); + }; +} + +test.each([ + "claude", + "codex", +] as const)("a stable exact %s history includes launch-time store checkpoints", async (provider) => { + const f = await fixture(provider); + const history = await inspectNativeResumeHistory(f.input); + expect(history?.path).toBe(f.path); + expect(history?.storeBindings).toHaveLength(provider === "claude" ? 2 : 4); + if (!history) throw new Error("Missing fixture history"); + expect(() => assertNativeResumeHistoryCurrent(history)).not.toThrow(); +}); + +test("a parent-directory replacement cannot validate an unlinked old transcript descriptor", async () => { + const f = await fixture(); + const result = await inspectNativeResumeHistoryWithReader( + f.input, + afterRead(async () => { + await rename(dirname(f.path), join(f.root, "retired-project")); + await mkdir(dirname(f.path)); + await writeFile( + f.path, + f.content.replace("saved history", "replacement"), + ); + }), + ); + expect(result).toBeNull(); +}); + +test("a destination history-root retarget during a read is rejected", async () => { + const f = await fixture(); + const result = await inspectNativeResumeHistoryWithReader( + f.input, + afterRead(async () => { + const next = join(f.root, "other-history"); + await mkdir(next); + const store = join(f.input.targetDirectory, "projects"); + await rm(store); + await symlink(next, store); + }), + ); + expect(result).toBeNull(); +}); + +test("a Codex destination writer-lock retarget during a read is rejected", async () => { + const f = await fixture("codex"); + const result = await inspectNativeResumeHistoryWithReader( + f.input, + afterRead(async () => { + const next = join(f.root, "other-locks"); + await mkdir(next); + const store = join(f.input.targetDirectory, "thread-writer-locks"); + await rm(store); + await symlink(next, store); + }), + ); + expect(result).toBeNull(); +}); + +test("a transcript changed after asynchronous validation fails command authorization", async () => { + const f = await fixture(); + const history = await inspectNativeResumeHistory(f.input); + if (!history) throw new Error("Missing fixture history"); + await appendFile(f.path, "\n"); + expect(() => assertNativeResumeHistoryCurrent(history)).toThrow(); +}); + +test("a destination root changed after validation fails command authorization", async () => { + const f = await fixture(); + const history = await inspectNativeResumeHistory(f.input); + if (!history) throw new Error("Missing fixture history"); + const store = join(f.input.targetDirectory, "projects"); + await rm(store); + await mkdir(store); + expect(() => assertNativeResumeHistoryCurrent(history)).toThrow(); +}); + +for (const provider of ["claude", "codex"] as const) { + test(`normal ${provider} exit may append while preserving every previously admitted byte`, async () => { + const f = await fixture(provider); + const original = await inspectNativeResumeHistory(f.input); + if (!original) throw new Error("Missing fixture history"); + const appended = + provider === "claude" + ? { + type: "assistant", + sessionId, + cwd: f.input.cwd, + uuid: "bbbbbbbb-cccc-dddd-eeee-ffffffffffff", + message: { role: "assistant", content: "saved final response" }, + } + : { type: "event_msg", payload: { type: "fixture_final_record" } }; + await appendFile(f.path, `${JSON.stringify(appended)}\n`); + const final = await inspectNativeResumeHistory({ + ...f.input, + previous: original, + }); + expect(final?.size).toBeGreaterThan(original.size); + expect(final?.sha256).not.toBe(original.sha256); + if (!final) throw new Error("Missing final fixture history"); + expect(() => assertNativeResumeHistoryCurrent(final)).not.toThrow(); + await appendFile(f.path, "\n"); + expect(() => assertNativeResumeHistoryCurrent(final)).toThrow(); + }); + for (const mutation of ["truncate", "rewrite", "replace"] as const) { + test(`post-exit ${provider} ${mutation} cannot substitute for append-only history`, async () => { + const f = await fixture(provider); + const original = await inspectNativeResumeHistory(f.input); + if (!original) throw new Error("Missing fixture history"); + if (mutation === "replace") await rename(f.path, `${f.path}.retired`); + const changed = + mutation === "truncate" + ? f.content.replace("synthetic saved history", "tiny") + : f.content.replace("saved", "other"); + await writeFile(f.path, changed); + // The replacement remains independently valid native history: only the old prefix fence rejects it. + expect(await inspectNativeResumeHistory(f.input)).not.toBeNull(); + expect( + await inspectNativeResumeHistory({ ...f.input, previous: original }), + ).toBeNull(); + }); + } +} diff --git a/packages/host-service/src/terminal-agents/saved-conversations/inspect-native-history.ts b/packages/host-service/src/terminal-agents/saved-conversations/inspect-native-history.ts new file mode 100644 index 00000000000..76e0f5d15b1 --- /dev/null +++ b/packages/host-service/src/terminal-agents/saved-conversations/inspect-native-history.ts @@ -0,0 +1,247 @@ +import { createHash } from "node:crypto"; +import { constants, lstatSync, realpathSync, statSync } from "node:fs"; +import { lstat, open, readdir, realpath, stat } from "node:fs/promises"; +import { isAbsolute, join } from "node:path"; +import { MAX_TRANSCRIPT_BYTES, validateNativeConversation } from "./native"; + +const MAX_DIRECTORIES = 5000; + +export interface AccountResumeHistory { + path: string; + device: number; + inode: number; + size: number; + modifiedAt: number; + changedAt: number; + sha256: string; + storeBindings?: Array<{ path: string; canonical: string }>; +} + +export function assertNativeResumeHistoryCurrent( + history: AccountResumeHistory, +): void { + const file = lstatSync(history.path); + if ( + !file.isFile() || + realpathSync(history.path) !== history.path || + file.dev !== history.device || + file.ino !== history.inode || + file.size !== history.size || + file.mtimeMs !== history.modifiedAt || + file.ctimeMs !== history.changedAt || + history.storeBindings?.some( + (binding) => + realpathSync(binding.path) !== binding.canonical || + !statSync(binding.path).isDirectory(), + ) + ) + refuse(); +} + +function refuse(): never { + throw new Error("Saved history unavailable"); +} + +export interface NativeResumeHistoryInput { + provider: "claude" | "codex"; + sourceDirectory: string; + targetDirectory: string; + sessionId: string; + cwd: string; + /** Require all bytes admitted before normal source exit to remain unchanged. */ + previous?: AccountResumeHistory; +} + +async function sharedDirectory( + source: string, + target: string, + name: string, +): Promise { + const [left, right] = await Promise.all([ + realpath(join(source, name)), + realpath(join(target, name)), + ]); + if (left !== right || !(await stat(left)).isDirectory()) refuse(); + return left; +} + +async function exactSessionFile( + root: string, + provider: "claude" | "codex", + sessionId: string, +): Promise { + const codexFilename = new RegExp( + `-${sessionId}(?:_[\\w-]+)?\\.jsonl(?:\\.zst)?$`, + ); + const pending = [root]; + const matches: string[] = []; + let visited = 0; + while (pending.length > 0) { + if (++visited > MAX_DIRECTORIES) refuse(); + const directory = pending.pop(); + if (!directory) break; + const entries = await readdir(directory, { withFileTypes: true }); + for (const entry of entries) { + const path = join(directory, entry.name); + const nameMatches = + provider === "claude" + ? entry.name === `${sessionId}.jsonl` + : codexFilename.test(entry.name); + if (nameMatches) { + if (!entry.isFile() || entry.name.endsWith(".zst")) refuse(); + matches.push(path); + if (matches.length > 1) refuse(); + } else if (entry.isSymbolicLink()) { + // Only the shared store root may be a link. Nested aliases can + // hide another copy from a bounded directory walk. + refuse(); + } else if ( + entry.isDirectory() && + (provider !== "claude" || directory === root) + ) { + pending.push(path); + } + } + } + if (matches.length !== 1) refuse(); + return matches[0] as string; +} + +export async function inspectNativeResumeHistory( + input: NativeResumeHistoryInput, +): Promise { + return inspectNativeResumeHistoryWithReader(input, open); +} + +export async function inspectNativeResumeHistoryWithReader( + input: NativeResumeHistoryInput, + openFile: typeof open, +): Promise { + const { provider, sourceDirectory, targetDirectory, sessionId, cwd } = input; + if ( + !isAbsolute(sourceDirectory) || + !isAbsolute(targetDirectory) || + !/^[\w-]+$/.test(sessionId) + ) + return null; + try { + const root = await sharedDirectory( + sourceDirectory, + targetDirectory, + provider === "claude" ? "projects" : "sessions", + ); + const storeBindings = [sourceDirectory, targetDirectory].map((profile) => ({ + path: join(profile, provider === "claude" ? "projects" : "sessions"), + canonical: root, + })); + if (provider === "codex") { + // Native Codex writer ownership is scoped to this directory, not + // the rollout tree: codex-rs/rollout/src/writer_lock.rs. + const lockRoot = await sharedDirectory( + sourceDirectory, + targetDirectory, + "thread-writer-locks", + ); + storeBindings.push( + ...[sourceDirectory, targetDirectory].map((profile) => ({ + path: join(profile, "thread-writer-locks"), + canonical: lockRoot, + })), + ); + } + const path = await exactSessionFile(root, provider, sessionId); + const file = await openFile( + path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const before = await file.stat(); + if ( + !before.isFile() || + before.size === 0 || + before.size > MAX_TRANSCRIPT_BYTES + ) + refuse(); + const previous = input.previous; + if ( + previous && + (previous.path !== path || + previous.device !== before.dev || + previous.inode !== before.ino || + !Number.isSafeInteger(previous.size) || + previous.size <= 0 || + previous.size > before.size || + !/^[a-f0-9]{64}$/.test(previous.sha256) || + JSON.stringify(previous.storeBindings) !== + JSON.stringify(storeBindings)) + ) + refuse(); + const buffer = Buffer.alloc(before.size); + let offset = 0; + while (offset < buffer.length) { + const { bytesRead } = await file.read( + buffer, + offset, + Math.min(64 * 1024, buffer.length - offset), + offset, + ); + if (!bytesRead) refuse(); + offset += bytesRead; + } + if ( + previous && + createHash("sha256") + .update(buffer.subarray(0, previous.size)) + .digest("hex") !== previous.sha256 + ) + refuse(); + const content = new TextDecoder("utf-8", { + fatal: true, + ignoreBOM: true, + }).decode(buffer); + const evidence = validateNativeConversation( + { provider, sessionId, cwd: await realpath(cwd) }, + [{ canonicalPath: path, content, complete: true }], + ); + if (!evidence.ok) refuse(); + const after = await file.stat(); + const named = await lstat(path); + if ( + before.size !== after.size || + before.mtimeMs !== after.mtimeMs || + before.ctimeMs !== after.ctimeMs || + !named.isFile() || + named.dev !== after.dev || + named.ino !== after.ino || + named.size !== after.size || + named.mtimeMs !== after.mtimeMs || + named.ctimeMs !== after.ctimeMs || + (await realpath(path)) !== path || + !( + await Promise.all( + storeBindings.map( + async (binding) => + (await realpath(binding.path)) === binding.canonical && + (await stat(binding.path)).isDirectory(), + ), + ) + ).every(Boolean) + ) + refuse(); + return { + path, + device: after.dev, + inode: after.ino, + size: after.size, + modifiedAt: after.mtimeMs, + changedAt: after.ctimeMs, + sha256: evidence.value.sha256, + storeBindings, + }; + } finally { + await file.close(); + } + } catch { + return null; + } +} diff --git a/packages/host-service/src/terminal-agents/saved-conversations/native.test.ts b/packages/host-service/src/terminal-agents/saved-conversations/native.test.ts new file mode 100644 index 00000000000..4f2f457e5dd --- /dev/null +++ b/packages/host-service/src/terminal-agents/saved-conversations/native.test.ts @@ -0,0 +1,265 @@ +import { describe, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { validateNativeConversation } from "./native"; +import type { NativeConversationReference, TranscriptSnapshot } from "./types"; + +const SESSION = "11111111-1111-4111-8111-111111111111"; +const OTHER = "22222222-2222-4222-8222-222222222222"; +const USER = "33333333-3333-4333-8333-333333333333"; +const HEAD = "44444444-4444-4444-8444-444444444444"; +const CWD = "/work/project"; +const reference: NativeConversationReference = { + provider: "claude", + sessionId: SESSION, + cwd: CWD, +}; + +function claude(overrides: Record = {}) { + return { + type: "assistant", + sessionId: SESSION, + cwd: CWD, + uuid: HEAD, + parentUuid: USER, + message: { role: "assistant", content: "Saved response" }, + ...overrides, + }; +} + +function snapshot(...records: unknown[]): TranscriptSnapshot { + return { + canonicalPath: `/profiles/a/projects/project/${SESSION}.jsonl`, + content: records.map((r) => JSON.stringify(r)).join("\n"), + complete: true, + }; +} + +function codexMeta(overrides: Record = {}) { + return { + type: "session_meta", + payload: { id: SESSION, cwd: CWD, source: "cli", ...overrides }, + }; +} +const codexMessage = { + type: "response_item", + payload: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "Saved response" }], + }, +}; +const codexReference = { ...reference, provider: "codex" } as const; + +describe("saved native conversation identity", () => { + test("validates complete Claude records without exposing conversation text", () => { + const file = snapshot( + claude({ type: "user", uuid: USER, parentUuid: null }), + claude(), + ); + const result = validateNativeConversation(reference, [file]); + expect(result).toEqual({ + ok: true, + value: { + reference, + transcriptPath: file.canonicalPath, + sha256: createHash("sha256").update(file.content).digest("hex"), + bytes: Buffer.byteLength(file.content), + records: 2, + messageRecords: 2, + }, + }); + expect(JSON.stringify(result)).not.toContain("Saved response"); + }); + + test("keeps two conversations in the same folder separate", () => { + const first = validateNativeConversation(reference, [snapshot(claude())]); + const second = validateNativeConversation( + { ...reference, sessionId: OTHER }, + [snapshot(claude({ sessionId: OTHER }))], + ); + expect(first.ok && second.ok).toBe(true); + if (first.ok && second.ok) + expect(first.value.reference.sessionId).not.toBe( + second.value.reference.sessionId, + ); + }); + + test("does not select among duplicate stores even when their bytes match", () => { + const file = snapshot(claude()); + expect( + validateNativeConversation(reference, [ + file, + { ...file, canonicalPath: "/profiles/b/copy.jsonl" }, + ]), + ).toEqual({ ok: false, issue: "ambiguous_transcript" }); + }); + + test("requires a complete snapshot and a present transcript", () => { + expect(validateNativeConversation(reference, [])).toEqual({ + ok: false, + issue: "missing_transcript", + }); + expect( + validateNativeConversation(reference, [ + { ...snapshot(claude()), complete: false }, + ]), + ).toEqual({ ok: false, issue: "incomplete_transcript" }); + }); + + test.each([ + "../session", + "last", + "", + `${SESSION}\n`, + ])("refuses non-native identity %j", (sessionId) => { + expect( + validateNativeConversation({ ...reference, sessionId }, [ + snapshot(claude()), + ]), + ).toEqual({ ok: false, issue: "invalid_reference" }); + }); + + test.each([ + "relative/project", + "/work/../project", + "/work/\u0000project", + ])("refuses an unresolved working path %j", (cwd) => { + expect( + validateNativeConversation({ ...reference, cwd }, [snapshot(claude())]), + ).toEqual({ ok: false, issue: "invalid_reference" }); + }); + + test("does not let an initial matching record hide a foreign identity", () => { + expect( + validateNativeConversation(reference, [ + snapshot(claude(), claude({ sessionId: OTHER })), + ]), + ).toEqual({ ok: false, issue: "session_mismatch" }); + }); + + test("rejects messages with no ownership and metadata without messages", () => { + expect( + validateNativeConversation(reference, [ + snapshot(claude({ sessionId: undefined })), + ]), + ).toEqual({ ok: false, issue: "session_mismatch" }); + expect( + validateNativeConversation(reference, [ + snapshot({ type: "queue-operation", sessionId: SESSION, cwd: CWD }), + ]), + ).toEqual({ ok: false, issue: "empty_conversation" }); + }); + + test("checks working-folder evidence throughout the snapshot", () => { + expect( + validateNativeConversation(reference, [ + snapshot(claude(), claude({ cwd: "/work/other" })), + ]), + ).toEqual({ ok: false, issue: "cwd_mismatch" }); + expect( + validateNativeConversation(reference, [ + snapshot(claude({ cwd: undefined })), + ]), + ).toEqual({ ok: false, issue: "missing_cwd" }); + }); + + test.each([ + { isSidechain: true }, + { teamName: "worker" }, + ])("does not import a Claude worker as an independent chat: %j", (overrides) => { + expect( + validateNativeConversation(reference, [snapshot(claude(overrides))]), + ).toEqual({ ok: false, issue: "subagent_transcript" }); + }); + + test.each([ + "{", + "null", + "[]", + '{"message":{}}', + ])("does not silently skip a malformed trailing record: %j", (tail) => { + const file = snapshot(claude()); + expect( + validateNativeConversation(reference, [ + { ...file, content: `${file.content}\n${tail}` }, + ]), + ).toEqual({ ok: false, issue: "invalid_record" }); + }); + + test("requires a selected Claude head to be the last assistant record", () => { + const pinned = { ...reference, headUuid: HEAD }; + expect(validateNativeConversation(pinned, [snapshot(claude())]).ok).toBe( + true, + ); + for (const later of [ + claude({ uuid: OTHER }), + claude({ type: "user", uuid: HEAD }), + ]) { + expect( + validateNativeConversation(pinned, [snapshot(claude(), later)]), + ).toEqual({ ok: false, issue: "head_mismatch" }); + } + }); + + test("Codex resumes the thread id, not session_id, title or creator account", () => { + const file = snapshot( + codexMeta({ session_id: OTHER, creator_account_id: "unrelated-account" }), + codexMessage, + ); + expect(validateNativeConversation(codexReference, [file]).ok).toBe(true); + expect( + validateNativeConversation({ ...codexReference, sessionId: OTHER }, [ + file, + ]), + ).toEqual({ ok: false, issue: "session_mismatch" }); + }); + + test("supports old bare Codex message records without inventing identity", () => { + expect( + validateNativeConversation(codexReference, [ + snapshot(codexMeta(), codexMessage.payload), + ]).ok, + ).toBe(true); + expect( + validateNativeConversation(codexReference, [ + snapshot(codexMessage.payload), + ]), + ).toEqual({ ok: false, issue: "missing_session" }); + }); + + test("rejects duplicated or displaced Codex metadata", () => { + for (const records of [ + [codexMeta(), codexMeta({ id: OTHER }), codexMessage], + [codexMessage, codexMeta()], + ]) { + expect( + validateNativeConversation(codexReference, [snapshot(...records)]), + ).toEqual({ ok: false, issue: "invalid_record" }); + } + }); + + test.each([ + { parent_thread_id: OTHER }, + { source: { subagent: { thread_spawn: { parent_thread_id: OTHER } } } }, + { source: { internal: "memory_consolidation" } }, + ])("does not promote a Codex worker to an independent chat: %j", (extra) => { + expect( + validateNativeConversation(codexReference, [ + snapshot(codexMeta(extra), codexMessage), + ]), + ).toEqual({ ok: false, issue: "subagent_transcript" }); + }); + + test("requires Codex working folder evidence and rejects Claude head options", () => { + expect( + validateNativeConversation(codexReference, [ + snapshot(codexMeta({ cwd: "/work/other" }), codexMessage), + ]), + ).toEqual({ ok: false, issue: "cwd_mismatch" }); + expect( + validateNativeConversation({ ...codexReference, headUuid: HEAD }, [ + snapshot(codexMeta(), codexMessage), + ]), + ).toEqual({ ok: false, issue: "invalid_reference" }); + }); +}); diff --git a/packages/host-service/src/terminal-agents/saved-conversations/native.ts b/packages/host-service/src/terminal-agents/saved-conversations/native.ts new file mode 100644 index 00000000000..56bad74553b --- /dev/null +++ b/packages/host-service/src/terminal-agents/saved-conversations/native.ts @@ -0,0 +1,175 @@ +import { createHash } from "node:crypto"; +import { isAbsolute, normalize } from "node:path"; +import type { + NativeConversationEvidence, + NativeConversationReference, + SavedConversationResult, + TranscriptSnapshot, +} from "./types"; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export const MAX_TRANSCRIPT_BYTES = 64 * 1024 * 1024; +const MAX_RECORD_BYTES = 8 * 1024 * 1024; +const MAX_RECORDS = 100_000; + +function isNativeSessionId(value: unknown): value is string { + return typeof value === "string" && UUID.test(value); +} + +function hasControlCharacters(value: string): boolean { + for (const character of value) { + const code = character.charCodeAt(0); + if (code < 32 || code === 127) return true; + } + return false; +} + +function isCanonicalPathInput(value: unknown): value is string { + return ( + typeof value === "string" && + isAbsolute(value) && + !hasControlCharacters(value) && + normalize(value) === value + ); +} + +function object(value: unknown): Record | null { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +function isCodexChild(payload: Record): boolean { + const source = object(payload.source); + return ( + payload.parent_thread_id != null || + payload.source === "subagent" || + payload.source === "internal" || + (source !== null && ("subagent" in source || "internal" in source)) + ); +} + +/** + * Identity evidence only. The caller must independently check store ownership, + * stable file reads, writers and launch-time identity; this never grants resume. + * Candidate paths must come from a complete search, deduplicated by realpath. + */ +export function validateNativeConversation( + reference: NativeConversationReference, + snapshots: readonly TranscriptSnapshot[], +): SavedConversationResult { + if ( + (reference.provider !== "claude" && reference.provider !== "codex") || + !isNativeSessionId(reference.sessionId) || + !isCanonicalPathInput(reference.cwd) || + (reference.headUuid !== undefined && + (reference.provider !== "claude" || + !isNativeSessionId(reference.headUuid))) + ) { + return { ok: false, issue: "invalid_reference" }; + } + if (snapshots.length === 0) return { ok: false, issue: "missing_transcript" }; + // Even matching bytes at two paths do not establish the provider's lookup. + if (snapshots.length !== 1) + return { ok: false, issue: "ambiguous_transcript" }; + const snapshot = snapshots[0]; + if (!snapshot || !isCanonicalPathInput(snapshot.canonicalPath)) + return { ok: false, issue: "invalid_reference" }; + if (snapshot.complete !== true) + return { ok: false, issue: "incomplete_transcript" }; + const bytes = Buffer.byteLength(snapshot.content, "utf8"); + if (bytes > MAX_TRANSCRIPT_BYTES) + return { ok: false, issue: "transcript_too_large" }; + let records = 0; + let messageRecords = 0; + let foundSession = false; + let foundCwd = false; + let lastMessageUuid: unknown = null; + let lastMessageType: unknown = null; + let codexMetadataCount = 0; + for (const line of snapshot.content.split("\n")) { + if (!line.trim()) continue; + if (++records > MAX_RECORDS || Buffer.byteLength(line) > MAX_RECORD_BYTES) + return { ok: false, issue: "transcript_too_large" }; + let event: Record | null; + try { + event = object(JSON.parse(line)); + } catch { + return { ok: false, issue: "invalid_record" }; + } + if (!event || typeof event.type !== "string") + return { ok: false, issue: "invalid_record" }; + let cwd: unknown; + if (reference.provider === "claude") { + if ( + event.sessionId !== undefined && + event.sessionId !== reference.sessionId + ) + return { ok: false, issue: "session_mismatch" }; + if (event.sessionId === reference.sessionId) { + foundSession = true; + cwd = event.cwd; + } + if (event.type === "user" || event.type === "assistant") { + if (event.sessionId !== reference.sessionId) + return { ok: false, issue: "session_mismatch" }; + if (event.isSidechain === true || event.teamName != null) + return { ok: false, issue: "subagent_transcript" }; + if (!object(event.message) || !isNativeSessionId(event.uuid)) + return { ok: false, issue: "invalid_record" }; + messageRecords++; + lastMessageUuid = event.uuid; + lastMessageType = event.type; + } + } else { + if (event.type === "session_meta") { + const payload = object(event.payload); + if (!payload || ++codexMetadataCount !== 1 || records !== 1) + return { ok: false, issue: "invalid_record" }; + // session_id may identify a root thread. Only id is resumable here. + if (payload.id !== reference.sessionId) + return { ok: false, issue: "session_mismatch" }; + if (isCodexChild(payload)) + return { ok: false, issue: "subagent_transcript" }; + foundSession = true; + cwd = payload.cwd; + } + const item = + event.type === "response_item" ? object(event.payload) : event; + if ( + item?.type === "message" && + (item.role === "user" || item.role === "assistant") + ) { + if (!Array.isArray(item.content)) + return { ok: false, issue: "invalid_record" }; + messageRecords++; + } + } + if (cwd !== undefined) { + if (!isCanonicalPathInput(cwd) || cwd !== reference.cwd) + return { ok: false, issue: "cwd_mismatch" }; + foundCwd = true; + } + } + if (!foundSession) return { ok: false, issue: "missing_session" }; + if (!foundCwd) return { ok: false, issue: "missing_cwd" }; + if (!messageRecords) return { ok: false, issue: "empty_conversation" }; + if ( + reference.headUuid !== undefined && + (lastMessageUuid !== reference.headUuid || lastMessageType !== "assistant") + ) + return { ok: false, issue: "head_mismatch" }; + return { + ok: true, + value: { + reference: { ...reference }, + transcriptPath: snapshot.canonicalPath, + sha256: createHash("sha256") + .update(snapshot.content, "utf8") + .digest("hex"), + bytes, + records, + messageRecords, + }, + }; +} diff --git a/packages/host-service/src/terminal-agents/saved-conversations/types.ts b/packages/host-service/src/terminal-agents/saved-conversations/types.ts new file mode 100644 index 00000000000..44264463340 --- /dev/null +++ b/packages/host-service/src/terminal-agents/saved-conversations/types.ts @@ -0,0 +1,47 @@ +export type SavedConversationProvider = "claude" | "codex"; + +export interface NativeConversationReference { + provider: SavedConversationProvider; + /** Claude session UUID or Codex thread UUID, never an app's chat ID. */ + sessionId: string; + /** The caller must resolve symlinks before supplying paths. */ + cwd: string; + /** A source-selected Claude branch position; must be the final message. */ + headUuid?: string; +} + +export interface TranscriptSnapshot { + canonicalPath: string; + /** Complete, strictly decoded UTF-8 JSONL from one stable file read. */ + content: string; + complete: boolean; +} + +export interface NativeConversationEvidence { + reference: NativeConversationReference; + transcriptPath: string; + sha256: string; + bytes: number; + records: number; + /** Record count, not a reconstructed conversation or active-branch count. */ + messageRecords: number; +} + +export type SavedConversationIssue = + | "invalid_reference" + | "missing_transcript" + | "ambiguous_transcript" + | "incomplete_transcript" + | "transcript_too_large" + | "invalid_record" + | "session_mismatch" + | "missing_session" + | "cwd_mismatch" + | "missing_cwd" + | "subagent_transcript" + | "empty_conversation" + | "head_mismatch"; + +export type SavedConversationResult = + | { ok: true; value: T } + | { ok: false; issue: SavedConversationIssue }; diff --git a/packages/host-service/src/terminal-agents/store.test.ts b/packages/host-service/src/terminal-agents/store.test.ts index d0aa7d7dd91..374d2ab5c8e 100644 --- a/packages/host-service/src/terminal-agents/store.test.ts +++ b/packages/host-service/src/terminal-agents/store.test.ts @@ -328,6 +328,31 @@ describe("TerminalAgentStore", () => { } }); + it("first native identity enriches a working launch without replacing its lifecycle", () => { + store.recordEvent({ + terminalId: "t1", + workspaceId: WORKSPACE, + eventType: "Start", + agentId: "claude", + launchId: "one", + occurredAt: 100, + }); + store.recordEvent({ + terminalId: "t1", + workspaceId: WORKSPACE, + eventType: "Attached", + agentId: "claude", + agentSessionId: "native", + launchId: "one", + occurredAt: 200, + }); + expect(store.get("t1")).toMatchObject({ + lastEventType: "Start", + agentSessionId: "native", + startedAt: 100, + }); + }); + it("Attached with a new session id overrides the previous session's working state", () => { store.recordEvent({ terminalId: "t1", @@ -901,3 +926,34 @@ describe("session account attribution", () => { expect(store.listByWorkspace("ws-account")[0]?.account).toEqual(account); }); }); + +it("does not transfer in-memory account provenance when the terminal moves to another workspace", () => { + const store = new TerminalAgentStore(); + const launch = { + terminalId: "moved", + workspaceId: "one", + agentId: "claude" as const, + agentSessionId: "native", + launchId: "launch", + eventType: "Attached", + occurredAt: 1, + }; + store.recordEvent({ + ...launch, + account: { + agent: "claude", + selection: "/fixture/profile", + credentialKind: "subscription", + identity: "a".repeat(64), + pinned: true, + }, + }); + store.recordEvent({ + ...launch, + workspaceId: "two", + eventType: "Start", + occurredAt: 2, + }); + expect(store.get("moved")?.workspaceId).toBe("two"); + expect(store.get("moved")?.account).toBeUndefined(); +}); diff --git a/packages/host-service/src/terminal-agents/store.ts b/packages/host-service/src/terminal-agents/store.ts index 30a3ab3a6ec..446bdc5b49b 100644 --- a/packages/host-service/src/terminal-agents/store.ts +++ b/packages/host-service/src/terminal-agents/store.ts @@ -93,6 +93,7 @@ export interface TerminalAgentBindingPersistence { load(): TerminalAgentBinding[]; upsert(binding: TerminalAgentBinding): void; delete(terminalId: string): void; + getProvenance?(terminalId: string): TerminalAgentBinding | undefined; /** * Retain the row but stamp `endedAt`/`endReason` so the agent session id * survives as a resume candidate. Absent → the store falls back to @@ -168,6 +169,17 @@ export class TerminalAgentStore extends EventEmitter { } const ended = this.persistence?.getEnded?.(terminalId); + const durable = this.persistence?.getProvenance?.(terminalId); + if ( + ended && + durable && + (durable.endReason === "resumed" || durable.endReason === "disposed") && + ((!input.launchId && !agentSessionId) || + (input.launchId !== undefined && durable.launchId === input.launchId) || + (agentSessionId !== undefined && + durable.agentSessionId === agentSessionId)) + ) + return; const existing = ended ? undefined : this.byTerminal.get(terminalId); if (!agentId && !existing) return; @@ -191,17 +203,39 @@ export class TerminalAgentStore extends EventEmitter { // Only inherit identity metadata when agentId hasn't changed; otherwise // a swap event that omits agentSessionId/definitionId would inherit the // prior agent's values and corrupt definitionId-filtered reads. - const prior = + const memoryPrior = existing !== undefined && + existing.workspaceId === workspaceId && existing.agentId === nextAgentId && (!input.launchId || !existing.launchId || input.launchId === existing.launchId) ? existing : undefined; + const sameDurableLaunch = + durable && + (durable.agentId === "claude" || durable.agentId === "codex") && + durable.workspaceId === workspaceId && + durable.agentId === nextAgentId && + !!agentSessionId && + durable.agentSessionId === agentSessionId && + !!input.launchId && + durable.launchId === input.launchId && + (durable.endedAt === undefined || + durable.endReason === "detached" || + durable.endReason === "terminal-exited"); + const prior = sameDurableLaunch + ? { + ...durable, + ...memoryPrior, + account: memoryPrior?.account ?? durable.account, + accountInvalid: memoryPrior?.accountInvalid ?? durable.accountInvalid, + startedAt: durable.startedAt, + } + : memoryPrior; const sessionChanged = - prior !== undefined && + prior?.agentSessionId !== undefined && agentSessionId !== undefined && prior.agentSessionId !== agentSessionId; @@ -227,6 +261,7 @@ export class TerminalAgentStore extends EventEmitter { agentSessionId: agentSessionId ?? prior?.agentSessionId, definitionId: definitionId ?? prior?.definitionId, launchId: input.launchId ?? prior?.launchId, + accountInvalid: input.account ? undefined : prior?.accountInvalid, account: input.account ?? (prior && (!sessionChanged || prior.agentSessionId === undefined) @@ -249,6 +284,27 @@ export class TerminalAgentStore extends EventEmitter { this.emit("activity", workspaceId); } + updateMetadata( + terminalId: string, + metadata: Pick< + RecordEventInput, + "account" | "agentSessionId" | "definitionId" + >, + ): void { + const prior = this.byTerminal.get(terminalId); + if (!prior || this.persistence?.getEnded?.(terminalId)) return; + const next = { + ...prior, + account: metadata.account ?? prior.account, + accountInvalid: metadata.account ? undefined : prior.accountInvalid, + agentSessionId: metadata.agentSessionId ?? prior.agentSessionId, + definitionId: metadata.definitionId ?? prior.definitionId, + }; + this.byTerminal.set(terminalId, next); + this.persistence?.upsert(next); + this.emit("change", prior.workspaceId); + } + recordChatEvent( input: RecordEventInput & { agentId: TerminalAgentId; @@ -502,6 +558,23 @@ export class TerminalAgentStore extends EventEmitter { if (changed) this.emit("change", workspaceId); } + reloadBinding(terminalId: string): void { + const previous = this.byTerminal.get(terminalId); + const durable = this.persistence?.getProvenance?.(terminalId); + if (durable && durable.endedAt === undefined) + this.byTerminal.set(terminalId, durable); + else this.byTerminal.delete(terminalId); + const workspaceId = durable?.workspaceId ?? previous?.workspaceId; + if (workspaceId) this.emit("change", workspaceId); + } + + getProvenance(terminalId: string): TerminalAgentBinding | undefined { + const durable = this.persistence?.getProvenance?.(terminalId); + return durable?.endedAt !== undefined + ? durable + : (this.byTerminal.get(terminalId) ?? durable); + } + get(terminalId: string): TerminalAgentBinding | undefined { if (this.persistence?.getEnded?.(terminalId)) return undefined; const binding = this.byTerminal.get(terminalId); diff --git a/packages/host-service/src/terminal-agents/types.ts b/packages/host-service/src/terminal-agents/types.ts index 1bbac7e56bb..3a88dbef9a0 100644 --- a/packages/host-service/src/terminal-agents/types.ts +++ b/packages/host-service/src/terminal-agents/types.ts @@ -51,6 +51,8 @@ export interface TerminalSubagent { export interface TerminalAgentBinding { launchId?: string; account?: import("../trpc/router/usage/session-account/session-account").SessionAccount; + /** Non-null stored context was malformed; never resume using a default. */ + accountInvalid?: true; terminalId: string; workspaceId: string; agentId: TerminalAgentId; diff --git a/packages/host-service/src/terminal/fresh-admission.test.ts b/packages/host-service/src/terminal/fresh-admission.test.ts new file mode 100644 index 00000000000..4d4b475fbca --- /dev/null +++ b/packages/host-service/src/terminal/fresh-admission.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from "bun:test"; +import { + invalidateFreshAdmission, + readFreshAdmission, + registerFreshAdmission, +} from "./fresh-admission"; + +test("only an owned fresh, complete, untouched terminal stream admits attachment", () => { + const session = {}; + let data: Uint8Array | null = new Uint8Array([1, 2]); + expect(readFreshAdmission(session, "terminal", "workspace")).toBeNull(); + registerFreshAdmission(session, { + terminalId: "terminal", + workspaceId: "workspace", + read: () => data, + }); + expect(readFreshAdmission(session, "terminal", "other")).toBeNull(); + const result = readFreshAdmission(session, "terminal", "workspace"); + expect(result).toEqual(data); + expect(result).not.toBe(data); + data = new Uint8Array(16 * 1024 + 1); + expect(readFreshAdmission(session, "terminal", "workspace")).toBeNull(); + data = new Uint8Array([3]); + invalidateFreshAdmission(session); + expect(readFreshAdmission(session, "terminal", "workspace")).toBeNull(); +}); diff --git a/packages/host-service/src/terminal/fresh-admission.ts b/packages/host-service/src/terminal/fresh-admission.ts new file mode 100644 index 00000000000..a4fbf35342f --- /dev/null +++ b/packages/host-service/src/terminal/fresh-admission.ts @@ -0,0 +1,34 @@ +const MAX_ADMISSION_BYTES = 16 * 1024; +const admissions = new WeakMap< + object, + { terminalId: string; workspaceId: string; read(): Uint8Array | null } +>(); + +export function registerFreshAdmission( + session: object, + value: { terminalId: string; workspaceId: string; read(): Uint8Array | null }, +): void { + admissions.set(session, value); +} + +export function invalidateFreshAdmission(session: object): void { + admissions.delete(session); +} + +export function readFreshAdmission( + session: object, + terminalId: string, + workspaceId: string, +): Uint8Array | null { + const entry = admissions.get(session); + if ( + !entry || + entry.terminalId !== terminalId || + entry.workspaceId !== workspaceId + ) + return null; + const data = entry.read(); + return data && data.byteLength > 0 && data.byteLength <= MAX_ADMISSION_BYTES + ? data.slice() + : null; +} diff --git a/packages/host-service/src/terminal/terminal.initial-command.node-test.ts b/packages/host-service/src/terminal/terminal.initial-command.node-test.ts index 66307646a2b..47872ffff39 100644 --- a/packages/host-service/src/terminal/terminal.initial-command.node-test.ts +++ b/packages/host-service/src/terminal/terminal.initial-command.node-test.ts @@ -20,13 +20,17 @@ import { after, before, describe, test } from "node:test"; import { fileURLToPath } from "node:url"; import { Server } from "@superset/pty-daemon"; import { createDb, type HostDb } from "../db/index.ts"; -import { projects, workspaces } from "../db/schema.ts"; -import { disposeDaemonClient } from "./daemon-client-singleton.ts"; +import { projects, terminalSessions, workspaces } from "../db/schema.ts"; +import { + disposeDaemonClient, + getDaemonClient, +} from "./daemon-client-singleton.ts"; import { initTerminalBaseEnv } from "./env.ts"; import { __resetSessionsForTesting, createTerminalSessionInternal, disposeSessionAndWait, + listTerminalSessions, snapshotSession, } from "./terminal.ts"; import { __setAccountShellForTesting } from "./user-shell.ts"; @@ -91,6 +95,236 @@ after(async () => { }); describe("initialCommand delivery", () => { + test("a recovery guard runs after shell setup and prevents refused commands", async () => { + const terminalId = `e2e-guard-${randomUUID().slice(0, 8)}`; + const sentinel = path.join(TEST_HOME, `guard-ran-${terminalId}`); + let guarded = false; + try { + await assert.rejects( + createTerminalSessionInternal({ + terminalId, + workspaceId, + db, + initialCommand: `echo ran > "${sentinel}"`, + beforeInitialCommand: async () => { + guarded = true; + assert.ok( + db.query.terminalSessions + .findFirst({ + where: (table, { eq }) => eq(table.id, terminalId), + }) + .sync(), + ); + throw new Error("saved identity changed"); + }, + }), + /saved identity changed/, + ); + assert.equal(guarded, true); + assert.equal(fs.existsSync(sentinel), false); + } finally { + await disposeSessionAndWait(terminalId, db); + } + }); + + test("a refused new launch closes only its never-launched target shell", async () => { + const sourceId = `e2e-source-${randomUUID().slice(0, 8)}`; + const targetId = `e2e-refused-${randomUUID().slice(0, 8)}`; + const source = await createTerminalSessionInternal({ + terminalId: sourceId, + workspaceId, + db, + }); + assert.ok(!("error" in source)); + try { + await assert.rejects( + createTerminalSessionInternal({ + terminalId: targetId, + workspaceId, + db, + initialCommand: "echo must-not-launch", + beforeInitialCommand: async () => { + throw new Error("fixture identity changed"); + }, + }), + /fixture identity changed/, + ); + assert.equal( + listTerminalSessions().some( + (session) => session.terminalId === targetId, + ), + false, + ); + assert.equal( + listTerminalSessions().some( + (session) => session.terminalId === sourceId && !session.exited, + ), + true, + ); + const daemonSessions = await (await getDaemonClient()).list(); + assert.equal( + daemonSessions.some((session) => session.id === targetId), + false, + ); + assert.equal( + daemonSessions.some((session) => session.id === sourceId), + true, + ); + assert.equal( + db.query.terminalSessions + .findFirst({ where: (table, { eq }) => eq(table.id, targetId) }) + .sync()?.status, + "disposed", + ); + } finally { + await disposeSessionAndWait(targetId, db); + await disposeSessionAndWait(sourceId, db); + } + }); + + test("a guard rejection keeps an already-existing user shell alive", async () => { + const sourceId = `e2e-existing-${randomUUID().slice(0, 8)}`; + const source = await createTerminalSessionInternal({ + terminalId: sourceId, + workspaceId, + db, + }); + assert.ok(!("error" in source)); + try { + await assert.rejects( + createTerminalSessionInternal({ + terminalId: sourceId, + workspaceId, + db, + initialCommand: "echo must-not-launch", + beforeInitialCommand: async () => { + throw new Error("fixture identity changed"); + }, + }), + /fixture identity changed/, + ); + assert.equal( + listTerminalSessions().some( + (session) => session.terminalId === sourceId && !session.exited, + ), + true, + ); + assert.equal( + (await (await getDaemonClient()).list()).some( + (session) => session.id === sourceId, + ), + true, + ); + } finally { + await disposeSessionAndWait(sourceId, db); + } + }); + + test("a guard rejection preserves a cold-restored existing terminal record", async () => { + const terminalId = `e2e-restored-${randomUUID().slice(0, 8)}`; + db.insert(terminalSessions) + .values({ + id: terminalId, + originWorkspaceId: workspaceId, + createdAt: Date.now(), + status: "active", + }) + .run(); + try { + await assert.rejects( + createTerminalSessionInternal({ + terminalId, + workspaceId, + db, + initialCommand: "echo must-not-launch", + beforeInitialCommand: async () => { + throw new Error("fixture identity changed"); + }, + }), + /fixture identity changed/, + ); + assert.equal( + listTerminalSessions().some( + (session) => session.terminalId === terminalId && !session.exited, + ), + true, + ); + assert.equal( + (await (await getDaemonClient()).list()).some( + (session) => session.id === terminalId, + ), + true, + ); + assert.equal( + db.query.terminalSessions + .findFirst({ where: (table, { eq }) => eq(table.id, terminalId) }) + .sync()?.status, + "active", + ); + } finally { + await disposeSessionAndWait(terminalId, db); + } + }); + + test("a passing recovery guard authorizes one initial command", async () => { + const terminalId = `e2e-guard-pass-${randomUUID().slice(0, 8)}`; + const sentinel = path.join(TEST_HOME, `guard-pass-${terminalId}`); + let guarded = 0; + try { + const session = await createTerminalSessionInternal({ + terminalId, + workspaceId, + db, + initialCommand: `echo ran > "${sentinel}"`, + beforeInitialCommand: async () => { + guarded++; + }, + }); + assert.ok(!("error" in session)); + await waitFor(() => fs.existsSync(sentinel), 5000); + assert.equal(guarded, 1); + assert.equal(fs.readFileSync(sentinel, "utf8"), "ran\n"); + } finally { + await disposeSessionAndWait(terminalId, db); + } + }); + + test("an exited fixture shell cannot authorize a saved-conversation launch", async () => { + const terminalId = `e2e-guard-exit-${randomUUID().slice(0, 8)}`; + const sentinel = path.join(TEST_HOME, `guard-exit-${terminalId}`); + let authorized = false; + try { + await assert.rejects( + createTerminalSessionInternal({ + terminalId, + workspaceId, + db, + initialCommand: `echo ran > "${sentinel}"`, + beforeInitialCommand: async () => { + await (await getDaemonClient()).close(terminalId, "SIGHUP"); + await waitFor( + () => + db.query.terminalSessions + .findFirst({ + where: (table, { eq }) => eq(table.id, terminalId), + }) + .sync()?.status === "exited", + 5000, + ); + }, + onInitialCommandReady: () => { + authorized = true; + }, + }), + /new terminal exited/, + ); + assert.equal(authorized, false); + assert.equal(fs.existsSync(sentinel), false); + } finally { + await disposeSessionAndWait(terminalId, db); + } + }); + test("a >2KB initialCommand executes fully (no MAX_CANON truncation)", async () => { const terminalId = `e2e-longcmd-${randomUUID().slice(0, 8)}`; const outFile = path.join(TEST_HOME, `long-${terminalId}`); diff --git a/packages/host-service/src/terminal/terminal.ts b/packages/host-service/src/terminal/terminal.ts index 42a79fef6e5..81dd6f5a58c 100644 --- a/packages/host-service/src/terminal/terminal.ts +++ b/packages/host-service/src/terminal/terminal.ts @@ -70,6 +70,11 @@ import { shellLaunchExpectsReadyMarker, waitForTerminalBaseEnv, } from "./env.ts"; +import { + invalidateFreshAdmission, + readFreshAdmission, + registerFreshAdmission, +} from "./fresh-admission"; import { TerminalLifecycleOperations, terminalLifecycleState, @@ -1017,6 +1022,17 @@ export async function listLiveTerminalSessions( return merged; } +/** Only initial, unreplayed output from a new untouched terminal can admit a native attachment. */ +export function readFreshTerminalAdmission(input: { + terminalId: string; + workspaceId: string; +}): Uint8Array | null { + const session = sessions.get(input.terminalId); + if (!session || session.exited || session.workspaceId !== input.workspaceId) + return null; + return readFreshAdmission(session, input.terminalId, input.workspaceId); +} + export function writeInputToSession({ terminalId, workspaceId, @@ -1040,6 +1056,7 @@ export function writeInputToSession({ return { kind: "SESSION_EXITED", error: "Terminal session has exited" }; } + invalidateFreshAdmission(session); session.pty.write(data); return { success: true }; } @@ -1277,8 +1294,10 @@ async function writeSessionMessage( agent || session.modeTracker.isBracketedPasteActive() ? `\x1b[200~${message}\x1b[201~` : message; - const write = (data: string) => - agent ? session.pty.writeOrThrow(data) : session.pty.write(data); + const write = (data: string) => { + invalidateFreshAdmission(session); + return agent ? session.pty.writeOrThrow(data) : session.pty.write(data); + }; let inputStaged: true | undefined; try { if (!submit) { @@ -2914,6 +2933,10 @@ interface CreateTerminalSessionOptions { db: HostDb; eventBus?: EventBus; initialCommand?: string; + /** Internal recovery guard, after terminal setup and before command queueing. */ + beforeInitialCommand?: () => Promise; + /** Synchronous authorization after the guard and final liveness check. */ + onInitialCommandReady?: () => void; cwd?: string; /** Hidden sessions are process-internal and should not appear in user pickers. */ listed?: boolean; @@ -2929,6 +2952,27 @@ interface CreateTerminalSessionOptions { restoredNotice?: boolean; } +async function authorizeGuardedInitialCommand( + session: TerminalSession, + guard: () => Promise, + authorize?: () => void, +): Promise { + const assertLive = () => { + if ( + !isCurrentLiveSession(session) || + session.shellReadyState === "cancelled" + ) + throw new Error( + "The new terminal exited before the saved conversation could be resumed. Nothing was launched.", + ); + }; + await session.shellReadyPromise; + assertLive(); + await guard(); + assertLive(); + authorize?.(); +} + function resolveTerminalCwd( cwdOverride: string | undefined, worktreePath: string, @@ -3002,6 +3046,8 @@ async function createTerminalSessionUnlocked({ db, eventBus, initialCommand, + beforeInitialCommand, + onInitialCommandReady, cwd: cwdOverride, listed = true, cols: requestedCols, @@ -3032,7 +3078,16 @@ async function createTerminalSessionUnlocked({ return { kind: "SESSION_WRONG_WORKSPACE", error: mismatchError }; if (listed) existing.listed = true; - if (initialCommand) queueInitialCommand(existing, initialCommand); + if (initialCommand) { + if (beforeInitialCommand && !existing.initialCommandQueued) { + await authorizeGuardedInitialCommand( + existing, + beforeInitialCommand, + onInitialCommandReady, + ); + } + queueInitialCommand(existing, initialCommand); + } return existing; } @@ -3343,6 +3398,15 @@ async function createTerminalSessionUnlocked({ }; reclaimSession = session; sessions.set(terminalId, session); + if (!isAdopted) + registerFreshAdmission(session, { + terminalId, + workspaceId, + read: () => + session.retainedStartSeq === 0 && session.outputSeq <= 16 * 1024 + ? readRetainedFrom(session, 0) + : null, + }); portManager.upsertSession(terminalId, workspaceId, pty.pid); if (session.shellReadyState === "pending") { @@ -3494,6 +3558,37 @@ async function createTerminalSessionUnlocked({ : Promise.resolve(); if (initialCommand) { + if (beforeInitialCommand && !session.initialCommandQueued) { + try { + await authorizeGuardedInitialCommand( + session, + beforeInitialCommand, + onInitialCommandReady, + ); + } catch (error) { + // This invocation owns only a fresh, never-launched target. Existing + // records and adopted shells belong to the user and must survive. + if ( + !record && + !isAdopted && + sessions.get(terminalId) === session && + !session.initialCommandQueued + ) { + db.update(terminalSessions) + .set({ disposeRequestedAt: Date.now() }) + .where(eq(terminalSessions.id, terminalId)) + .run(); + // Already under this terminal's lifecycle lock: do not reacquire it. + const disposed = await disposeSessionUnlocked(terminalId, db); + if (!disposed.daemonCloseSucceeded) + console.warn( + "[terminal] refused launch target could not be closed", + { terminalId }, + ); + } + throw error; + } + } queueInitialCommand(session, initialCommand); } @@ -3844,6 +3939,7 @@ export function registerWorkspaceTerminalRoute({ } if (message.type === "input") { + invalidateFreshAdmission(session); session.pty.write(message.data); return; } diff --git a/packages/host-service/src/trpc/router/agents/account-auth-routing.test.ts b/packages/host-service/src/trpc/router/agents/account-auth-routing.test.ts new file mode 100644 index 00000000000..d0f3b745d56 --- /dev/null +++ b/packages/host-service/src/trpc/router/agents/account-auth-routing.test.ts @@ -0,0 +1,268 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import type { SessionAccount } from "../usage/session-account/session-account"; +import { validateAccountAuthRouting } from "./account-auth-routing"; + +describe("explicit account authentication routing", () => { + let root: string; + let cwd: string; + let account: SessionAccount & { directory: string }; + let options: Required< + NonNullable[2]> + >; + async function put(path: string, content: string) { + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, content); + } + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "superset-account-routing-")); + cwd = join(root, "home", "project"); + await mkdir(join(cwd, ".git"), { recursive: true }); + account = { + agent: "claude", + selection: join(root, "home", ".claude-work"), + directory: join(root, "home", ".claude-work"), + identity: "test-account", + credentialKind: "subscription", + pinned: true, + }; + options = { + homeDir: join(root, "home"), + os: "linux", + systemDir: join(root, "system"), + managedPreferencesDir: join(root, "managed"), + username: "test-user", + }; + }); + afterEach(async () => { + await rm(root, { recursive: true, force: true }); + }); + + test("accepts absent files and ordinary Claude model, hook and permission settings", async () => { + await expect( + validateAccountAuthRouting(account, cwd, options), + ).resolves.toBeUndefined(); + await put( + join(account.directory, "settings.json"), + JSON.stringify({ + model: "sonnet", + hooks: {}, + permissions: { deny: ["Read(.env)"] }, + env: { API_TIMEOUT_MS: "30000" }, + }), + ); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).resolves.toBeUndefined(); + }); + + test.each([ + { apiKeyHelper: "read-test-key" }, + { forceLoginMethod: "console" }, + { forceLoginMethod: "gateway" }, + { forceLoginOrgUUID: "other-org" }, + { env: { ANTHROPIC_AUTH_TOKEN: "test-token" } }, + { env: { ANTHROPIC_CUSTOM_HEADERS: "Authorization: test-token" } }, + { env: { CLAUDE_CONFIG_DIR: "/other-profile" } }, + { env: { HOME: "/other-home" } }, + { env: { USER: "other-keychain-account" } }, + ])("rejects profile credential routing: %j", async (settings) => { + await put( + join(account.directory, "settings.json"), + JSON.stringify(settings), + ); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }); + }); + + test("rejects workspace settings and main-worktree local settings", async () => { + await put( + join(cwd, ".claude", "settings.json"), + '{"apiKeyHelper":"test-helper"}', + ); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("Nothing was launched"); + await rm(join(cwd, ".claude"), { recursive: true }); + await rm(join(cwd, ".git"), { recursive: true }); + const main = join(root, "main"); + const gitDir = join(main, ".git", "worktrees", "checkout"); + await put(join(cwd, ".git"), `gitdir: ${gitDir}\n`); + await put(join(gitDir, "commondir"), "../..\n"); + await put( + join(main, ".claude", "settings.local.json"), + '{"env":{"ANTHROPIC_API_KEY":"test-key"}}', + ); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("Nothing was launched"); + }); + + test("does not confuse the unselected system profile with project settings", async () => { + await put( + join(root, "home", ".claude", "settings.json"), + '{"apiKeyHelper":"other-profile-helper"}', + ); + await rm(join(cwd, ".git"), { recursive: true }); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).resolves.toBeUndefined(); + }); + + test("rejects credential routing from managed drop-ins without running helpers", async () => { + await put( + join(options.systemDir, "managed-settings.d", "20-auth.json"), + '{"policyHelper":"should-not-execute"}', + ); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("Nothing was launched"); + }); + + test("fails closed on unparsed macOS managed policy", async () => { + await put( + join(options.managedPreferencesDir, "com.anthropic.claudecode.plist"), + "policy", + ); + await expect( + validateAccountAuthRouting(account, cwd, { ...options, os: "darwin" }), + ).rejects.toThrow("managed authentication policy"); + }); + + test("refuses an inconclusive managed preference probe", async () => { + await put(options.managedPreferencesDir, "not a directory"); + await expect( + validateAccountAuthRouting(account, cwd, { ...options, os: "darwin" }), + ).rejects.toThrow("managed authentication policy"); + }); + + test.each([ + "claude", + "codex", + ] as const)("accepts ordinary macOS %s preferences but refuses managed preferences", async (agent) => { + account = { ...account, agent }; + const domain = + agent === "claude" ? "com.anthropic.claudecode" : "com.openai.codex"; + await put( + join(options.homeDir, "Library/Preferences", `${domain}.plist`), + "ordinary preferences", + ); + const macOptions = { ...options, os: "darwin" as const }; + await expect( + validateAccountAuthRouting(account, cwd, macOptions), + ).resolves.toBeUndefined(); + await put( + join(options.managedPreferencesDir, options.username, `${domain}.plist`), + "managed preferences", + ); + await expect( + validateAccountAuthRouting(account, cwd, macOptions), + ).rejects.toThrow("managed authentication policy"); + }); + + test("accepts ordinary Codex configuration with real TOML syntax", async () => { + account = { ...account, agent: "codex" }; + await put( + join(account.directory, "config.toml"), + ` +model = 'gpt-test' +model_provider = 'openai' +forced_login_method = 'chatgpt' +cli_auth_credentials_store = 'file' +[mcp_servers.local] +command = 'node' +args = ['server.js'] +[projects.'/some/project'] +trust_level = 'trusted' +`, + ); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).resolves.toBeUndefined(); + }); + + test.each([ + 'model_provider = "custom"', + '"model_providers" = { custom = { env_key = "OTHER_KEY" } }', + '[model_providers.custom]\nexperimental_bearer_token = "test-token"', + 'profile = "work"', + 'forced_login_method = "api"', + 'cli_auth_credentials_store = "keyring"', + 'chatgpt_base_url = "https://example.test"', + ])("rejects Codex alternate authentication: %s", async (config) => { + account = { ...account, agent: "codex" }; + await put(join(account.directory, "config.toml"), config); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("Codex authentication"); + }); + + test("rejects Codex system requirements selecting a different credential store", async () => { + account = { ...account, agent: "codex" }; + await put( + join(options.systemDir, "requirements.toml"), + 'cli_auth_credentials_store = "auto"', + ); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("Codex authentication"); + }); + + test("rejects malformed JSON and TOML without echoing their contents", async () => { + for (const agent of ["claude", "codex"] as const) { + const filename = agent === "claude" ? "settings.json" : "config.toml"; + await put( + join(account.directory, filename), + "invalid-secret-test-value = {", + ); + let error: unknown; + try { + await validateAccountAuthRouting({ ...account, agent }, cwd, options); + } catch (caught) { + error = caught; + } + expect(error).toMatchObject({ code: "PRECONDITION_FAILED" }); + expect(String(error)).not.toContain("invalid-secret-test-value"); + } + }); + + test("bounds config reads and rejects non-file settings", async () => { + const file = join(account.directory, "settings.json"); + await put(file, " ".repeat(2 * 1024 * 1024 + 1)); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("configuration file"); + await rm(file); + await mkdir(file); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("configuration file"); + }); + + test("checks symlinked settings at their destination", async () => { + const actual = join(root, "dotfiles", "settings.json"); + await put(actual, '{"apiKeyHelper":"test-helper"}'); + await mkdir(account.directory, { recursive: true }); + await symlink(actual, join(account.directory, "settings.json")); + await expect( + validateAccountAuthRouting(account, cwd, options), + ).rejects.toThrow("Nothing was launched"); + }); + + test("checks the real project ancestors when the working folder is a symlink", async () => { + const nested = join(cwd, "packages", "app"); + await mkdir(nested, { recursive: true }); + const alias = join(root, "shortcut"); + await symlink(nested, alias); + await put( + join(cwd, ".claude", "settings.json"), + '{"apiKeyHelper":"parent-project-helper"}', + ); + await expect( + validateAccountAuthRouting(account, alias, options), + ).rejects.toThrow("Nothing was launched"); + }); +}); diff --git a/packages/host-service/src/trpc/router/agents/account-auth-routing.ts b/packages/host-service/src/trpc/router/agents/account-auth-routing.ts new file mode 100644 index 00000000000..3b733035c1f --- /dev/null +++ b/packages/host-service/src/trpc/router/agents/account-auth-routing.ts @@ -0,0 +1,302 @@ +import { constants, type Stats } from "node:fs"; +import { + type FileHandle, + lstat, + open, + readdir, + realpath, +} from "node:fs/promises"; +import { homedir, platform, userInfo } from "node:os"; +import { basename, dirname, isAbsolute, join, resolve } from "node:path"; +import { TRPCError } from "@trpc/server"; +import { parse as parseToml } from "smol-toml"; +import type { SessionAccount } from "../usage/session-account/session-account"; + +const MAX_CONFIG_BYTES = 2 * 1024 * 1024; +const MAX_ANCESTORS = 64; +const MAX_MANAGED_FILES = 64; + +// Settings can reintroduce these after env -u. Do not override organization +// policy or execute credential helpers to make an account selection succeed. +// https://code.claude.com/docs/en/env-vars +const CLAUDE_AUTH_ENV = new Set([ + "HOME", + "USER", + "LOGNAME", + "XDG_CONFIG_HOME", + "CLAUDE_CONFIG_DIR", + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "ANTHROPIC_CUSTOM_HEADERS", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", + "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + "CLAUDE_CODE_USE_ANTHROPIC_AWS", + "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", +]); +const CLAUDE_AUTH_SETTINGS = [ + "apiKeyHelper", + "awsAuthRefresh", + "awsCredentialExport", + "forceLoginOrgUUID", + "forceLoginGatewayUrl", + "gatewayInternalNetworks", + "policyHelper", +]; +const CODEX_AUTH_SETTINGS = [ + "model_providers", + "profile", + "profiles", + "openai_base_url", + "chatgpt_base_url", + "forced_chatgpt_workspace_id", +]; + +function refuse(detail: string): never { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: `Account selection cannot verify ${detail}. Use the agent's configured launch or resolve its authentication settings first. Nothing was launched.`, + }); +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isMissing(error: unknown): boolean { + return isObject(error) && error.code === "ENOENT"; +} + +async function readConfig(path: string): Promise { + let file: FileHandle | undefined; + try { + // Nonblocking open also lets us reject a FIFO without waiting for a writer. + file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK); + const info = await file.stat(); + if (!info.isFile() || info.size > MAX_CONFIG_BYTES) + refuse("a configuration file"); + const buffer = Buffer.alloc(MAX_CONFIG_BYTES + 1); + let total = 0; + while (total < buffer.length) { + const { bytesRead } = await file.read( + buffer, + total, + buffer.length - total, + total, + ); + if (bytesRead === 0) break; + total += bytesRead; + } + if (total > MAX_CONFIG_BYTES) refuse("a configuration file"); + return buffer.toString("utf8", 0, total); + } catch (error) { + if (isMissing(error)) return undefined; + // Parser and OS errors may contain credentials or entire config lines. + refuse("a configuration file"); + } finally { + await file?.close(); + } +} + +async function validateFile( + path: string, + format: "json" | "toml", +): Promise { + const text = await readConfig(path); + if (text === undefined) return; + let config: unknown; + try { + config = format === "json" ? JSON.parse(text) : parseToml(text); + } catch { + refuse("a configuration file"); + } + if (!isObject(config)) refuse("a configuration file"); + if (format === "json") { + if ( + CLAUDE_AUTH_SETTINGS.some( + (key) => config[key] !== undefined && config[key] !== null, + ) + ) { + refuse("the Claude authentication configuration"); + } + if ( + config.forceLoginMethod !== undefined && + config.forceLoginMethod !== "claudeai" + ) { + refuse("the Claude login method"); + } + if (config.env !== undefined) { + if (!isObject(config.env)) refuse("the Claude environment settings"); + if ( + Object.keys(config.env).some( + (key) => + CLAUDE_AUTH_ENV.has(key) || key.startsWith("CLAUDE_CODE_USE_"), + ) + ) { + refuse("the Claude authentication environment"); + } + } + } else { + // Reject alternate profiles/providers instead of trying to merge their + // authentication precedence. Ordinary model, MCP and approval settings remain. + // https://developers.openai.com/codex/config-reference + if ( + CODEX_AUTH_SETTINGS.some((key) => config[key] !== undefined) || + (config.model_provider !== undefined && + config.model_provider !== "openai") || + (config.forced_login_method !== undefined && + config.forced_login_method !== "chatgpt") || + (config.cli_auth_credentials_store !== undefined && + config.cli_auth_credentials_store !== "file") + ) { + refuse("the Codex authentication configuration"); + } + } +} + +async function projectDirectories( + cwd: string, + home: string, +): Promise> { + const dirs = new Set(); + let start: string; + let homeDirectory: string; + try { + // A launched process resolves the physical cwd. Checking only the + // symlink's parents can miss project settings in its actual checkout. + start = await realpath(cwd); + homeDirectory = await realpath(home); + } catch { + refuse("the project settings locations"); + } + let current = start; + for (let depth = 0; depth < MAX_ANCESTORS; depth++) { + // The unselected system profile is not project configuration. Stop at + // the home boundary unless the user actually launched in that folder. + if (current === homeDirectory && current !== start) return dirs; + dirs.add(current); + const gitEntry = join(current, ".git"); + let info: Stats | undefined; + try { + info = await lstat(gitEntry); + } catch (error) { + if (!isMissing(error)) refuse("the project settings locations"); + } + if (info?.isSymbolicLink()) refuse("the worktree settings locations"); + if (info?.isFile()) { + const pointer = await readConfig(gitEntry); + if (!pointer?.startsWith("gitdir: ")) + refuse("the worktree settings locations"); + const gitDir = resolve(current, pointer.slice(8).trim()); + const common = await readConfig(join(gitDir, "commondir")); + if (common !== undefined) { + const commonDir = resolve(gitDir, common.trim()); + if (basename(commonDir) !== ".git") + refuse("the worktree settings locations"); + dirs.add(dirname(commonDir)); + } + } + if (info) return dirs; + if (dirname(current) === current) return dirs; + current = dirname(current); + } + refuse("the project settings locations"); +} + +interface RoutingOptions { + /** Explicit locations keep synthetic tests away from real provider profiles. */ + homeDir?: string; + os?: NodeJS.Platform; + username?: string; + systemDir?: string; + managedPreferencesDir?: string; +} + +async function refuseUnparsedPolicy(path: string): Promise { + try { + await lstat(path); + } catch (error) { + if (isMissing(error)) return; + refuse("managed authentication policy"); + } + refuse("managed authentication policy"); +} + +/** + * Local preflight only: checks known configuration sources without executing + * helpers, changing policy, or claiming live authentication. Server-delivered + * policy and later settings edits remain controlled by the provider itself. + * https://code.claude.com/docs/en/settings + * https://code.claude.com/docs/en/managed-settings + */ +export async function validateAccountAuthRouting( + account: SessionAccount, + cwd: string, + options: RoutingOptions = {}, +): Promise { + if ( + !account.directory || + !isAbsolute(account.directory) || + !isAbsolute(cwd) + ) { + refuse("the selected profile location"); + } + const os = options.os ?? platform(); + if (os !== "darwin" && os !== "linux") + refuse("this platform's authentication policy"); + const home = options.homeDir ?? homedir(); + const roots = await projectDirectories(cwd, home); + const files = new Set(); + if (account.agent === "claude") { + files.add(join(account.directory, "settings.json")); + for (const root of roots) { + files.add(join(root, ".claude", "settings.json")); + files.add(join(root, ".claude", "settings.local.json")); + } + const systemDir = + options.systemDir ?? + (os === "darwin" + ? "/Library/Application Support/ClaudeCode" + : "/etc/claude-code"); + files.add(join(systemDir, "managed-settings.json")); + let entries: string[]; + try { + entries = await readdir(join(systemDir, "managed-settings.d")); + } catch (error) { + if (!isMissing(error)) refuse("managed authentication policy"); + entries = []; + } + if (entries.length > MAX_MANAGED_FILES) + refuse("managed authentication policy"); + for (const entry of entries) { + if (!entry.startsWith(".") && entry.endsWith(".json")) { + files.add(join(systemDir, "managed-settings.d", entry)); + } + } + } else { + files.add(join(account.directory, "config.toml")); + for (const root of roots) files.add(join(root, ".codex", "config.toml")); + const systemDir = options.systemDir ?? "/etc/codex"; + files.add(join(systemDir, "config.toml")); + files.add(join(systemDir, "requirements.toml")); + files.add(join(systemDir, "managed_config.toml")); + files.add(join(account.directory, "managed_config.toml")); + } + if (os === "darwin") { + const domain = + account.agent === "claude" + ? "com.anthropic.claudecode" + : "com.openai.codex"; + const managed = + options.managedPreferencesDir ?? "/Library/Managed Preferences"; + const username = options.username ?? userInfo().username; + await refuseUnparsedPolicy(join(managed, `${domain}.plist`)); + await refuseUnparsedPolicy(join(managed, username, `${domain}.plist`)); + } + for (const file of files) + await validateFile(file, account.agent === "claude" ? "json" : "toml"); +} diff --git a/packages/host-service/src/trpc/router/agents/agents.test.ts b/packages/host-service/src/trpc/router/agents/agents.test.ts index 5e200489578..4ca6448befc 100644 --- a/packages/host-service/src/trpc/router/agents/agents.test.ts +++ b/packages/host-service/src/trpc/router/agents/agents.test.ts @@ -9,7 +9,10 @@ import { drizzle } from "drizzle-orm/bun-sqlite"; import { migrate } from "drizzle-orm/bun-sqlite/migrator"; import type { HostDb } from "../../../db"; import * as schema from "../../../db/schema"; -import { TerminalAgentStore } from "../../../terminal-agents"; +import { + SqliteTerminalAgentBindingPersistence, + TerminalAgentStore, +} from "../../../terminal-agents"; import { claudeProjectDirName } from "../../../terminal-agents/harness-sessions/claude"; import { setDefaultAccountSelection } from "../usage/default-account"; import { @@ -18,6 +21,7 @@ import { buildTerminalAgentLaunch, chatContinuationTarget, chatLaunchTarget, + commitTerminalAgentLaunch, continuationTarget, validateAgentEffortSelection, validateAgentForkSelection, @@ -843,6 +847,111 @@ describe("bindResumedSession", () => { const WORKSPACE_ID = "11111111-1111-1111-1111-111111111111"; const TERMINAL_ID = "22222222-2222-2222-2222-222222222222"; + it("a rejected launch authorization rolls back both durable and in-memory bindings", () => { + const db = createTestDb(); + seedCodexConfig(db); + const store = new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ); + const input = { + workspaceId: WORKSPACE_ID, + agent: "codex", + prompt: "", + resumeSessionId: "requested-session", + terminalLaunch: { + terminalId: TERMINAL_ID, + beforeInitialCommand: async () => {}, + onInitialCommandReady: () => { + throw new Error("history changed"); + }, + }, + }; + expect(() => + commitTerminalAgentLaunch( + { db, terminalAgentStore: store }, + input, + TERMINAL_ID, + ), + ).toThrow("history changed"); + expect(store.get(TERMINAL_ID)).toBeUndefined(); + expect(store.getProvenance(TERMINAL_ID)).toBeUndefined(); + expect(db.select().from(schema.terminalAgentBindings).all()).toEqual([]); + }); + + it("refuses pinned recovery when an early native ID conflicts before account metadata arrives", () => { + const db = createTestDb(); + seedCodexConfig(db); + const store = new TerminalAgentStore(); + store.recordEvent({ + terminalId: TERMINAL_ID, + workspaceId: WORKSPACE_ID, + agentId: "codex", + agentSessionId: "observed-session", + eventType: "SessionStart", + occurredAt: 1, + }); + bindResumedSession( + { db, terminalAgentStore: store }, + { + workspaceId: WORKSPACE_ID, + agent: "codex", + prompt: "", + resumeSessionId: "requested-session", + account: { + agent: "codex", + selection: "/selected", + directory: "/selected", + credentialKind: "subscription", + identity: "a".repeat(64), + pinned: true, + }, + }, + TERMINAL_ID, + ); + expect(store.get(TERMINAL_ID)?.agentSessionId).toBe("observed-session"); + expect(store.get(TERMINAL_ID)?.account?.conflict).toBe(true); + }); + + for (const matching of [true, false]) { + it(`preserves early hook identity and ${matching ? "pins a matching account" : "blocks a conflicting account"}`, () => { + const db = createTestDb(); + seedCodexConfig(db); + const store = new TerminalAgentStore(); + const account = { + agent: "codex" as const, + selection: "/selected", + directory: "/selected", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + pinned: true as const, + }; + store.recordEvent({ + terminalId: TERMINAL_ID, + workspaceId: WORKSPACE_ID, + agentId: "codex", + agentSessionId: "native-first", + eventType: "Attached", + occurredAt: 1, + account: { + ...account, + identity: matching ? account.identity : "other", + }, + }); + bindResumedSession( + { db, terminalAgentStore: store }, + { workspaceId: WORKSPACE_ID, agent: "codex", prompt: "", account }, + TERMINAL_ID, + ); + expect(store.get(TERMINAL_ID)?.agentSessionId).toBe("native-first"); + expect(String(store.get(TERMINAL_ID)?.definitionId)).toBe( + "00000000-0000-0000-0000-00000000000c", + ); + expect(store.get(TERMINAL_ID)?.account).toEqual( + matching ? account : { ...account, conflict: true }, + ); + }); + } + it("binds the resumed session id without waiting for a hook", () => { const db = createTestDb(); seedCodexConfig(db); diff --git a/packages/host-service/src/trpc/router/agents/agents.ts b/packages/host-service/src/trpc/router/agents/agents.ts index 549555e9f39..8df9ce49f3c 100644 --- a/packages/host-service/src/trpc/router/agents/agents.ts +++ b/packages/host-service/src/trpc/router/agents/agents.ts @@ -1,4 +1,7 @@ -import { isBuiltinAgentId } from "@superset/shared/agent-catalog"; +import { + type AgentDefinitionId, + isBuiltinAgentId, +} from "@superset/shared/agent-catalog"; import { FORK_SESSION_ID_TOKEN } from "@superset/shared/agent-definition"; import { buildAgentEffortArgs, @@ -45,9 +48,19 @@ import { hasHarnessSession } from "../../../terminal-agents/harness-sessions"; import type { HostServiceContext } from "../../../types"; import { protectedProcedure, router } from "../../index"; import { resolveAttachmentPath } from "../attachments/storage"; +import { prepareNativeClaudeTerminalLaunch } from "../notifications/native-claude-usage"; import { createChatSession } from "../sessions/create-chat-session"; import { toTerminalSessionError } from "../terminal/errors"; +import type { SessionAccount } from "../usage/session-account/session-account"; import { seedAgentFolderTrust } from "../workspace-creation/shared/seed-agent-trust"; +import { validateAccountAuthRouting } from "./account-auth-routing"; +import { + listLaunchAccounts, + pinnedAccountCommandPrefix, + prepareLaunchAccountHooks, + resolveLaunchAccount, + validatePinnedLaunchAccount, +} from "./launch-account"; /** * Build a shell command string that runs the resolved agent config with the @@ -133,6 +146,14 @@ function buildAttachmentBlock( } export interface AgentRunInput { + /** Internal recovery transaction; never accepted by a public input schema. */ + terminalLaunch?: { + terminalId: string; + beforeInitialCommand: () => Promise; + onInitialCommandReady: () => void; + }; + /** Internal, validated explicit selection. Public callers use runWithAccount. */ + account?: SessionAccount; colors?: TerminalColors; workspaceId: string; agent: string; @@ -458,7 +479,14 @@ export function buildTerminalAgentLaunch( ); const modelEnv = buildAgentModelEnv(launchPresetId, input.model); return { - fullCommand: `${envOverlayPrefix({ ...agentLaunchEnv(db, config), ...modelEnv })}${command}`, + fullCommand: `${ + input.account + ? pinnedAccountCommandPrefix(input.account, { + ...config.env, + ...modelEnv, + }) + : envOverlayPrefix({ ...agentLaunchEnv(db, config), ...modelEnv }) + }${command}`, label: config.label, }; } @@ -478,27 +506,79 @@ export function bindResumedSession( input: AgentRunInput, terminalId: string, ): void { - if (!input.resumeSessionId) return; - const presetId = resolveHostAgentConfig(ctx.db, input.agent)?.presetId; + if (!input.resumeSessionId && !input.account) return; + const config = resolveHostAgentConfig(ctx.db, input.agent); + const presetId = config?.presetId; if (!presetId || !isBuiltinAgentId(presetId)) return; + const observed = ctx.terminalAgentStore.get(terminalId); + let account = input.account; + if ( + account && + observed && + (observed.agentId !== account.agent || + (observed.account && + (observed.account.agent !== account.agent || + observed.account.identity !== account.identity || + observed.account.directory !== account.directory)) || + (input.resumeSessionId && + observed.agentSessionId && + input.resumeSessionId !== observed.agentSessionId)) + ) + account = { ...account, conflict: true }; ctx.terminalAgentStore.recordEvent({ terminalId, workspaceId: input.workspaceId, eventType: "Attached", agentId: presetId, - agentSessionId: input.resumeSessionId, + agentSessionId: account + ? (observed?.agentSessionId ?? input.resumeSessionId) + : input.resumeSessionId, + ...(account + ? { account, definitionId: config.id as AgentDefinitionId } + : {}), occurredAt: Date.now(), }); } +export function commitTerminalAgentLaunch( + ctx: Pick, + input: AgentRunInput, + terminalId: string, +): void { + try { + ctx.db.transaction(() => { + bindResumedSession(ctx, input, terminalId); + input.terminalLaunch?.onInitialCommandReady(); + }); + } catch (error) { + ctx.terminalAgentStore.reloadBinding(terminalId); + throw error; + } +} + async function runTerminalAgent( ctx: Pick, input: AgentRunInput, ): Promise { - const { fullCommand, label } = buildTerminalAgentLaunch(ctx.db, input); + const launch = buildTerminalAgentLaunch(ctx.db, input); + const label = launch.label; + let fullCommand = launch.fullCommand; - const terminalId = crypto.randomUUID(); + const terminalId = input.terminalLaunch?.terminalId ?? crypto.randomUUID(); + if ( + process.env.SUPERSET_NATIVE_CLAUDE_USAGE === "1" && + !input.forkSessionId + ) { + const prepared = await prepareNativeClaudeTerminalLaunch( + terminalId, + input.account, + ).catch(() => false); + if (prepared && input.resumeSessionId) + fullCommand = `${envOverlayPrefix({ + SUPERSET_NATIVE_CLAUDE_OWNED_LAUNCH: "1", + })}${fullCommand}`; + } const result = await createTerminalSessionInternal({ terminalId, workspaceId: input.workspaceId, @@ -506,13 +586,20 @@ async function runTerminalAgent( eventBus: ctx.eventBus, initialCommand: fullCommand, colors: input.colors, + ...(input.terminalLaunch + ? { + beforeInitialCommand: input.terminalLaunch.beforeInitialCommand, + onInitialCommandReady: () => + commitTerminalAgentLaunch(ctx, input, terminalId), + } + : {}), }); if ("error" in result) { throw toTerminalSessionError(result); } - bindResumedSession(ctx, input, result.terminalId); + if (!input.terminalLaunch) bindResumedSession(ctx, input, result.terminalId); return { kind: "terminal", @@ -775,6 +862,34 @@ export async function runAgentInWorkspace( ctx: HostServiceContext, input: AgentRunInput, ): Promise { + if ( + input.terminalLaunch && + (!input.account || !input.resumeSessionId || input.surface !== "terminal") + ) + throw new TRPCError({ + code: "BAD_REQUEST", + message: + "A guarded launch requires exact account-bound terminal recovery.", + }); + if (input.account) { + if ( + input.surface === "chat" || + input.continueTerminalId || + input.forkSessionId + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Explicit account selection requires a new terminal launch.", + }); + } + const config = resolveHostAgentConfig(ctx.db, input.agent); + if (!config) + throw new TRPCError({ + code: "NOT_FOUND", + message: "The selected agent is no longer available.", + }); + await validatePinnedLaunchAccount(config, input.account); + } const workspace = ctx.db.query.workspaces .findFirst({ // A tombstoned (archived) row is gone for agent launches: without @@ -795,6 +910,10 @@ export async function runAgentInWorkspace( message: `Workspace ${input.workspaceId} not found on this host — it may have been deleted.`, }); } + if (input.account) { + await validateAccountAuthRouting(input.account, workspace.worktreePath); + prepareLaunchAccountHooks(input.account); + } // Ahead of the launch path: continuing costs no pty and no trust seeding. const continued = continueChatAgent(ctx, input) ?? (await continueTerminalAgent(ctx, input)); @@ -805,7 +924,7 @@ export async function runAgentInWorkspace( // folder in the launching agent's own trust store so its first // interactive boot skips the trust dialog. Worktree workspaces inherit // trust from the main checkout and need nothing. - if (workspace.projectId === null) { + if (workspace.projectId === null && !input.account) { const config = resolveHostAgentConfig(ctx.db, input.agent); if (config) { await seedAgentFolderTrust(ctx.db, workspace.worktreePath, config); @@ -818,6 +937,60 @@ export async function runAgentInWorkspace( } export const agentsRouter = router({ + launchAccounts: protectedProcedure + .input( + z.object({ + agent: z.string().min(1), + surface: z.enum(["terminal", "chat"]).optional(), + }), + ) + .query(async ({ ctx, input }) => { + const config = resolveHostAgentConfig(ctx.db, input.agent); + if (!config) + throw new TRPCError({ + code: "NOT_FOUND", + message: "The selected agent is no longer available.", + }); + return listLaunchAccounts(config, undefined, input.surface); + }), + // Separate procedure so an older host cannot strip the selection and launch + // with its default. Explicit choices must never fall back to agents.run. + runWithAccount: protectedProcedure + .input( + z + .object({ + workspaceId: z.string().uuid(), + colors: terminalColorsSchema.optional(), + agent: z.string().min(1), + prompt: z.string().default(""), + attachmentIds: z.array(z.string().uuid()).optional(), + model: z.string().min(1).optional(), + effort: z.string().min(1).optional(), + mode: z.string().min(1).optional(), + surface: z.literal("terminal").optional(), + account: z + .object({ + selection: z.string().max(4096).nullable(), + identity: z.string().regex(/^[a-f0-9]{64}$/), + }) + .strict(), + }) + .strict(), + ) + .mutation(async ({ ctx, input }) => { + const config = resolveHostAgentConfig(ctx.db, input.agent); + if (!config) + throw new TRPCError({ + code: "NOT_FOUND", + message: "The selected agent is no longer available.", + }); + const account = await resolveLaunchAccount(config, input.account); + return runAgentInWorkspace(ctx, { + ...input, + surface: "terminal", + account, + }); + }), run: protectedProcedure .input( z.object({ diff --git a/packages/host-service/src/trpc/router/agents/launch-account.test.ts b/packages/host-service/src/trpc/router/agents/launch-account.test.ts new file mode 100644 index 00000000000..9cec6ab3052 --- /dev/null +++ b/packages/host-service/src/trpc/router/agents/launch-account.test.ts @@ -0,0 +1,380 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { writeSharedDisabledAgentIds } from "@superset/agent-setup"; +import { buildArgvCommand } from "@superset/shared/agent-prompt-launch"; +import type { ResolvedHostAgentConfig } from "../../../terminal-agents/agent-config"; +import { + readAccountIdentity, + type SessionAccount, +} from "../usage/session-account/session-account"; +import { + accountLaunchUnsupportedReason, + listLaunchAccounts, + pinnedAccountCommandPrefix, + prepareLaunchAccountHooks, + resolveLaunchAccount, + validatePinnedLaunchAccount, +} from "./launch-account"; + +const config: ResolvedHostAgentConfig = { + id: "agent", + presetId: "claude", + label: "Claude", + command: "claude", + args: [], + promptTransport: "argv" as const, + promptArgs: [], + resumeArgs: ["--resume"], + forkArgs: [], + env: {}, +}; +const account = { + agent: "claude", + selection: "/profiles/work", + directory: "/profiles/work", + identity: "a".repeat(64), + credentialKind: "subscription", + email: "work@example.test", +} satisfies SessionAccount; +const directories: string[] = []; +afterEach(async () => { + await Promise.all( + directories + .splice(0) + .map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +describe("explicit terminal account selection", () => { + test("lists subscription metadata only and does not expose API credentials", async () => { + const result = await listLaunchAccounts(config, async () => [ + account, + { ...account, credentialKind: "api_key" }, + ]); + expect(result.accounts).toEqual([ + { + selection: account.selection, + identity: account.identity, + email: account.email, + label: account.selection, + }, + ]); + }); + + test("native discovery ignores terminal-only settings and keeps subscription eligibility", async () => { + const discover = async (provider: "claude" | "codex") => { + expect(provider).toBe("claude"); + return [ + account, + { ...account, credentialKind: "api_key" as const }, + { ...account, directory: "relative" }, + ]; + }; + expect( + await listLaunchAccounts( + { ...config, args: ["--model", "fixture"] }, + discover, + ), + ).toMatchObject({ supported: false, accounts: [] }); + expect( + await listLaunchAccounts( + { ...config, args: ["--model", "fixture"] }, + discover, + "chat", + ), + ).toEqual({ + supported: true, + accounts: [ + { + selection: account.selection, + identity: account.identity, + email: account.email, + label: account.selection, + }, + ], + }); + }); + + test("rejects undiscovered paths, stale identities and terminal control characters", async () => { + const discover = async () => [account]; + await expect( + resolveLaunchAccount( + config, + { selection: "/not/discovered", identity: account.identity }, + discover, + ), + ).rejects.toThrow("no longer available"); + await expect( + resolveLaunchAccount( + config, + { selection: account.selection, identity: "changed" }, + discover, + ), + ).rejects.toThrow("no longer available"); + const unsafe = { + ...account, + selection: "/profile\ncommand", + directory: "/profile\ncommand", + }; + await expect( + resolveLaunchAccount(config, unsafe, async () => [unsafe]), + ).rejects.toThrow("no longer available"); + }); + + test("keeps explicit system selection distinct from inheriting a default", async () => { + const system = { + ...account, + selection: null, + directory: "/home/test/.claude", + }; + expect( + await resolveLaunchAccount(config, system, async () => [system]), + ).toEqual({ ...system, pinned: true }); + const prefix = pinnedAccountCommandPrefix({ ...system, pinned: true }, {}); + expect(prefix).toContain("'-u' 'CLAUDE_CONFIG_DIR'"); + expect(prefix).not.toContain("'CLAUDE_CONFIG_DIR="); + }); + + test("rejects custom commands, config flags and per-agent authentication overrides", () => { + const overrides: Partial[] = [ + { command: "custom-claude" }, + { args: ["--settings=/other/settings.json"] }, + { args: ["--resume", "old-session"] }, + { args: ["resume"] }, + { args: ["--remote", "other-server"] }, + { args: ["--oss"] }, + { args: ["-C", "/other"] }, + { args: ["--cd=/other"] }, + { args: ["-cmodel_provider=other"] }, + { promptArgs: ["--continue"] }, + { resumeArgs: ["--resume", "--settings", "/other"] }, + { env: { HOME: "/other" } }, + { env: { PATH: "/other/bin" } }, + { env: { ANTHROPIC_API_KEY: "synthetic" } }, + { env: { CLAUDE_CONFIG_DIR: "/other" } }, + ]; + for (const changed of overrides) + expect( + accountLaunchUnsupportedReason({ ...config, ...changed }), + ).toBeDefined(); + expect(accountLaunchUnsupportedReason(config)).toBeUndefined(); + }); + + test("accepts stock Claude and Codex arguments and exact native resume paths", () => { + expect( + accountLaunchUnsupportedReason({ + ...config, + args: ["--dangerously-skip-permissions"], + }), + ).toBeUndefined(); + const codex = { + ...config, + presetId: "codex", + command: "codex", + args: [ + "--dangerously-bypass-approvals-and-sandbox", + "--dangerously-bypass-hook-trust", + ], + promptArgs: ["--"], + resumeArgs: ["resume"], + }; + expect(accountLaunchUnsupportedReason(codex)).toBeUndefined(); + expect( + accountLaunchUnsupportedReason({ + ...codex, + resumeArgs: ["resume", "--config", "model_provider=other"], + }), + ).toBeDefined(); + }); + + test("validates saved profile identity again before recovery", async () => { + const dir = await mkdtemp(join(tmpdir(), "superset-launch-account-")); + directories.push(dir); + const file = join(dir, ".claude.json"); + await writeFile( + file, + JSON.stringify({ + oauthAccount: { + accountUuid: "first", + emailAddress: "first@example.test", + }, + }), + ); + const identity = await readAccountIdentity("claude", dir); + if (!identity) throw new Error("Expected fixture identity"); + const pinned = { + ...account, + ...identity, + selection: dir, + directory: dir, + pinned: true as const, + }; + await validatePinnedLaunchAccount(config, pinned, { + discover: async () => [pinned], + }); + await writeFile( + file, + JSON.stringify({ + oauthAccount: { + accountUuid: "second", + emailAddress: "second@example.test", + }, + }), + ); + await expect( + validatePinnedLaunchAccount(config, pinned, { + discover: async () => [pinned], + }), + ).rejects.toThrow("sign-in changed"); + }); + + test("refuses recovery after a hook reported conflicting account metadata", async () => { + await expect( + validatePinnedLaunchAccount( + config, + { ...account, pinned: true, conflict: true }, + { validate: async () => true }, + ), + ).rejects.toThrow("Nothing was launched"); + }); + + test("isolates command env and retains quoted paths", () => { + const pinned = { + ...account, + directory: "/profiles/space 'quote $literal", + pinned: true as const, + }; + const script = + // biome-ignore lint/suspicious/noTemplateCurlyInString: shell variable syntax + 'printf \'%s|%s|%s\' "$CLAUDE_CONFIG_DIR" "${ANTHROPIC_API_KEY-unset}" "$SUPERSET_PINNED_ACCOUNT"'; + const command = + pinnedAccountCommandPrefix(pinned, {}) + + buildArgvCommand(["bash", "-c", script]); + const result = execFileSync("bash", ["-c", command], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + CLAUDE_CONFIG_DIR: "/wrong", + ANTHROPIC_API_KEY: "synthetic", + SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR: "/wrong", + }, + }); + expect(result).toBe(`${pinned.directory}|unset|CLAUDE_CONFIG_DIR`); + }); +}); + +test("pinned Codex launch preserves the true ambient home for nested hosts", () => { + const selected = { + ...account, + agent: "codex" as const, + directory: "/profiles/codex", + selection: "/profiles/codex", + pinned: true as const, + }; + const probe = `import {resolveAmbientCodexHome} from ${JSON.stringify(resolve(import.meta.dir, "../../../../../agent-setup/src/provider-profiles.ts"))}; console.log(resolveAmbientCodexHome("/fixture-user"));`; + const command = + pinnedAccountCommandPrefix(selected, {}) + + buildArgvCommand([process.execPath, "-e", probe]); + expect( + execFileSync("/bin/sh", ["-c", command], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + CODEX_HOME: "/profiles/previous", + SUPERSET_DEFAULT_CODEX_HOME: "/profiles/previous", + SUPERSET_AMBIENT_CODEX_HOME: "/profiles/system", + }, + }).trim(), + ).toBe("/profiles/system"); +}); + +test("prepares only managed hooks in a selected profile and preserves its login and settings", async () => { + const dir = await mkdtemp(join(tmpdir(), "superset-profile-hooks-")); + directories.push(dir); + await writeFile(join(dir, ".claude.json"), '{"fixture":"login bytes"}'); + await writeFile( + join(dir, "settings.json"), + JSON.stringify({ + theme: "dark", + hooks: { Stop: [{ hooks: [{ type: "command", command: "user-hook" }] }] }, + }), + ); + prepareLaunchAccountHooks({ + ...account, + directory: dir, + selection: dir, + pinned: true, + }); + const settings = JSON.parse( + await readFile(join(dir, "settings.json"), "utf8"), + ); + expect(settings.theme).toBe("dark"); + expect( + settings.hooks.Stop.some((entry: { hooks: { command: string }[] }) => + entry.hooks.some((hook) => hook.command === "user-hook"), + ), + ).toBe(true); + expect(JSON.stringify(settings.hooks)).toContain("notify.sh"); + expect(await readFile(join(dir, ".claude.json"), "utf8")).toBe( + '{"fixture":"login bytes"}', + ); + await writeFile(join(dir, "settings.json"), "{"); + expect(() => + prepareLaunchAccountHooks({ + ...account, + directory: dir, + selection: dir, + pinned: true, + }), + ).toThrow("hooks"); + expect(await readFile(join(dir, "settings.json"), "utf8")).toBe("{"); +}); + +for (const agent of ["claude", "codex"] as const) { + test(`leaves disabled ${agent} hooks and profile bytes unchanged`, async () => { + const dir = await mkdtemp( + join(tmpdir(), "superset-disabled-profile-hooks-"), + ); + directories.push(dir); + const state = await mkdtemp( + join(tmpdir(), "superset-disabled-hooks-state-"), + ); + directories.push(state); + const originalHome = process.env.SUPERSET_HOME_DIR; + const originalDisabled = process.env.SUPERSET_DISABLED_AGENT_HOOKS; + process.env.SUPERSET_HOME_DIR = state; + delete process.env.SUPERSET_DISABLED_AGENT_HOOKS; + const filename = agent === "claude" ? "settings.json" : "config.toml"; + const contents = + agent === "claude" + ? '{"theme":"dark","hooks":{"Stop":[{"hooks":[{"type":"command","command":"user-hook"}]}]}}' + : 'model = "fixture"\n'; + await writeFile(join(dir, filename), contents); + const hookBytes = + '{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"user-hook"}]}]}}'; + if (agent === "codex") await writeFile(join(dir, "hooks.json"), hookBytes); + try { + if (agent === "claude") writeSharedDisabledAgentIds([agent]); + else process.env.SUPERSET_DISABLED_AGENT_HOOKS = agent; + prepareLaunchAccountHooks({ + ...account, + agent, + directory: dir, + selection: agent === "claude" ? null : dir, + pinned: true, + }); + expect(await readFile(join(dir, filename), "utf8")).toBe(contents); + if (agent === "codex") + expect(await readFile(join(dir, "hooks.json"), "utf8")).toBe(hookBytes); + } finally { + if (originalHome === undefined) delete process.env.SUPERSET_HOME_DIR; + else process.env.SUPERSET_HOME_DIR = originalHome; + if (originalDisabled === undefined) + delete process.env.SUPERSET_DISABLED_AGENT_HOOKS; + else process.env.SUPERSET_DISABLED_AGENT_HOOKS = originalDisabled; + } + }); +} diff --git a/packages/host-service/src/trpc/router/agents/launch-account.ts b/packages/host-service/src/trpc/router/agents/launch-account.ts new file mode 100644 index 00000000000..4e10909347c --- /dev/null +++ b/packages/host-service/src/trpc/router/agents/launch-account.ts @@ -0,0 +1,298 @@ +import { isAbsolute } from "node:path"; +import { + ensureClaudeManagedHooksAt, + ensureCodexManagedHooksAt, + resolveDisabledAgentIds, +} from "@superset/agent-setup"; +import { buildArgvCommand } from "@superset/shared/agent-prompt-launch"; +import { TRPCError } from "@trpc/server"; +import type { ResolvedHostAgentConfig } from "../../../terminal-agents/agent-config"; +import { + discoverSessionAccounts, + type SessionAccount, + validateSessionAccount, +} from "../usage/session-account/session-account"; + +export interface LaunchAccountChoice { + selection: string | null; + identity: string; +} + +const AUTH_ENV = { + claude: [ + "CLAUDE_CONFIG_DIR", + "SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR", + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "ANTHROPIC_CUSTOM_HEADERS", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", + "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + "CLAUDE_CODE_USE_ANTHROPIC_AWS", + "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", + ], + codex: [ + "CODEX_HOME", + "SUPERSET_DEFAULT_CODEX_HOME", + "OPENAI_API_KEY", + "OPENAI_BASE_URL", + "CODEX_API_KEY", + ], +} as const; + +const LAUNCH_ENV_OVERRIDES = new Set([ + "HOME", + "USER", + "LOGNAME", + "XDG_CONFIG_HOME", + "PATH", + "BASH_ENV", + "ENV", + "ZDOTDIR", +]); + +// Limit explicit selection to the stock preset flags. Arbitrary provider flags +// can change authentication, the configuration root, or the server being used. +const ACCOUNT_LAUNCH_ARGS = { + claude: new Set(["--dangerously-skip-permissions"]), + codex: new Set([ + "--dangerously-bypass-approvals-and-sandbox", + "--dangerously-bypass-hook-trust", + ]), +}; + +export function accountLaunchUnsupportedReason( + config: ResolvedHostAgentConfig, +): string | undefined { + const provider = config.presetId; + if ( + (provider !== "claude" && provider !== "codex") || + config.command !== provider + ) { + return "Account selection requires the built-in Claude or Codex command."; + } + if ( + config.promptTransport !== "argv" || + config.args.some((arg) => !ACCOUNT_LAUNCH_ARGS[provider].has(arg)) || + !( + config.promptArgs.length === 0 || + (provider === "codex" && + config.promptArgs.length === 1 && + config.promptArgs[0] === "--") + ) || + config.resumeArgs.length !== 1 || + config.resumeArgs[0] !== (provider === "claude" ? "--resume" : "resume") + ) { + return "This agent has custom launch settings. Use its configured account instead."; + } + if ( + Object.keys(config.env).some( + (key) => + (AUTH_ENV[provider] as readonly string[]).includes(key) || + LAUNCH_ENV_OVERRIDES.has(key) || + (provider === "claude" && key.startsWith("CLAUDE_CODE_USE_")) || + key.startsWith("SUPERSET_"), + ) + ) { + return "This agent has an account or authentication override in its environment."; + } + return undefined; +} + +function selectableAccount(account: SessionAccount): boolean { + return ( + account.credentialKind === "subscription" && + (account.selection === null || account.selection === account.directory) && + Boolean( + account.directory && + isAbsolute(account.directory) && + // These values are typed into an interactive shell, where control bytes + // can submit a line before normal shell quoting has a chance to apply. + // biome-ignore lint/suspicious/noControlCharactersInRegex: reject terminal control bytes + !/[\x00-\x1f\x7f-\x9f]/.test(account.directory), + ) && + Boolean(account.email) + ); +} + +export async function listLaunchAccounts( + config: ResolvedHostAgentConfig, + discover = discoverSessionAccounts, + surface: "terminal" | "chat" = "terminal", +) { + if ( + surface === "chat" && + (config.presetId === "claude" || config.presetId === "codex") + ) + return listProviderLaunchAccounts(config.presetId, discover); + const reason = accountLaunchUnsupportedReason(config); + if (reason) return { supported: false, accounts: [], reason }; + return listProviderLaunchAccounts( + config.presetId as "claude" | "codex", + discover, + ); +} + +export async function listProviderLaunchAccounts( + provider: "claude" | "codex", + discover = discoverSessionAccounts, +) { + const accounts = await discover(provider); + return { + supported: true, + accounts: accounts.filter(selectableAccount).map((account) => ({ + selection: account.selection, + identity: account.identity, + email: account.email as string, + label: account.selection ?? "System account", + })), + }; +} + +/** Resolve only a current, discovered profile; client-supplied paths are never trusted. */ +export async function resolveLaunchAccount( + config: ResolvedHostAgentConfig, + choice: LaunchAccountChoice, + discover = discoverSessionAccounts, +): Promise { + const reason = accountLaunchUnsupportedReason(config); + if (reason) throw new TRPCError({ code: "BAD_REQUEST", message: reason }); + return resolveProviderLaunchAccount( + config.presetId as "claude" | "codex", + choice, + discover, + ); +} + +export async function resolveProviderLaunchAccount( + provider: "claude" | "codex", + choice: LaunchAccountChoice, + discover = discoverSessionAccounts, +): Promise { + const accounts = await discover(provider); + const account = accounts.find( + (candidate) => + candidate.selection === choice.selection && + candidate.identity === choice.identity && + selectableAccount(candidate), + ); + if (!account) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The selected account is no longer available or its sign-in changed. Refresh the account list and choose again.", + }); + return { ...account, pinned: true }; +} + +export async function validatePinnedLaunchAccount( + config: ResolvedHostAgentConfig, + account: SessionAccount, + deps: { + validate?: typeof validateSessionAccount; + discover?: typeof discoverSessionAccounts; + } = {}, +): Promise { + const reason = accountLaunchUnsupportedReason(config); + if ( + reason || + !account.pinned || + account.conflict || + account.agent !== config.presetId || + !selectableAccount(account) || + !(await (deps.validate ?? validateSessionAccount)(account)) + ) { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + reason ?? + "The saved account is unavailable or its sign-in changed. Nothing was launched.", + }); + } + const current = await resolveLaunchAccount( + config, + account, + deps.discover ?? discoverSessionAccounts, + ); + if (current.directory !== account.directory) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The saved account's profile location changed. Nothing was launched.", + }); +} + +export function pinnedAccountEnv( + account: SessionAccount, +): Record { + if (account.agent === "claude") { + // Unset is significant: Claude's system keychain identity differs from + // the one selected by explicitly exporting the same ~/.claude path. + return account.selection === null + ? {} + : { CLAUDE_CONFIG_DIR: account.directory as string }; + } + return { + CODEX_HOME: account.directory as string, + SUPERSET_DEFAULT_CODEX_HOME: account.directory as string, + }; +} + +export function withPinnedAccountEnv( + account: SessionAccount, + env: Record, +): Record { + const result = { ...env }; + for (const key of AUTH_ENV[account.agent]) delete result[key]; + return { + ...result, + ...pinnedAccountEnv(account), + SUPERSET_PINNED_ACCOUNT: + account.agent === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME", + }; +} + +export function pinnedAccountCommandPrefix( + account: SessionAccount, + env: Record, +): string { + const variable = + account.agent === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME"; + return `${buildArgvCommand([ + "env", + ...AUTH_ENV[account.agent].flatMap((key) => ["-u", key]), + ...Object.entries({ + ...env, + ...pinnedAccountEnv(account), + SUPERSET_PINNED_ACCOUNT: variable, + SUPERSET_NATIVE_CLAUDE_USAGE: + process.env.SUPERSET_NATIVE_CLAUDE_USAGE === "1" ? "1" : "", + }).map(([key, value]) => `${key}=${value}`), + ])} `; +} + +/** Prepare lifecycle tracking without changing login, default selection or history. */ +export function prepareLaunchAccountHooks(account: SessionAccount): void { + const directory = account.directory; + if (!account.pinned || !directory) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The selected account cannot prepare its hooks. Nothing was launched.", + }); + if (resolveDisabledAgentIds().includes(account.agent)) return; + const prepared = + account.agent === "claude" + ? ensureClaudeManagedHooksAt(directory) + : ensureCodexManagedHooksAt(directory); + if (!prepared) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The selected account's hooks could not be prepared. Fix its settings before launching.", + }); +} diff --git a/packages/host-service/src/trpc/router/notifications/background-successor-adapter.ts b/packages/host-service/src/trpc/router/notifications/background-successor-adapter.ts new file mode 100644 index 00000000000..519d6f63524 --- /dev/null +++ b/packages/host-service/src/trpc/router/notifications/background-successor-adapter.ts @@ -0,0 +1,351 @@ +import { execFile } from "node:child_process"; +import { realpath } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { isDeepStrictEqual, promisify } from "node:util"; +import { and, eq, isNull } from "drizzle-orm"; +import { getSupervisor } from "../../../daemon"; +import type { HostDb } from "../../../db"; +import { + terminalAgentBindings, + terminalSessions, + workspaces, +} from "../../../db/schema"; +import { resolveHostAgentConfig } from "../../../terminal-agents/agent-config"; +import { verifyAttributionToken } from "../../../terminal-agents/attribution-token"; +import { + backgroundAdoptionLaunchId, + backgroundWorkerBirthHash, + parseBackgroundAdoptionLaunchId, +} from "../../../terminal-agents/background-adoption"; +import { discoverClaudeBackgroundSession } from "../../../terminal-agents/claude-background-session"; +import { findClaudeSessionWriters } from "../../../terminal-agents/claude-session-writers"; +import { + findNativeClaudeTerminalClient, + observeNativeClaudeProcess, + resolveTrustedNativeClaudeExecutable, +} from "../../../terminal-agents/native-claude-process"; +import type { HostServiceContext } from "../../../types"; +import { validateAccountAuthRouting } from "../agents/account-auth-routing"; +import { + pinnedAccountEnv, + resolveLaunchAccount, +} from "../agents/launch-account"; +import { + parsePersistedSessionAccount, + sameSessionAccountContext, +} from "../usage/session-account/session-account"; +import { + type BackgroundSuccessorLineage, + type BackgroundSuccessorRefreshIO, + type BackgroundSuccessorTrigger, + createBackgroundSuccessorRefresh, +} from "./background-successor-refresh"; +import { fanOutAgentLifecycle } from "./fan-out-agent-lifecycle"; + +const execute = promisify(execFile); +type Binding = typeof terminalAgentBindings.$inferSelect; +interface LineageProof { + chain: Binding[]; + account: NonNullable>; + config: NonNullable>; +} +function binding(db: HostDb, terminalId: string) { + return db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, terminalId)) + .get(); +} +export async function readBackgroundSuccessorLineage( + ctx: HostServiceContext, + input: BackgroundSuccessorTrigger, +): Promise { + const first = binding(ctx.db, input.terminalId); + if ( + !first || + first.agentId !== "claude" || + first.launchId !== input.launchId || + first.agentSessionId !== input.sessionId || + !first.launchId || + first.endedAt === null || + first.endReason !== "resumed" + ) + return null; + const account = parsePersistedSessionAccount(first.accountJson); + if ( + !account?.pinned || + account.conflict || + account.agent !== "claude" || + account.credentialKind !== "subscription" || + !account.directory + ) + return null; + const workspace = ctx.db + .select() + .from(workspaces) + .where( + and(eq(workspaces.id, first.workspaceId), isNull(workspaces.archivedAt)), + ) + .get(); + if (!workspace) return null; + const [cwd, profile] = await Promise.all([ + realpath(workspace.worktreePath), + realpath(account.directory), + ]); + const chain: Binding[] = [first]; + let source = first; + for (let depth = 0; depth < 8; depth++) { + if ( + !source.resumedIntoTerminalId || + !source.launchId || + source.endReason !== "resumed" || + source.endedAt === null + ) + return null; + const target = binding(ctx.db, source.resumedIntoTerminalId); + if ( + !target || + chain.some((row) => row.terminalId === target.terminalId) || + target.agentId !== "claude" || + target.workspaceId !== first.workspaceId || + target.agentSessionId !== first.agentSessionId || + target.definitionId !== source.definitionId || + !sameSessionAccountContext( + parsePersistedSessionAccount(target.accountJson), + account, + ) + ) + return null; + const grant = parseBackgroundAdoptionLaunchId(target.launchId); + if ( + !grant || + target.launchId !== + backgroundAdoptionLaunchId({ + source: { + terminalId: source.terminalId, + workspaceId: source.workspaceId, + launchId: source.launchId, + sessionId: first.agentSessionId, + account, + definitionId: source.definitionId, + startedAt: source.startedAt, + }, + terminalId: target.terminalId, + cwd, + adoptedAt: target.startedAt, + worker: grant, + }) + ) + return null; + chain.push(target); + if (target.endedAt !== null) { + source = target; + continue; + } + const terminal = ctx.db + .select() + .from(terminalSessions) + .where(eq(terminalSessions.id, target.terminalId)) + .get(); + const config = resolveHostAgentConfig( + ctx.db, + target.definitionId ?? target.agentId, + ); + if ( + !terminal || + terminal.originWorkspaceId !== first.workspaceId || + terminal.status !== "active" || + terminal.disposeRequestedAt !== null || + !config || + config.presetId !== "claude" || + !target.launchId + ) + return null; + return { + key: JSON.stringify([ + target.workspaceId, + target.terminalId, + target.launchId, + first.agentSessionId, + ]), + terminalId: target.terminalId, + launchId: target.launchId, + workspaceId: target.workspaceId, + sessionId: first.agentSessionId, + workerPid: grant.pid, + workerBirthHash: grant.birthHash, + profile, + cwd, + lastEventAt: target.lastEventAt, + proof: { chain, account, config } satisfies LineageProof, + }; + } + return null; +} +function selectedEnvironment(account: LineageProof["account"]) { + const env = { ...process.env }; + for (const key of Object.keys(env)) + if ( + key === "CLAUDE_CONFIG_DIR" || + key === "SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR" || + key.startsWith("ANTHROPIC_") || + key.startsWith("CLAUDE_CODE_USE_") || + key === "CLAUDE_CODE_OAUTH_TOKEN" || + key === "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" || + key === "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR" + ) + delete env[key]; + return { ...env, ...pinnedAccountEnv(account) }; +} +export function backgroundSuccessorRefreshAdapter( + ctx: HostServiceContext, +): BackgroundSuccessorRefreshIO { + return { + read: (input) => + readBackgroundSuccessorLineage(ctx, input).catch(() => null), + async observe(lineage, signal) { + const facts = lineage.proof as LineageProof; + const verify = async () => { + const current = await resolveLaunchAccount(facts.config, facts.account); + await validateAccountAuthRouting(current, lineage.cwd); + return ( + sameSessionAccountContext(current, facts.account) && + (await realpath(current.directory as string)) === lineage.profile + ); + }; + const cli = await resolveTrustedNativeClaudeExecutable( + join(homedir(), ".local/bin/claude"), + { signal }, + ); + const proof = await discoverClaudeBackgroundSession( + { + sessionId: lineage.sessionId, + configDir: lineage.profile, + worktreePath: lineage.cwd, + }, + { + signal, + validateScope: verify, + runDiscovery: async (request) => + ( + await execute(cli, [...request.args], { + signal: request.signal, + env: selectedEnvironment(facts.account), + cwd: lineage.cwd, + timeout: 1_500, + maxBuffer: 256 * 1024, + encoding: "utf8", + }) + ).stdout, + verifyWorker: async (expected) => { + if (expected.pid !== lineage.workerPid) return null; + const worker = await observeNativeClaudeProcess(expected.pid, { + signal, + }); + if ( + backgroundWorkerBirthHash(worker.birth) !== + lineage.workerBirthHash || + worker.configDir !== lineage.profile || + worker.cwd !== lineage.cwd + ) + return null; + const sessions = await getSupervisor().listSessions( + ctx.organizationId, + 1_500, + ); + const session = sessions?.find( + (row) => row.id === lineage.terminalId && row.alive, + ); + if (!session || signal.aborted) return null; + const client = await findNativeClaudeTerminalClient(session.pid, { + signal, + }); + if ( + !client || + client.configDir !== lineage.profile || + client.cwd !== lineage.cwd || + client.executable !== worker.executable + ) + return null; + const writers = await findClaudeSessionWriters({ + sessionId: lineage.sessionId, + directories: [lineage.profile], + }); + if ( + !writers.includes(worker.pid) || + writers.some((pid) => pid !== worker.pid && pid !== client.pid) + ) + return null; + return { + pid: worker.pid, + birth: worker.birth, + executable: worker.executable, + configDir: worker.configDir, + worktreePath: worker.cwd, + sessionId: lineage.sessionId, + backgroundId: expected.backgroundId, + }; + }, + }, + ); + return proof && (await verify()) && !signal.aborted ? proof : null; + }, + publish(lineage, eventType, occurredAt) { + const proof = lineage.proof as LineageProof; + const target = binding(ctx.db, lineage.terminalId); + if ( + !target || + !isDeepStrictEqual(target, proof.chain.at(-1)) || + target.endedAt !== null || + target.launchId !== lineage.launchId || + target.lastEventAt >= occurredAt + ) + return; + ctx.terminalAgentStore.recordEvent({ + terminalId: lineage.terminalId, + workspaceId: lineage.workspaceId, + agentId: "claude", + agentSessionId: lineage.sessionId, + launchId: lineage.launchId, + eventType, + occurredAt, + }); + fanOutAgentLifecycle(ctx, { + terminalId: lineage.terminalId, + workspaceId: lineage.workspaceId, + agent: { agentId: "claude", sessionId: lineage.sessionId }, + eventType, + occurredAt, + }); + }, + wait: () => new Promise((resolve) => setTimeout(resolve, 250)), + }; +} +const refreshers = new WeakMap< + HostDb, + ReturnType +>(); +export function getBackgroundSuccessorRefresh(ctx: HostServiceContext) { + let refresh = refreshers.get(ctx.db); + if (!refresh) { + refresh = createBackgroundSuccessorRefresh( + backgroundSuccessorRefreshAdapter(ctx), + ); + refreshers.set(ctx.db, refresh); + } + return refresh; +} +export async function queueBackgroundSuccessorRefresh( + ctx: HostServiceContext, + input: BackgroundSuccessorTrigger & { attributionToken?: string }, +) { + if (!verifyAttributionToken(input.terminalId, input.attributionToken)) + return false; + return getBackgroundSuccessorRefresh(ctx).enqueue(input); +} + +export function disposeBackgroundSuccessorRefresh(db: HostDb): void { + refreshers.get(db)?.dispose(); + refreshers.delete(db); +} diff --git a/packages/host-service/src/trpc/router/notifications/background-successor-refresh.test.ts b/packages/host-service/src/trpc/router/notifications/background-successor-refresh.test.ts new file mode 100644 index 00000000000..fa814ca271d --- /dev/null +++ b/packages/host-service/src/trpc/router/notifications/background-successor-refresh.test.ts @@ -0,0 +1,193 @@ +import { expect, test } from "bun:test"; +import { backgroundWorkerBirthHash } from "../../../terminal-agents/background-adoption"; +import type { ClaudeBackgroundAttachProof } from "../../../terminal-agents/claude-background-session"; +import { + type BackgroundSuccessorLineage, + type BackgroundSuccessorRefreshIO, + createBackgroundSuccessorRefresh, + observedBackgroundLifecycle, +} from "./background-successor-refresh"; + +function fixture() { + const input = { + terminalId: "old", + launchId: "original-launch", + sessionId: "exact-native", + }; + let lineage: BackgroundSuccessorLineage | null = { + key: "exact-worker-and-successor", + terminalId: "new", + launchId: "grant", + workspaceId: "workspace", + sessionId: input.sessionId, + workerPid: 123, + workerBirthHash: backgroundWorkerBirthHash("exact-birth"), + profile: "/profile", + cwd: "/project", + lastEventAt: 10, + proof: { adopted: true }, + }; + const worker = { + pid: 123, + birth: "exact-birth", + executable: "/native/claude", + configDir: "/profile", + worktreePath: "/project", + sessionId: input.sessionId, + backgroundId: "aabbccdd", + }; + const proof: ClaudeBackgroundAttachProof = { + candidate: { + id: "aabbccdd", + sessionId: input.sessionId, + cwd: "/project", + state: "done", + status: "idle", + startedAt: 1, + }, + observedAt: 20, + target: { + sessionId: input.sessionId, + configDir: "/profile", + worktreePath: "/project", + }, + workerBefore: worker, + workerAfter: worker, + attachArgs: ["attach", "aabbccdd"], + nonAtomicAttach: true, + }; + let reads = 0; + let observations = 0; + const published: unknown[] = []; + const io: BackgroundSuccessorRefreshIO = { + read: async () => { + reads++; + return structuredClone(lineage); + }, + observe: async () => { + observations++; + return proof; + }, + publish: (scope, type, observedAt) => { + published.push({ terminalId: scope.terminalId, type, observedAt }); + }, + wait: async () => {}, + }; + return { + input, + io, + proof, + published, + counts: () => ({ reads, observations }), + rotate() { + lineage = { + ...(lineage as BackgroundSuccessorLineage), + launchId: "new-unrelated-launch", + proof: { rotated: true }, + }; + }, + dispose() { + lineage = null; + }, + }; +} +test("a burst of predecessor hooks only rereads the current worker and publishes its observed state", async () => { + const f = fixture(); + const refresh = createBackgroundSuccessorRefresh(f.io); + expect( + ( + await Promise.all( + Array.from({ length: 20 }, () => refresh.enqueue(f.input)), + ) + ).every(Boolean), + ).toBe(true); + await refresh.drain(); + expect(f.counts().observations).toBeLessThanOrEqual(2); + expect(f.published).toEqual([ + { terminalId: "new", type: "Stop", observedAt: 20 }, + ]); +}); +test("a disposed or rotated successor cancels publication after pending native observation", async () => { + for (const change of ["dispose", "rotate"] as const) { + const f = fixture(); + const observe = f.io.observe; + f.io.observe = async (...args) => { + const result = await observe(...args); + f[change](); + return result; + }; + const refresh = createBackgroundSuccessorRefresh(f.io); + await refresh.enqueue(f.input); + await refresh.drain(); + expect(f.published).toEqual([]); + } +}); +test("unknown attention or activity never becomes a synthetic busy/waiting state", () => { + const f = fixture(); + for (const candidate of [ + { + ...f.proof.candidate, + state: "working" as const, + status: "idle" as const, + }, + { + ...f.proof.candidate, + state: "blocked" as const, + status: "waiting" as const, + }, + { + ...f.proof.candidate, + state: "blocked" as const, + status: "waiting" as const, + waitingFor: "unknown reason", + }, + ]) + expect(observedBackgroundLifecycle({ ...f.proof, candidate })).toBeNull(); + expect( + observedBackgroundLifecycle({ + ...f.proof, + candidate: { + ...f.proof.candidate, + state: "blocked", + status: "waiting", + waitingFor: "input needed", + }, + }), + ).toBe("PermissionRequest"); +}); +test("a stale native observation cannot freshen an already newer successor", async () => { + const f = fixture(); + f.proof.observedAt = 9; + const refresh = createBackgroundSuccessorRefresh(f.io); + await refresh.enqueue(f.input); + await refresh.drain(); + expect(f.published).toEqual([]); +}); +test("disposal aborts owned work and late native results cannot publish or reopen collection", async () => { + const f = fixture(); + let release: ((value: ClaudeBackgroundAttachProof) => void) | undefined; + f.io.observe = async () => + new Promise((resolve) => { + release = resolve; + }); + const refresh = createBackgroundSuccessorRefresh(f.io); + await refresh.enqueue(f.input); + await Promise.resolve(); + await Promise.resolve(); + refresh.dispose(); + if (!release) throw new Error("Missing observation"); + release(f.proof); + await refresh.drain(); + expect(f.published).toEqual([]); + expect(await refresh.enqueue(f.input)).toBe(false); +}); + +test("a different native worker incarnation cannot publish even a plausible current state", async () => { + const f = fixture(); + f.proof.workerBefore = { ...f.proof.workerBefore, birth: "reused-pid" }; + f.proof.workerAfter = f.proof.workerBefore; + const refresh = createBackgroundSuccessorRefresh(f.io); + await refresh.enqueue(f.input); + await refresh.drain(); + expect(f.published).toEqual([]); +}); diff --git a/packages/host-service/src/trpc/router/notifications/background-successor-refresh.ts b/packages/host-service/src/trpc/router/notifications/background-successor-refresh.ts new file mode 100644 index 00000000000..200538a2b44 --- /dev/null +++ b/packages/host-service/src/trpc/router/notifications/background-successor-refresh.ts @@ -0,0 +1,151 @@ +import { isDeepStrictEqual } from "node:util"; +import { backgroundWorkerBirthHash } from "../../../terminal-agents/background-adoption"; +import type { ClaudeBackgroundAttachProof } from "../../../terminal-agents/claude-background-session"; +export interface BackgroundSuccessorTrigger { + terminalId: string; + launchId: string; + sessionId: string; +} +export interface BackgroundSuccessorLineage { + key: string; + terminalId: string; + launchId: string; + workspaceId: string; + sessionId: string; + workerPid: number; + workerBirthHash: string; + profile: string; + cwd: string; + lastEventAt: number; + proof: unknown; +} +export type BackgroundObservedLifecycle = + | "Start" + | "Stop" + | "PermissionRequest"; +export interface BackgroundSuccessorRefreshIO { + read( + input: BackgroundSuccessorTrigger, + ): Promise; + observe( + lineage: BackgroundSuccessorLineage, + signal: AbortSignal, + ): Promise; + publish( + lineage: BackgroundSuccessorLineage, + type: BackgroundObservedLifecycle, + observedAt: number, + ): void; + wait(): Promise; + schedule?(callback: () => void, milliseconds: number): () => void; +} +export function observedBackgroundLifecycle( + proof: ClaudeBackgroundAttachProof, +): BackgroundObservedLifecycle | null { + const row = proof.candidate; + if (row.state === "working" && row.status === "busy") return "Start"; + if (row.state === "done" && row.status === "idle") return "Stop"; + if ( + row.state === "blocked" && + row.status === "waiting" && + [ + "permission prompt", + "input needed", + "sandbox request", + "worker request", + "dialog open", + ].includes(row.waitingFor ?? "") + ) + return "PermissionRequest"; + return null; +} +/** The old hook is only a trigger. Its lifecycle, preview and receipt time are never replayed. */ +export function createBackgroundSuccessorRefresh( + io: BackgroundSuccessorRefreshIO, +) { + const jobs = new Map< + string, + { dirty: boolean; work: Promise; controller: AbortController } + >(); + let closed = false; + const api = { + async enqueue(input: BackgroundSuccessorTrigger): Promise { + if (closed) return false; + const first = await io.read(input); + if (closed || !first) return false; + const existing = jobs.get(first.key); + if (existing) { + existing.dirty = true; + return true; + } + if (jobs.size >= 64) return false; + const controller = new AbortController(); + const entry = { dirty: false, work: Promise.resolve(), controller }; + const cancel = io.schedule + ? io.schedule(() => controller.abort(), 8_000) + : (() => { + const timer = setTimeout(() => controller.abort(), 8_000); + return () => clearTimeout(timer); + })(); + const run = async () => { + await io.wait(); + for (let pass = 0; pass < 2 && !controller.signal.aborted; pass++) { + entry.dirty = false; + const lineage = await io.read(input); + if ( + !lineage || + lineage.key !== first.key || + controller.signal.aborted + ) + return; + const proof = await io.observe(lineage, controller.signal); + if ( + !proof || + controller.signal.aborted || + proof.target.sessionId !== lineage.sessionId || + proof.candidate.sessionId !== lineage.sessionId || + proof.target.configDir !== lineage.profile || + proof.target.worktreePath !== lineage.cwd || + proof.workerAfter.pid !== lineage.workerPid || + backgroundWorkerBirthHash(proof.workerAfter.birth) !== + lineage.workerBirthHash || + !isDeepStrictEqual(proof.workerBefore, proof.workerAfter) + ) + return; + const type = observedBackgroundLifecycle(proof); + const latest = await io.read(input); + if ( + type && + latest && + isDeepStrictEqual(latest, lineage) && + !controller.signal.aborted && + proof.observedAt > lineage.lastEventAt + ) + io.publish(lineage, type, proof.observedAt); + if (!entry.dirty) return; + await io.wait(); + } + }; + jobs.set(first.key, entry); + entry.work = run() + .catch(() => {}) + .finally(() => { + const followup = entry.dirty && !closed && !controller.signal.aborted; + cancel(); + controller.abort(); + if (jobs.get(first.key) === entry) jobs.delete(first.key); + if (followup) void api.enqueue(input); + }); + return true; + }, + async drain() { + while (jobs.size) + await Promise.all([...jobs.values()].map((entry) => entry.work)); + }, + dispose() { + closed = true; + for (const entry of jobs.values()) entry.controller.abort(); + }, + }; + return api; +} diff --git a/packages/host-service/src/trpc/router/notifications/background-successor-router.test.ts b/packages/host-service/src/trpc/router/notifications/background-successor-router.test.ts new file mode 100644 index 00000000000..9f9171fc18a --- /dev/null +++ b/packages/host-service/src/trpc/router/notifications/background-successor-router.test.ts @@ -0,0 +1,304 @@ +import { Database } from "bun:sqlite"; +import { afterEach, expect, test } from "bun:test"; +import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { eq } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import type { HostDb } from "../../../db"; +import * as schema from "../../../db/schema"; +import { + hostAgentConfigs, + terminalAgentBindings, + terminalSessions, + workspaces, +} from "../../../db/schema"; +import { + SqliteTerminalAgentBindingPersistence, + TerminalAgentStore, +} from "../../../terminal-agents"; +import { issueAttributionToken } from "../../../terminal-agents/attribution-token"; +import { + backgroundAdoptionLaunchId, + backgroundWorkerBirthHash, +} from "../../../terminal-agents/background-adoption"; +import type { ClaudeBackgroundAttachProof } from "../../../terminal-agents/claude-background-session"; +import type { HostServiceContext } from "../../../types"; +import { backgroundSuccessorRefreshAdapter } from "./background-successor-adapter"; +import { createBackgroundSuccessorRefresh } from "./background-successor-refresh"; +import { createNotificationsRouter } from "./notifications"; + +const databases: Database[] = []; +const folders: string[] = []; +afterEach(async () => { + for (const db of databases.splice(0)) db.close(); + for (const folder of folders.splice(0)) + await rm(folder, { recursive: true, force: true }); +}); +async function fixture() { + const root = await realpath( + await mkdtemp(join(tmpdir(), "superset-successor-router-")), + ); + folders.push(root); + const cwd = join(root, "project"); + const profile = join(root, "profile"); + await Promise.all([mkdir(cwd), mkdir(profile)]); + const sqlite = new Database(":memory:"); + databases.push(sqlite); + const db = drizzle(sqlite, { schema }) as unknown as HostDb; + migrate(db as never, { + migrationsFolder: resolve(import.meta.dir, "../../../../drizzle"), + }); + db.insert(workspaces) + .values({ id: "workspace", worktreePath: cwd, branch: "main" }) + .run(); + db.insert(hostAgentConfigs) + .values({ + id: "custom:fixture", + presetId: "claude", + label: "Claude", + command: "claude", + promptTransport: "argv", + resumeArgsJson: '["--resume"]', + displayOrder: 0, + }) + .run(); + const account = { + pinned: true as const, + agent: "claude" as const, + selection: profile, + directory: profile, + identity: "a".repeat(64), + credentialKind: "subscription" as const, + }; + const sessionId = "11111111-2222-4333-8444-555555555555"; + const source = { + terminalId: "old", + workspaceId: "workspace", + launchId: "original-launch", + sessionId, + account, + definitionId: "custom:fixture", + startedAt: 100, + }; + const grant = backgroundAdoptionLaunchId({ + source, + terminalId: "new", + cwd, + adoptedAt: 200, + worker: { pid: 123, birthHash: backgroundWorkerBirthHash("exact-birth") }, + }); + for (const terminalId of ["old", "new"]) + db.insert(terminalSessions) + .values({ + id: terminalId, + originWorkspaceId: "workspace", + status: terminalId === "new" ? "active" : "exited", + createdAt: 1, + }) + .run(); + db.insert(terminalAgentBindings) + .values([ + { + terminalId: "old", + workspaceId: "workspace", + agentId: "claude", + definitionId: "custom:fixture", + agentSessionId: sessionId, + launchId: source.launchId, + accountJson: JSON.stringify(account), + startedAt: 100, + lastEventAt: 150, + lastEventType: "Stop", + endedAt: 200, + endReason: "resumed", + resumedIntoTerminalId: "new", + }, + { + terminalId: "new", + workspaceId: "workspace", + agentId: "claude", + definitionId: "custom:fixture", + agentSessionId: sessionId, + launchId: grant, + accountJson: JSON.stringify(account), + startedAt: 200, + lastEventAt: 200, + lastEventType: "Attached", + }, + ]) + .run(); + const events: unknown[] = []; + const ctx = { + db, + organizationId: "fixture-org", + isAuthenticated: true, + terminalAgentStore: new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ), + eventBus: { + broadcastAgentLifecycle: (event: unknown) => { + events.push(event); + }, + broadcastAgentBindingsChanged: () => {}, + broadcastWorkspaceChanged: () => {}, + }, + api: { task: { start: { mutate: async () => {} } } }, + } as unknown as HostServiceContext; + const io = backgroundSuccessorRefreshAdapter(ctx); + let observations = 0; + const worker = { + pid: 123, + birth: "exact-birth", + executable: "/native/claude", + configDir: profile, + worktreePath: cwd, + sessionId, + backgroundId: "aabbccdd", + }; + const proof: ClaudeBackgroundAttachProof = { + candidate: { + id: "aabbccdd", + sessionId, + name: "Exact worker", + cwd, + state: "done", + status: "idle", + startedAt: 1, + pid: 123, + }, + observedAt: 300, + target: { sessionId, configDir: profile, worktreePath: cwd }, + workerBefore: worker, + workerAfter: worker, + attachArgs: ["attach", "aabbccdd"], + nonAtomicAttach: true, + }; + io.observe = async () => { + observations++; + return proof; + }; + io.wait = async () => {}; + const refresh = createBackgroundSuccessorRefresh(io); + let captures = 0; + const router = createNotificationsRouter( + async () => { + captures++; + return undefined; + }, + async (_ctx, input) => refresh.enqueue(input), + ); + const caller = router.createCaller(ctx); + const hook = { + terminalId: "old", + launchId: source.launchId, + attributionToken: issueAttributionToken("old"), + agent: { agentId: "claude", sessionId }, + eventType: "Start", + preview: "STALE_PREVIEW_MUST_NOT_FORWARD", + }; + const row = (terminalId: string) => + db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, terminalId)) + .get(); + return { + db, + ctx, + io, + refresh, + caller, + hook, + proof, + row, + events, + count: () => ({ observations, captures }), + }; +} +test("real hook router treats late and out-of-order predecessor events only as current-state refresh triggers", async () => { + const f = await fixture(); + const results = await Promise.all([ + f.caller.hook(f.hook), + f.caller.hook({ ...f.hook, eventType: "Stop" }), + f.caller.hook({ + ...f.hook, + eventType: "Attached", + accountProfile: "/wrong", + }), + ]); + expect(results.every((result) => !result.ignored)).toBe(true); + await f.refresh.drain(); + expect(f.row("old")).toMatchObject({ + endReason: "resumed", + lastEventAt: 150, + agentSessionId: f.hook.agent.sessionId, + }); + expect(f.row("new")).toMatchObject({ + lastEventType: "Stop", + lastEventAt: 300, + }); + expect(f.count().captures).toBe(0); + expect(f.count().observations).toBeLessThanOrEqual(2); + expect(f.events).toEqual([ + { + workspaceId: "workspace", + eventType: "Stop", + terminalId: "new", + agent: { agentId: "claude", sessionId: f.hook.agent.sessionId }, + occurredAt: 300, + }, + ]); +}); +test("unknown launch, wrong native session and forged original token cannot forward", async () => { + for (const change of [ + { attributionToken: "0".repeat(64) }, + { launchId: "foreign-launch" }, + { agent: { agentId: "claude", sessionId: "foreign-session" } }, + ]) { + const f = await fixture(); + expect((await f.caller.hook({ ...f.hook, ...change })).ignored).toBe(true); + await f.refresh.drain(); + expect(f.count().observations).toBe(0); + expect(f.events).toEqual([]); + expect(f.row("new")?.lastEventAt).toBe(200); + } +}); +test("source or destination account rotation invalidates adoption lineage", async () => { + for (const terminalId of ["old", "new"]) { + const f = await fixture(); + f.db + .update(terminalAgentBindings) + .set({ + accountJson: JSON.stringify({ + ...f.ctx.terminalAgentStore.getProvenance(terminalId)?.account, + identity: "b".repeat(64), + }), + }) + .where(eq(terminalAgentBindings.terminalId, terminalId)) + .run(); + await f.caller.hook(f.hook); + await f.refresh.drain(); + expect(f.count().observations).toBe(0); + expect(f.events).toEqual([]); + } +}); +test("destination disposal while native observation is pending cannot resurrect it", async () => { + const f = await fixture(); + f.io.observe = async () => { + f.db + .update(terminalAgentBindings) + .set({ endedAt: 250, endReason: "disposed" }) + .where(eq(terminalAgentBindings.terminalId, "new")) + .run(); + return f.proof; + }; + await f.caller.hook(f.hook); + await f.refresh.drain(); + expect(f.row("new")).toMatchObject({ + endReason: "disposed", + lastEventAt: 200, + }); + expect(f.events).toEqual([]); +}); diff --git a/packages/host-service/src/trpc/router/notifications/native-claude-usage.test.ts b/packages/host-service/src/trpc/router/notifications/native-claude-usage.test.ts new file mode 100644 index 00000000000..5bb4186a1a8 --- /dev/null +++ b/packages/host-service/src/trpc/router/notifications/native-claude-usage.test.ts @@ -0,0 +1,188 @@ +import { expect, test } from "bun:test"; +import type { TerminalAgentBinding } from "../../../terminal-agents/types"; +import type { NativeClaudeUsageDependencies } from "../usage/native-claude-binding"; +import { createNativeClaudeUsageStore } from "../usage/native-claude-usage"; +import { + createNativeClaudeTerminalFeed, + matchesNativeClaudeHook, +} from "./native-claude-usage"; + +function fixture() { + let now = 1_800_000_000_000; + let generation = "a".repeat(64); + let scope: string | null = null; + const account = { + agent: "claude" as const, + credentialKind: "subscription" as const, + pinned: true as const, + identity: "e".repeat(64), + selection: "/fixture/profile", + directory: "/fixture/profile", + }; + const identity = { + terminalId: "owned-terminal", + launchId: "owned-launch", + sessionId: "owned-session", + }; + let binding: TerminalAgentBinding = { + ...identity, + agentSessionId: identity.sessionId, + account, + workspaceId: "owned-workspace", + agentId: "claude", + startedAt: now, + lastEventAt: now, + lastEventType: "Attached", + }; + const store = createNativeClaudeUsageStore({ + persist: false, + now: () => now, + }); + const deps: NativeClaudeUsageDependencies = { + store, + validateAccount: async () => true, + captureGeneration: async () => generation, + resolveScope: async (_a, _d, _i, expected) => + expected === generation ? scope : null, + }; + const feed = createNativeClaudeTerminalFeed(deps, () => now); + const frame = (counter: number) => ({ + cost: { total_api_duration_ms: counter }, + rate_limits: { + five_hour: { used_percentage: 25, resets_at: 1_800_000_300 }, + }, + }); + return { + account, + identity, + feed, + store, + deps, + frame, + current: () => binding, + advance: (ms = 1000) => { + now += ms; + }, + time: () => now, + warm: () => { + scope = "b".repeat(64); + }, + rotate: () => { + generation = "c".repeat(64); + }, + replace: (change: Partial) => { + binding = { ...binding, ...change }; + }, + }; +} +test("prelaunch generation survives cold proof and promotes later replay at its original age", async () => { + const f = fixture(); + expect(await f.feed.prepare(f.identity.terminalId, f.account)).toBe(true); + expect(f.feed.capture(f.identity, f.current)).toBe(true); + expect(await f.feed.ingest(f.identity, f.frame(0), f.current)).toBe(false); + f.advance(); + await f.feed.ingest(f.identity, f.frame(1), f.current); + f.advance(); + f.warm(); + expect(await f.feed.ingest(f.identity, f.frame(1), f.current)).toBe(true); + expect(f.store.snapshot("b".repeat(64))[0]?.observedAt).toBe( + 1_800_000_001_000, + ); +}); +test("unprepared, changed generation, ended and foreign sessions cannot bind", async () => { + const f = fixture(); + expect(f.feed.capture(f.identity, f.current)).toBe(false); + await f.feed.prepare(f.identity.terminalId, f.account); + expect( + f.feed.capture({ ...f.identity, sessionId: "foreign" }, f.current), + ).toBe(false); + expect(f.feed.capture(f.identity, f.current)).toBe(true); + f.warm(); + f.rotate(); + expect(await f.feed.ingest(f.identity, f.frame(1), f.current)).toBe(false); + f.replace({ endedAt: 1_800_000_002_000 }); + expect(matchesNativeClaudeHook(f.current(), f.identity)).toBe(false); +}); +test("a delayed hook cannot capture a credential rotated after prelaunch", async () => { + const f = fixture(); + await f.feed.prepare(f.identity.terminalId, f.account); + f.rotate(); + f.warm(); + expect(f.feed.capture(f.identity, f.current)).toBe(true); + expect(await f.feed.ingest(f.identity, f.frame(0), f.current)).toBe(false); + expect(await f.feed.ingest(f.identity, f.frame(1), f.current)).toBe(false); + expect(f.store.snapshot("b".repeat(64))).toEqual([]); +}); + +test("background adoption never forwards predecessor samples or refreshes their age", async () => { + const f = fixture(); + f.warm(); + await f.feed.prepare(f.identity.terminalId, f.account); + f.feed.capture(f.identity, f.current); + await f.feed.ingest(f.identity, f.frame(0), f.current); + f.advance(); + await f.feed.ingest(f.identity, f.frame(1), f.current); + const original = f.store.snapshot("b".repeat(64)); + f.advance(); + f.replace({ endedAt: 1_800_000_002_000, endReason: "resumed" }); + expect(await f.feed.ingest(f.identity, f.frame(2), f.current)).toBe(false); + expect(f.store.snapshot("b".repeat(64))).toEqual(original); + f.replace({ + terminalId: "successor-terminal", + endedAt: undefined, + endReason: undefined, + launchId: "successor-launch", + }); + expect(await f.feed.ingest(f.identity, f.frame(2), f.current)).toBe(false); + expect( + await f.feed.ingest( + { + ...f.identity, + terminalId: "successor-terminal", + launchId: "successor-launch", + }, + f.frame(2), + f.current, + ), + ).toBe(false); + expect(f.store.snapshot("b".repeat(64))).toEqual(original); +}); + +test("terminal hook receipt precedes deferred account validation", async () => { + const f = fixture(); + f.warm(); + await f.feed.prepare(f.identity.terminalId, f.account); + f.feed.capture(f.identity, f.current); + await f.feed.ingest(f.identity, f.frame(0), f.current); + f.advance(); + const receivedAt = f.time(); + let release!: () => void; + let entered!: () => void; + const waiting = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + f.deps.validateAccount = async () => { + entered(); + await gate; + return true; + }; + const pending = f.feed.ingest(f.identity, f.frame(1), f.current); + await waiting; + f.advance(45_000); + release(); + expect(await pending).toBe(true); + expect(f.store.snapshot("b".repeat(64))[0]?.observedAt).toBe(receivedAt); +}); + +test("a warm credential proof without a host launch permit cannot accept producer frames", async () => { + const f = fixture(); + f.warm(); + expect(f.feed.capture(f.identity, f.current)).toBe(false); + expect(await f.feed.ingest(f.identity, f.frame(0), f.current)).toBe(false); + f.advance(); + expect(await f.feed.ingest(f.identity, f.frame(1), f.current)).toBe(false); + expect(f.store.snapshot("b".repeat(64))).toEqual([]); +}); diff --git a/packages/host-service/src/trpc/router/notifications/native-claude-usage.ts b/packages/host-service/src/trpc/router/notifications/native-claude-usage.ts new file mode 100644 index 00000000000..468d1418568 --- /dev/null +++ b/packages/host-service/src/trpc/router/notifications/native-claude-usage.ts @@ -0,0 +1,131 @@ +import type { TerminalAgentBinding } from "../../../terminal-agents/types"; +import { + captureNativeClaudeUsageGeneration, + resolveNativeClaudeUsageScope, +} from "../usage/claude"; +import { + ingestNativeClaudeBinding, + isNativeClaudeAccount, + type NativeClaudeAccount, + type NativeClaudeUsageDependencies, +} from "../usage/native-claude-binding"; +import { nativeClaudeUsage } from "../usage/native-claude-usage"; +import { + sameSessionAccountContext, + validateSessionAccount, +} from "../usage/session-account/session-account"; + +export interface NativeClaudeHookIdentity { + terminalId: string; + launchId: string; + sessionId: string; +} +const dependencies: NativeClaudeUsageDependencies = { + captureGeneration: captureNativeClaudeUsageGeneration, + resolveScope: resolveNativeClaudeUsageScope, + validateAccount: validateSessionAccount, + store: nativeClaudeUsage, +}; +export function matchesNativeClaudeHook( + binding: TerminalAgentBinding | undefined, + input: NativeClaudeHookIdentity, +): binding is TerminalAgentBinding { + return ( + !!binding && + binding.endedAt === undefined && + !binding.accountInvalid && + binding.agentId === "claude" && + binding.terminalId === input.terminalId && + binding.launchId === input.launchId && + binding.agentSessionId === input.sessionId && + binding.account?.pinned === true && + !binding.account.conflict && + binding.account.agent === "claude" && + binding.account.credentialKind === "subscription" + ); +} +export function createNativeClaudeTerminalFeed( + deps = dependencies, + now = Date.now, +) { + const permits = new Map< + string, + { account: NativeClaudeAccount; generation: string; at: number } + >(); + return { + async prepare( + terminalId: string, + account: NativeClaudeAccount | undefined, + ): Promise { + if ( + !isNativeClaudeAccount(account) || + !(await deps.validateAccount(account)) + ) + return false; + const generation = await deps.captureGeneration( + account.selection, + account.directory, + account.identity, + ); + if (!generation) return false; + const at = now(); + for (const [id, value] of permits) + if (at - value.at > 300_000 || value.at > at) permits.delete(id); + while (permits.size >= 256) + permits.delete(permits.keys().next().value as string); + permits.set(terminalId, { account: { ...account }, generation, at }); + return true; + }, + capture( + identity: NativeClaudeHookIdentity, + current: () => TerminalAgentBinding | undefined, + ): boolean { + const binding = current(); + const permit = permits.get(identity.terminalId); + if ( + !permit || + now() < permit.at || + now() - permit.at > 300_000 || + !matchesNativeClaudeHook(binding, identity) || + !sameSessionAccountContext(binding.account, permit.account) + ) + return false; + const captured = deps.store.captureLaunch({ + ...identity, + generation: permit.generation, + }); + if (captured) permits.delete(identity.terminalId); + return captured; + }, + async ingest( + identity: NativeClaudeHookIdentity, + payload: unknown, + current: () => TerminalAgentBinding | undefined, + ): Promise { + // Receipt is captured before asynchronous account/proof validation. + const receivedAt = now(); + const binding = current(); + if (!matchesNativeClaudeHook(binding, identity) || !binding.account) + return false; + const account = binding.account; + const unchanged = () => { + const after = current(); + return ( + matchesNativeClaudeHook(after, identity) && + sameSessionAccountContext(after.account, account) + ); + }; + return ingestNativeClaudeBinding( + account, + identity, + { source: "claude_statusline", payload, receivedAt }, + unchanged, + deps, + ); + }, + }; +} +const feed = createNativeClaudeTerminalFeed(); +export const prepareNativeClaudeTerminalLaunch = feed.prepare; +export const captureNativeClaudeLaunch = feed.capture; +export const ingestNativeClaudeHook = feed.ingest; diff --git a/packages/host-service/src/trpc/router/notifications/notifications.test.ts b/packages/host-service/src/trpc/router/notifications/notifications.test.ts index 77064e45072..394be317d4e 100644 --- a/packages/host-service/src/trpc/router/notifications/notifications.test.ts +++ b/packages/host-service/src/trpc/router/notifications/notifications.test.ts @@ -17,13 +17,19 @@ import type { AgentLifecycleEventType } from "../../../events"; import type { WorkspaceChangedMessage } from "../../../events/types"; import { TerminalAgentStore } from "../../../terminal-agents"; import { issueAttributionToken } from "../../../terminal-agents/attribution-token"; -import { SqliteTerminalAgentBindingPersistence } from "../../../terminal-agents/persistence"; +import { + markTerminalAgentBindingEnded, + SqliteTerminalAgentBindingPersistence, +} from "../../../terminal-agents/persistence"; import type { HostServiceContext } from "../../../types"; import { getLocalWorkspace, insertLocalWorkspace, } from "../../../workspaces/local-workspace-store"; -import { notificationsRouter } from "./notifications"; +import { + createNotificationsRouter, + notificationsRouter, +} from "./notifications"; interface BroadcastedAgentLifecycleEvent { workspaceId: string; @@ -139,6 +145,7 @@ function createDbContext({ const workspaceChanged: WorkspaceChangedMessage[] = []; const eventBus = { broadcastAgentLifecycle: () => {}, + broadcastAgentBindingsChanged: () => {}, broadcastWorkspaceChanged: ( message: Omit, ) => { @@ -609,6 +616,71 @@ describe("reported transcript path", () => { }); describe("login attribution authentication", () => { + it("retains a conflicting explicit pin instead of falling back to the default account", async () => { + const { ctx, terminalAgentStore } = createContext("workspace-1"); + const account = { + agent: "claude" as const, + selection: "/selected", + directory: "/selected", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + pinned: true as const, + }; + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + account, + launchId: "one", + eventType: "Attached", + occurredAt: 1, + }); + await notificationsRouter.createCaller(ctx).hook({ + terminalId: "terminal-1", + eventType: "SessionStart", + agent: { agentId: "claude", sessionId: "native" }, + launchId: "one", + accountProfile: "", + apiKey: true, + attributionToken: issueAttributionToken("terminal-1"), + }); + expect(terminalAgentStore.get("terminal-1")?.account).toEqual({ + ...account, + conflict: true, + }); + }); + + it("does not let unauthenticated launch metadata erase an explicit pin", async () => { + const { ctx, terminalAgentStore } = createContext("workspace-1"); + const account = { + agent: "claude" as const, + selection: "/selected", + directory: "/selected", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + pinned: true as const, + }; + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + agentSessionId: "native", + account, + launchId: "one", + eventType: "Attached", + occurredAt: 1, + }); + await notificationsRouter.createCaller(ctx).hook({ + terminalId: "terminal-1", + eventType: "SessionStart", + agent: { agentId: "claude", sessionId: "other" }, + launchId: "other-launch", + accountProfile: "", + apiKey: true, + }); + expect(terminalAgentStore.get("terminal-1")?.account).toEqual(account); + expect(terminalAgentStore.get("terminal-1")?.agentSessionId).toBe("native"); + }); it("publishes launch events after the binding and account are readable", async () => { const { ctx, terminalAgentStore, broadcastAgentLifecycle } = createContext("workspace-1"); @@ -665,3 +737,481 @@ describe("login attribution authentication", () => { expect(terminalAgentStore.get("terminal-1")?.account).toBeUndefined(); }); }); + +describe("pinned capture race safety", () => { + const account = { + agent: "claude" as const, + selection: "/selected", + directory: "/selected", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + pinned: true as const, + }; + function pinned() { + const context = createContext("workspace-1"); + context.terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + account, + launchId: "one", + eventType: "Attached", + occurredAt: 1, + }); + return context; + } + const hook = { + terminalId: "terminal-1", + eventType: "SessionStart", + agent: { agentId: "claude", sessionId: "native" }, + launchId: "one", + accountProfile: "/selected", + }; + it("does not accept the first native id from an unattributed hook", async () => { + const { ctx, terminalAgentStore } = pinned(); + await notificationsRouter + .createCaller(ctx) + .hook({ ...hook, agent: { ...hook.agent, sessionId: "forged" } }); + expect( + terminalAgentStore.get("terminal-1")?.agentSessionId, + ).toBeUndefined(); + await createNotificationsRouter(async () => account) + .createCaller(ctx) + .hook({ ...hook, attributionToken: issueAttributionToken("terminal-1") }); + expect(terminalAgentStore.get("terminal-1")?.account).toEqual(account); + expect(terminalAgentStore.get("terminal-1")?.agentSessionId).toBe("native"); + }); + it("retains an explicit pin when capture is temporarily unavailable", async () => { + const { ctx, terminalAgentStore } = pinned(); + await createNotificationsRouter(async () => undefined) + .createCaller(ctx) + .hook({ ...hook, attributionToken: issueAttributionToken("terminal-1") }); + expect(terminalAgentStore.get("terminal-1")?.account).toEqual(account); + }); + it("does not heal a positively conflicting pin on a later matching capture", async () => { + const { ctx, terminalAgentStore } = pinned(); + await createNotificationsRouter(async () => ({ + ...account, + identity: "b".repeat(64), + })) + .createCaller(ctx) + .hook({ ...hook, attributionToken: issueAttributionToken("terminal-1") }); + await createNotificationsRouter(async () => account) + .createCaller(ctx) + .hook({ ...hook, attributionToken: issueAttributionToken("terminal-1") }); + expect(terminalAgentStore.get("terminal-1")?.account?.conflict).toBe(true); + }); + function deferredCapture(value: typeof account | undefined = account) { + let finish!: () => void; + let started!: () => void; + const capturing = new Promise((resolve) => { + started = resolve; + }); + const captured = new Promise((resolve) => { + finish = () => resolve(value); + }); + return { + capturing, + finish, + capture: () => { + started(); + return captured; + }, + }; + } + + it("retains native details when the same launch's wrapper report finishes first", async () => { + const { ctx, db } = createDbContext({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + }); + ctx.terminalAgentStore = new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ); + ctx.terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + account, + launchId: "one", + eventType: "Attached", + occurredAt: 1, + }); + const pendingCapture = deferredCapture(); + const caller = createNotificationsRouter( + pendingCapture.capture, + ).createCaller(ctx); + const transcriptPath = resolve( + homedir(), + ".claude/projects/-tmp-workspace-1/native.jsonl", + ); + const pending = caller.hook({ + ...hook, + transcriptPath, + attributionToken: issueAttributionToken("terminal-1"), + }); + await pendingCapture.capturing; + await createNotificationsRouter(async () => account) + .createCaller(ctx) + .hook({ + ...hook, + agent: { agentId: "claude" }, + attributionToken: issueAttributionToken("terminal-1"), + }); + const wrapper = ctx.terminalAgentStore.get("terminal-1"); + pendingCapture.finish(); + expect((await pending).ignored).toBe(false); + const restored = new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ).get("terminal-1"); + expect(restored).toMatchObject({ + account, + agentSessionId: "native", + startedAt: wrapper?.startedAt, + lastEventAt: wrapper?.lastEventAt, + lastEventType: wrapper?.lastEventType, + }); + expect( + db + .select({ path: terminalAgentBindings.transcriptPath }) + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, "terminal-1")) + .get()?.path, + ).toBe(transcriptPath); + }); + + for (const eventType of ["Start", "Stop"]) { + it(`merges a same-launch account after ${eventType} without replaying lifecycle`, async () => { + const { + ctx, + terminalAgentStore, + broadcastAgentLifecycle, + broadcastAgentBindingsChanged, + } = createContext("workspace-1"); + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + launchId: "one", + eventType: "Attached", + occurredAt: 1, + }); + const pendingCapture = deferredCapture(); + const pending = createNotificationsRouter(pendingCapture.capture) + .createCaller(ctx) + .hook({ + ...hook, + attributionToken: issueAttributionToken("terminal-1"), + }); + await pendingCapture.capturing; + await notificationsRouter.createCaller(ctx).hook({ + ...hook, + accountProfile: undefined, + eventType, + attributionToken: issueAttributionToken("terminal-1"), + }); + const advanced = terminalAgentStore.get("terminal-1"); + pendingCapture.finish(); + expect((await pending).ignored).toBe(false); + expect(terminalAgentStore.get("terminal-1")).toMatchObject({ + account, + agentSessionId: "native", + startedAt: advanced?.startedAt, + lastEventAt: advanced?.lastEventAt, + lastEventType: eventType, + }); + expect(broadcastAgentLifecycle).toHaveBeenCalledTimes(1); + expect(broadcastAgentBindingsChanged).toHaveBeenCalledTimes(1); + }); + } + + it("records a captured pin mismatch after same-launch work starts", async () => { + const { ctx, terminalAgentStore } = pinned(); + const pendingCapture = deferredCapture({ + ...account, + identity: "b".repeat(64), + }); + const pending = createNotificationsRouter(pendingCapture.capture) + .createCaller(ctx) + .hook({ ...hook, attributionToken: issueAttributionToken("terminal-1") }); + await pendingCapture.capturing; + await notificationsRouter.createCaller(ctx).hook({ + ...hook, + accountProfile: undefined, + eventType: "Start", + attributionToken: issueAttributionToken("terminal-1"), + }); + const advanced = terminalAgentStore.get("terminal-1"); + pendingCapture.finish(); + expect((await pending).ignored).toBe(false); + expect(terminalAgentStore.get("terminal-1")).toMatchObject({ + account: { ...account, conflict: true }, + agentSessionId: "native", + lastEventType: "Start", + lastEventAt: advanced?.lastEventAt, + }); + }); + + for (const replacement of ["native-id", "account", "ended"] as const) { + it(`rejects delayed metadata after ${replacement} ownership changes`, async () => { + const { ctx, terminalAgentStore } = pinned(); + const pendingCapture = deferredCapture(); + const pending = createNotificationsRouter(pendingCapture.capture) + .createCaller(ctx) + .hook({ + ...hook, + attributionToken: issueAttributionToken("terminal-1"), + }); + await pendingCapture.capturing; + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + account: + replacement === "account" + ? { ...account, identity: "c".repeat(64) } + : account, + agentSessionId: + replacement === "native-id" ? "other-native" : undefined, + launchId: "one", + eventType: replacement === "ended" ? "exit" : "Start", + occurredAt: 2, + }); + const advanced = terminalAgentStore.get("terminal-1"); + pendingCapture.finish(); + expect((await pending).ignored).toBe(true); + expect(terminalAgentStore.get("terminal-1")).toEqual(advanced); + }); + } + + it("rejects a replaced account even when the delayed capture matches its new identity", async () => { + const { ctx, terminalAgentStore } = pinned(); + const replacement = { ...account, identity: "c".repeat(64) }; + const pendingCapture = deferredCapture(replacement); + const pending = createNotificationsRouter(pendingCapture.capture) + .createCaller(ctx) + .hook({ ...hook, attributionToken: issueAttributionToken("terminal-1") }); + await pendingCapture.capturing; + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + account: replacement, + launchId: "one", + eventType: "Start", + occurredAt: 2, + }); + const advanced = terminalAgentStore.get("terminal-1"); + pendingCapture.finish(); + expect((await pending).ignored).toBe(true); + expect(terminalAgentStore.get("terminal-1")).toEqual(advanced); + }); + + for (const replacement of ["launch", "native-id"] as const) { + it(`does not merge a different ${replacement} into a launch that advanced during capture`, async () => { + const { ctx, terminalAgentStore } = pinned(); + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + agentSessionId: "original-native", + launchId: "one", + account, + eventType: "Attached", + occurredAt: 2, + }); + const pendingCapture = deferredCapture(); + const pending = createNotificationsRouter(pendingCapture.capture) + .createCaller(ctx) + .hook({ + ...hook, + launchId: replacement === "launch" ? "two" : "one", + agent: { + agentId: "claude", + sessionId: + replacement === "native-id" ? "other-native" : "original-native", + }, + attributionToken: issueAttributionToken("terminal-1"), + }); + await pendingCapture.capturing; + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + agentSessionId: "original-native", + launchId: "one", + eventType: "Start", + occurredAt: 3, + }); + const advanced = terminalAgentStore.get("terminal-1"); + pendingCapture.finish(); + expect((await pending).ignored).toBe(true); + expect(terminalAgentStore.get("terminal-1")).toEqual(advanced); + }); + } + + it("discards delayed account capture after a newer launch replaces the binding", async () => { + const { ctx, terminalAgentStore } = pinned(); + let finish!: (value: typeof account) => void; + const captured = new Promise((resolve) => { + finish = resolve; + }); + let started!: () => void; + const capturing = new Promise((resolve) => { + started = resolve; + }); + const pending = createNotificationsRouter(() => { + started(); + return captured; + }) + .createCaller(ctx) + .hook({ ...hook, attributionToken: issueAttributionToken("terminal-1") }); + await capturing; + const newer = { ...account, identity: "c".repeat(64) }; + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "workspace-1", + agentId: "claude", + agentSessionId: "newer-native", + account: newer, + launchId: "two", + eventType: "Start", + occurredAt: 2, + }); + finish(account); + expect((await pending).ignored).toBe(true); + expect(terminalAgentStore.get("terminal-1")?.account).toEqual(newer); + expect(terminalAgentStore.get("terminal-1")?.launchId).toBe("two"); + }); +}); + +it("an unauthenticated end hook cannot end an explicitly pinned account launch", async () => { + const { ctx, terminalAgentStore, broadcastAgentBindingsChanged } = + createContext("ws-1"); + terminalAgentStore.recordEvent({ + terminalId: "terminal-1", + workspaceId: "ws-1", + agentId: "claude", + agentSessionId: "native-1", + launchId: "launch-1", + eventType: "Attached", + occurredAt: 1, + account: { + agent: "claude", + selection: "/fixture/profile", + directory: "/fixture/profile", + credentialKind: "subscription", + identity: "a".repeat(64), + pinned: true, + }, + }); + const result = await notificationsRouter.createCaller(ctx).hook({ + terminalId: "terminal-1", + eventType: "Detached", + agent: { agentId: "claude", sessionId: "native-1" }, + launchId: "launch-1", + }); + expect(result).toMatchObject({ success: true, ignored: true }); + expect(terminalAgentStore.get("terminal-1")?.agentSessionId).toBe("native-1"); + expect(broadcastAgentBindingsChanged).not.toHaveBeenCalled(); +}); + +describe("ended pinned launch ownership through the actual hook router", () => { + const account = { + agent: "claude" as const, + selection: "/fixture/profile", + directory: "/fixture/profile", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + pinned: true as const, + }; + function ended(reason: "detached" | "resumed" | "disposed") { + const { ctx, db } = createDbContext({ + terminalId: "terminal-ended", + workspaceId: "workspace-ended", + }); + const persistence = new SqliteTerminalAgentBindingPersistence(db); + ctx.terminalAgentStore = new TerminalAgentStore(persistence); + ctx.terminalAgentStore.recordEvent({ + terminalId: "terminal-ended", + workspaceId: "workspace-ended", + agentId: "claude", + agentSessionId: "native", + launchId: "launch", + account, + eventType: "Attached", + occurredAt: 1, + }); + markTerminalAgentBindingEnded(db, "terminal-ended", reason, 2); + ctx.terminalAgentStore = new TerminalAgentStore(persistence); + return { ctx, db }; + } + it("an authenticated ended pinned launch survives account capture and restores its exact durable metadata", async () => { + const { ctx, db } = ended("detached"); + const result = await createNotificationsRouter(async () => account) + .createCaller(ctx) + .hook({ + terminalId: "terminal-ended", + eventType: "Attached", + agent: { agentId: "claude", sessionId: "native" }, + launchId: "launch", + accountProfile: "/fixture/profile", + attributionToken: issueAttributionToken("terminal-ended"), + }); + expect(result).toMatchObject({ success: true, ignored: false }); + expect(ctx.terminalAgentStore.get("terminal-ended")?.account).toEqual( + account, + ); + expect( + db.query.terminalAgentBindings.findFirst().sync()?.endedAt, + ).toBeNull(); + }); + it("an ended pinned row stays intact without a native ID and revives only on a fresh identified hook", async () => { + const { ctx, db } = ended("detached"); + const before = db.query.terminalAgentBindings.findFirst().sync(); + let captures = 0; + const caller = createNotificationsRouter(async () => { + captures++; + return account; + }).createCaller(ctx); + const input = { + terminalId: "terminal-ended", + eventType: "Attached", + launchId: "launch", + accountProfile: "/fixture/profile", + attributionToken: issueAttributionToken("terminal-ended"), + }; + expect( + await caller.hook({ ...input, agent: { agentId: "claude" } }), + ).toMatchObject({ success: true, ignored: true }); + expect(captures).toBe(0); + expect(db.query.terminalAgentBindings.findFirst().sync()).toEqual(before); + expect( + await caller.hook({ + ...input, + agent: { agentId: "claude", sessionId: "native" }, + }), + ).toMatchObject({ success: true, ignored: false }); + expect(captures).toBe(1); + expect(ctx.terminalAgentStore.get("terminal-ended")?.agentSessionId).toBe( + "native", + ); + expect(ctx.terminalAgentStore.get("terminal-ended")?.account).toEqual( + account, + ); + }); + it("an unsigned or missing-launch hook cannot revive a consumed or disposed pinned row", async () => { + for (const reason of ["resumed", "disposed"] as const) { + const { ctx, db } = ended(reason); + const before = db.query.terminalAgentBindings.findFirst().sync(); + const result = await notificationsRouter.createCaller(ctx).hook({ + terminalId: "terminal-ended", + eventType: "Attached", + agent: { agentId: "claude", sessionId: "native" }, + }); + expect(result).toMatchObject({ success: true, ignored: true }); + expect(ctx.terminalAgentStore.get("terminal-ended")).toBeUndefined(); + expect(db.query.terminalAgentBindings.findFirst().sync()).toEqual(before); + } + }); +}); diff --git a/packages/host-service/src/trpc/router/notifications/notifications.ts b/packages/host-service/src/trpc/router/notifications/notifications.ts index 046d4755749..2737dc0f9ee 100644 --- a/packages/host-service/src/trpc/router/notifications/notifications.ts +++ b/packages/host-service/src/trpc/router/notifications/notifications.ts @@ -8,8 +8,16 @@ import { verifyAttributionToken } from "../../../terminal-agents/attribution-tok import { recordTerminalAgentTranscriptPath } from "../../../terminal-agents/persistence"; import { isTrustedTranscriptPath } from "../../../terminal-agents/transcript-path"; import { protectedProcedure, publicProcedure, router } from "../../index"; -import { captureSessionAccount } from "../usage/session-account/session-account"; +import { + captureSessionAccount, + sameSessionAccountContext, +} from "../usage/session-account/session-account"; +import { queueBackgroundSuccessorRefresh } from "./background-successor-adapter"; import { fanOutAgentLifecycle } from "./fan-out-agent-lifecycle"; +import { + captureNativeClaudeLaunch, + ingestNativeClaudeHook, +} from "./native-claude-usage"; import { showDesktopNotification } from "./show-desktop-notification"; // Hook scripts emit "" for unset env vars; we coerce to undefined so the @@ -35,7 +43,28 @@ const subagentInput = z }) .optional(); +const nativeClaudeUsageInput = z.object({ + session_id: z.string().min(1).max(256), + cost: z.object({ + total_api_duration_ms: z.number().finite().nonnegative().nullable(), + }), + rate_limits: z.object({ + five_hour: z + .object({ + used_percentage: z.number().finite().min(0).max(100), + resets_at: z.number().finite(), + }) + .optional(), + seven_day: z + .object({ + used_percentage: z.number().finite().min(0).max(100), + resets_at: z.number().finite(), + }) + .optional(), + }), +}); const hookInput = z.object({ + nativeClaudeUsage: nativeClaudeUsageInput.optional(), terminalId: z.string().optional(), eventType: z.string().optional(), agent: agentIdentityInput, @@ -72,131 +101,338 @@ function normalizeAgentIdentity( }; } -export const notificationsRouter = router({ - /** A notification sent with `superset notifications show`, shown by the attached desktop app. */ - show: protectedProcedure - .input(desktopNotificationSchema) - .mutation(({ ctx, input }) => showDesktopNotification(ctx, input)), - - /** - * Agent lifecycle hook. The shell hook POSTs here; we normalize, resolve - * the terminal's workspace, and fan out over the WS event bus. - * - * Intentionally unauthenticated: a caller can only trigger a chime, a - * sidebar indicator, and the idempotent forward-only "linked task → - * In Progress" nudge for a real workspace. Reusing the host-service PSK - * would leak it into every agent shell's env for zero practical gain. - */ - hook: publicProcedure.input(hookInput).mutation(async ({ ctx, input }) => { - const subagentId = trimOrUndefined(input.subagent?.id); - const eventType = subagentId ? undefined : mapEventType(input.eventType); - if (!subagentId && !eventType) { - return { success: true, ignored: true as const }; - } - - if (!input.terminalId || ctx.terminalAgentStore.hasChat(input.terminalId)) { - return { success: true, ignored: true as const }; - } - - const terminalSession = ctx.db.query.terminalSessions - .findFirst({ - where: eq(terminalSessions.id, input.terminalId), - columns: { originWorkspaceId: true }, - }) - .sync(); - if (!terminalSession?.originWorkspaceId) { - return { success: true, ignored: true as const }; - } - - const occurredAt = Date.now(); - - // Subagent activity is not the terminal's lifecycle: no chime, no - // status change, no session id capture. The roster change is fanned - // out as an invalidation so the sidebar refetches bindings. - if (subagentId) { - const agentType = trimOrUndefined(input.subagent?.type); - const recorded = ctx.terminalAgentStore.recordSubagentHook({ - terminalId: input.terminalId, - workspaceId: terminalSession.originWorkspaceId, - eventType: input.eventType ?? "", - subagentId, - ...(agentType ? { agentType } : {}), - hint: { +export function createNotificationsRouter( + captureAccount = captureSessionAccount, + backgroundRefresh = queueBackgroundSuccessorRefresh, +) { + return router({ + /** A notification sent with `superset notifications show`, shown by the attached desktop app. */ + show: protectedProcedure + .input(desktopNotificationSchema) + .mutation(({ ctx, input }) => showDesktopNotification(ctx, input)), + + /** + * Agent lifecycle hook. The shell hook POSTs here; we normalize, resolve + * the terminal's workspace, and fan out over the WS event bus. + * + * Intentionally unauthenticated: a caller can only trigger a chime, a + * sidebar indicator, and the idempotent forward-only "linked task → + * In Progress" nudge for a real workspace. Reusing the host-service PSK + * would leak it into every agent shell's env for zero practical gain. + */ + hook: publicProcedure.input(hookInput).mutation(async ({ ctx, input }) => { + if (input.nativeClaudeUsage) { + const terminalId = input.terminalId; + const sessionId = input.nativeClaudeUsage.session_id; + const launchId = trimOrUndefined(input.launchId); + if ( + process.env.SUPERSET_NATIVE_CLAUDE_USAGE !== "1" || + !terminalId || + !launchId || + input.subagent || + input.agent?.agentId !== "claude" || + input.agent.sessionId !== sessionId || + ctx.terminalAgentStore.hasChat(terminalId) || + !verifyAttributionToken(terminalId, input.attributionToken) + ) + return { success: true, ignored: true as const }; + const terminal = ctx.db.query.terminalSessions + .findFirst({ + where: eq(terminalSessions.id, terminalId), + columns: { originWorkspaceId: true }, + }) + .sync(); + const current = () => { + const binding = ctx.terminalAgentStore.getProvenance(terminalId); + return terminal?.originWorkspaceId && + binding?.workspaceId === terminal.originWorkspaceId + ? binding + : undefined; + }; + const accepted = await ingestNativeClaudeHook( + { terminalId, launchId, sessionId }, + input.nativeClaudeUsage, + current, + ).catch(() => false); + return { success: true, ignored: !accepted }; + } + const subagentId = trimOrUndefined(input.subagent?.id); + const eventType = subagentId ? undefined : mapEventType(input.eventType); + if (!subagentId && !eventType) { + return { success: true, ignored: true as const }; + } + + if ( + !input.terminalId || + ctx.terminalAgentStore.hasChat(input.terminalId) + ) { + return { success: true, ignored: true as const }; + } + + const terminalSession = ctx.db.query.terminalSessions + .findFirst({ + where: eq(terminalSessions.id, input.terminalId), + columns: { originWorkspaceId: true }, + }) + .sync(); + if (!terminalSession?.originWorkspaceId) { + return { success: true, ignored: true as const }; + } + + // An authenticated predecessor hook only triggers a fresh native read. + // Its old event, preview and receipt timestamp never become successor data. + const predecessor = ctx.terminalAgentStore.getProvenance( + input.terminalId, + ); + const predecessorAgent = normalizeAgentIdentity(input.agent); + if ( + predecessor?.endReason === "resumed" && + predecessor.agentId === "claude" && + predecessor.endedAt !== undefined && + predecessorAgent?.agentId === "claude" && + predecessorAgent.sessionId === predecessor.agentSessionId && + input.launchId === predecessor.launchId && + input.launchId && + predecessorAgent.sessionId && + verifyAttributionToken(input.terminalId, input.attributionToken) + ) { + const accepted = await backgroundRefresh(ctx, { + terminalId: input.terminalId, + launchId: input.launchId, + sessionId: predecessorAgent.sessionId, + attributionToken: input.attributionToken, + }).catch(() => false); + if (accepted) return { success: true, ignored: false as const }; + } + + const occurredAt = Date.now(); + + // Subagent activity is not the terminal's lifecycle: no chime, no + // status change, no session id capture. The roster change is fanned + // out as an invalidation so the sidebar refetches bindings. + if (subagentId) { + const agentType = trimOrUndefined(input.subagent?.type); + const recorded = ctx.terminalAgentStore.recordSubagentHook({ + terminalId: input.terminalId, + workspaceId: terminalSession.originWorkspaceId, + eventType: input.eventType ?? "", subagentId, - sessionId: trimOrUndefined(input.subagent?.sessionId), - transcriptPath: trimOrUndefined(input.subagent?.transcriptPath), - agentTranscriptPath: trimOrUndefined( - input.subagent?.agentTranscriptPath, - ), - }, - occurredAt, - }); - if (!recorded) { + ...(agentType ? { agentType } : {}), + hint: { + subagentId, + sessionId: trimOrUndefined(input.subagent?.sessionId), + transcriptPath: trimOrUndefined(input.subagent?.transcriptPath), + agentTranscriptPath: trimOrUndefined( + input.subagent?.agentTranscriptPath, + ), + }, + occurredAt, + }); + if (!recorded) { + return { success: true, ignored: true as const }; + } + ctx.eventBus.broadcastAgentBindingsChanged({ + workspaceId: terminalSession.originWorkspaceId, + occurredAt, + }); + return { success: true, ignored: false as const }; + } + if (!eventType) { return { success: true, ignored: true as const }; } - ctx.eventBus.broadcastAgentBindingsChanged({ - workspaceId: terminalSession.originWorkspaceId, - occurredAt, - }); - return { success: true, ignored: false as const }; - } - if (!eventType) { - return { success: true, ignored: true as const }; - } - - const agent = normalizeAgentIdentity(input.agent); - const preview = trimOrUndefined(input.preview); - - const prior = ctx.terminalAgentStore.get(input.terminalId); - const account = - verifyAttributionToken(input.terminalId, input.attributionToken) && - eventType === "Attached" && - input.accountProfile !== undefined && - (!prior?.account || - prior.agentId !== agent?.agentId || - (input.launchId && input.launchId !== prior.launchId) || - (agent?.sessionId && - prior.agentSessionId && - agent.sessionId !== prior.agentSessionId)) - ? await captureSessionAccount( + + const agent = normalizeAgentIdentity(input.agent); + const preview = trimOrUndefined(input.preview); + + const prior = ctx.terminalAgentStore.getProvenance(input.terminalId); + const verifiedAttribution = verifyAttributionToken( + input.terminalId, + input.attributionToken, + ); + if ( + (prior?.account?.pinned || prior?.accountInvalid) && + !verifiedAttribution && + (eventType === "Detached" || + (agent?.agentId && agent.agentId !== prior.agentId) || + (input.launchId && input.launchId !== prior.launchId) || + (agent?.sessionId && agent.sessionId !== prior.agentSessionId)) + ) + return { success: true, ignored: true as const }; + if ( + prior?.endedAt !== undefined && + (prior.account?.pinned || prior.accountInvalid) && + (!verifiedAttribution || + !agent?.sessionId || + !trimOrUndefined(input.launchId) || + ((prior.endReason === "resumed" || prior.endReason === "disposed") && + (prior.launchId === input.launchId || + prior.agentSessionId === agent?.sessionId))) + ) + return { success: true, ignored: true as const }; + const shouldCaptureAccount = + verifiedAttribution && + eventType === "Attached" && + input.accountProfile !== undefined && + (prior?.account?.pinned || + !prior?.account || + prior.agentId !== agent?.agentId || + (input.launchId && input.launchId !== prior.launchId) || + (agent?.sessionId && + prior.agentSessionId && + agent.sessionId !== prior.agentSessionId)); + let account = shouldCaptureAccount + ? await captureAccount( agent?.agentId, - input.accountProfile, + input.accountProfile as string, input.apiKey ?? false, ).catch(() => undefined) : undefined; - ctx.terminalAgentStore.recordEvent({ - account, - launchId: trimOrUndefined(input.launchId), - terminalId: input.terminalId, - workspaceId: terminalSession.originWorkspaceId, - eventType, - ...(agent?.agentId ? { agentId: agent.agentId } : {}), - ...(agent?.sessionId ? { agentSessionId: agent.sessionId } : {}), - ...(agent?.definitionId ? { definitionId: agent.definitionId } : {}), - occurredAt, - }); - const transcriptPath = trimOrUndefined(input.transcriptPath); - if ( - agent?.sessionId && - transcriptPath && - isTrustedTranscriptPath(transcriptPath) - ) { - recordTerminalAgentTranscriptPath(ctx.db, { + let binding = prior; + let metadataOnly = false; + if (shouldCaptureAccount) { + const current = ctx.terminalAgentStore.getProvenance(input.terminalId); + const sameOwner = prior + ? current && + current.workspaceId === prior.workspaceId && + current.endedAt === prior.endedAt && + current.endReason === prior.endReason && + current.agentId === prior.agentId && + current.launchId === prior.launchId && + current.definitionId === prior.definitionId && + current.startedAt === prior.startedAt && + (current.agentSessionId === prior.agentSessionId || + (prior.agentSessionId === undefined && + (!agent?.sessionId || + current.agentSessionId === agent.sessionId))) + : !current || + (input.launchId && + current.launchId === input.launchId && + current.agentId === agent?.agentId && + (!agent?.sessionId || + !current.agentSessionId || + current.agentSessionId === agent.sessionId)); + const unchangedAccount = + (!current?.account && !prior?.account) || + sameSessionAccountContext(current?.account, prior?.account) || + (!prior?.account && + sameSessionAccountContext(current?.account, account)) || + (prior?.account?.pinned && + current?.account?.pinned && + sameSessionAccountContext( + { ...current.account, conflict: prior.account.conflict }, + prior.account, + )); + if ( + !sameOwner || + !unchangedAccount || + current?.accountInvalid !== prior?.accountInvalid + ) + return { success: true, ignored: true as const }; + binding = current; + metadataOnly = + current !== undefined && + (current.lastEventAt !== prior?.lastEventAt || + current.lastEventType !== prior?.lastEventType || + current.agentSessionId !== prior?.agentSessionId); + if ( + metadataOnly && + ((agent?.agentId && agent.agentId !== current?.agentId) || + (input.launchId && input.launchId !== current?.launchId) || + (agent?.sessionId && + current?.agentSessionId && + agent.sessionId !== current.agentSessionId)) + ) + return { success: true, ignored: true as const }; + } + // A same-launch mismatch cannot downgrade a pin to default-account + // recovery. Retain the requested identity with a conflict marker instead. + // A genuinely new CLI in the shell gets its own unpinned attribution. + if ( + shouldCaptureAccount && + binding?.account?.pinned && + (!binding.launchId || binding.launchId === input.launchId) + ) { + const matches = + account && + binding.account.agent === account.agent && + binding.account.identity === account.identity && + binding.account.directory === account.directory; + account = + !account || matches + ? binding.account + : { ...binding.account, conflict: true }; + } + if (metadataOnly) { + ctx.terminalAgentStore.updateMetadata(input.terminalId, { + account, + agentSessionId: agent?.sessionId, + definitionId: agent?.definitionId, + }); + } else { + ctx.terminalAgentStore.recordEvent({ + account, + launchId: trimOrUndefined(input.launchId), + terminalId: input.terminalId, + workspaceId: terminalSession.originWorkspaceId, + eventType, + ...(agent?.agentId ? { agentId: agent.agentId } : {}), + ...(agent?.sessionId ? { agentSessionId: agent.sessionId } : {}), + ...(agent?.definitionId ? { definitionId: agent.definitionId } : {}), + occurredAt, + }); + } + + if ( + process.env.SUPERSET_NATIVE_CLAUDE_USAGE === "1" && + verifiedAttribution && + eventType === "Attached" && + agent?.agentId === "claude" && + agent.sessionId && + input.launchId + ) { + captureNativeClaudeLaunch( + { + terminalId: input.terminalId, + launchId: input.launchId, + sessionId: agent.sessionId, + }, + () => + ctx.terminalAgentStore.getProvenance(input.terminalId as string), + ); + } + const transcriptPath = trimOrUndefined(input.transcriptPath); + if ( + agent?.sessionId && + transcriptPath && + isTrustedTranscriptPath(transcriptPath) + ) { + recordTerminalAgentTranscriptPath(ctx.db, { + terminalId: input.terminalId, + agentSessionId: agent.sessionId, + transcriptPath, + }); + } + + if (metadataOnly) { + ctx.eventBus.broadcastAgentBindingsChanged({ + workspaceId: terminalSession.originWorkspaceId, + occurredAt, + }); + return { success: true, ignored: false as const }; + } + + fanOutAgentLifecycle(ctx, { + workspaceId: terminalSession.originWorkspaceId, + eventType, terminalId: input.terminalId, - agentSessionId: agent.sessionId, - transcriptPath, + ...(agent ? { agent } : {}), + ...(preview ? { preview } : {}), + occurredAt, }); - } - - fanOutAgentLifecycle(ctx, { - workspaceId: terminalSession.originWorkspaceId, - eventType, - terminalId: input.terminalId, - ...(agent ? { agent } : {}), - ...(preview ? { preview } : {}), - occurredAt, - }); - - return { success: true, ignored: false as const }; - }), -}); + + return { success: true, ignored: false as const }; + }), + }); +} + +export const notificationsRouter = createNotificationsRouter(); diff --git a/packages/host-service/src/trpc/router/terminal-agents/account-resume-history.test.ts b/packages/host-service/src/trpc/router/terminal-agents/account-resume-history.test.ts new file mode 100644 index 00000000000..0d2b924fc1e --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/account-resume-history.test.ts @@ -0,0 +1,264 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { + appendFile, + mkdir, + mkdtemp, + readdir, + realpath, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { SessionAccount } from "../usage/session-account/session-account"; +import { + inspectAccountResumeHistory, + sameAccountResumeHistory, +} from "./account-resume-history"; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all( + roots.splice(0).map((path) => rm(path, { recursive: true, force: true })), + ); +}); +const id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"; +async function fixture(provider: "claude" | "codex" = "claude") { + const temporary = await mkdtemp( + join(tmpdir(), "superset-account-resume-history-"), + ); + roots.push(temporary); + const root = await realpath(temporary); + const cwd = join(root, "workspace"); + const shared = join(root, "shared"); + const lock = join(root, "locks"); + const sourceDir = join(root, "source"); + const targetDir = join(root, "target"); + await Promise.all( + [cwd, shared, lock, sourceDir, targetDir].map((path) => mkdir(path)), + ); + for (const dir of [sourceDir, targetDir]) { + await symlink( + shared, + join(dir, provider === "claude" ? "projects" : "sessions"), + ); + if (provider === "codex") + await symlink(lock, join(dir, "thread-writer-locks")); + } + const project = join( + shared, + provider === "claude" ? "project" : "2026/10/09", + ); + await mkdir(project, { recursive: true }); + const file = join( + project, + provider === "claude" + ? `${id}.jsonl` + : `rollout-2026-10-09T10-10-10-${id}.jsonl`, + ); + const record = + provider === "claude" + ? { + type: "user", + sessionId: id, + cwd, + message: { role: "user", content: "synthetic" }, + uuid: "11111111-2222-3333-4444-555555555555", + } + : { type: "session_meta", payload: { id, cwd } }; + await writeFile( + file, + `${JSON.stringify(record)}\n${provider === "codex" ? `${JSON.stringify({ type: "response_item", payload: { type: "message", role: "user", content: [{ type: "input_text", text: "synthetic" }] } })}\n` : ""}`, + ); + const source: SessionAccount = { + agent: provider, + selection: sourceDir, + directory: sourceDir, + identity: "a".repeat(64), + credentialKind: "subscription", + }; + const target = { + ...source, + selection: targetDir, + directory: targetDir, + identity: "b".repeat(64), + }; + return { + root, + shared, + file, + record, + source, + target, + input: { source, target, sessionId: id, cwd }, + }; +} + +describe("exact shared history required for account resume", () => { + test.each([ + "claude", + "codex", + ] as const)("accepts one exact %s transcript in the shared store without copying it", async (provider) => { + const f = await fixture(provider); + const before = await readdir(f.shared, { recursive: true }); + const first = await inspectAccountResumeHistory(f.input); + expect(first.path).toBe(await realpath(f.file)); + expect(first.size).toBeGreaterThan(0); + expect( + sameAccountResumeHistory( + first, + await inspectAccountResumeHistory(f.input), + ), + ).toBe(true); + expect(await readdir(f.shared, { recursive: true })).toEqual(before); + }); + + test("rejects a different recorded worktree", async () => { + const f = await fixture(); + await writeFile(f.file, JSON.stringify({ ...f.record, cwd: f.root })); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "unavailable or ambiguous", + ); + }); + + test("rejects an ID that exists only in a filename", async () => { + const f = await fixture(); + await writeFile( + f.file, + JSON.stringify({ ...f.record, sessionId: "other-id" }), + ); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "unavailable or ambiguous", + ); + }); + + test("rejects two exact Claude transcript copies even when the working folder matches", async () => { + const f = await fixture(); + const other = join(f.shared, "other-project"); + await mkdir(other); + await writeFile(join(other, `${id}.jsonl`), JSON.stringify(f.record)); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "unavailable or ambiguous", + ); + }); + + test("rejects independent profile stores without copying a transcript", async () => { + const f = await fixture(); + const alias = join(f.target.directory, "projects"); + await rm(alias); + await mkdir(alias); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "Shared conversation history", + ); + expect(await readdir(alias)).toEqual([]); + }); + + test("rejects Codex profiles with separate native writer-lock directories", async () => { + const f = await fixture("codex"); + const alias = join(f.target.directory, "thread-writer-locks"); + await rm(alias); + await mkdir(alias); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "Shared conversation history", + ); + }); + + test("rejects compressed Codex history alongside the uncompressed record", async () => { + const f = await fixture("codex"); + await writeFile(`${f.file}.zst`, "synthetic compressed marker"); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "unavailable or ambiguous", + ); + }); + + test("rejects a nested transcript symlink instead of trusting an unchecked location", async () => { + const f = await fixture(); + const other = join(f.root, "elsewhere.jsonl"); + await writeFile(other, JSON.stringify(f.record)); + await rm(f.file); + await symlink(other, f.file); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "unavailable or ambiguous", + ); + }); + + test("detects history growth between the initial check and launch", async () => { + const f = await fixture(); + const before = await inspectAccountResumeHistory(f.input); + await appendFile(f.file, `${JSON.stringify(f.record)}\n`); + expect( + sameAccountResumeHistory( + before, + await inspectAccountResumeHistory(f.input), + ), + ).toBe(false); + }); + + test("rejects traversal syntax in a saved native ID", async () => { + const f = await fixture(); + await expect( + inspectAccountResumeHistory({ ...f.input, sessionId: "../other" }), + ).rejects.toThrow("unavailable or ambiguous"); + }); + test.each([ + "foreign", + "truncated", + "worker", + ])("rejects a %s record after a matching initial message", async (kind) => { + const f = await fixture(); + const suffix = + kind === "truncated" + ? '{"type":' + : JSON.stringify({ + ...f.record, + ...(kind === "foreign" + ? { sessionId: "99999999-2222-3333-4444-555555555555" } + : { isSidechain: true }), + }); + await appendFile(f.file, `${suffix}\n`); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "unavailable or ambiguous", + ); + }); + test("ignores Claude session sidecars when finding the main transcript", async () => { + const f = await fixture(); + const deep = join(f.shared, "project", id, "subagents"); + await mkdir(deep, { recursive: true }); + await writeFile( + join(deep, `${id}.jsonl`), + JSON.stringify({ ...f.record, isSidechain: true }), + ); + expect((await inspectAccountResumeHistory(f.input)).path).toBe( + await realpath(f.file), + ); + }); + + test("does not hide an ambiguous Codex copy in a deeper directory", async () => { + const f = await fixture("codex"); + const deep = join(f.shared, "extra/nested/level"); + await mkdir(deep, { recursive: true }); + await writeFile( + join(deep, `rollout-duplicate-${id}.jsonl`), + JSON.stringify(f.record), + ); + await expect(inspectAccountResumeHistory(f.input)).rejects.toThrow( + "unavailable or ambiguous", + ); + }); +}); + +test("worker refusal retains the public precondition error without transcript details", async () => { + const { file, input } = await fixture(); + await writeFile(file, "{private synthetic invalid content}\n"); + try { + await inspectAccountResumeHistory(input); + throw new Error("Expected refusal"); + } catch (error) { + expect(error).toMatchObject({ + code: "PRECONDITION_FAILED", + message: + "The exact saved conversation is unavailable or ambiguous in the selected account. Shared conversation history is required. Nothing was launched.", + }); + } +}); diff --git a/packages/host-service/src/trpc/router/terminal-agents/account-resume-history.ts b/packages/host-service/src/trpc/router/terminal-agents/account-resume-history.ts new file mode 100644 index 00000000000..8c5e8038724 --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/account-resume-history.ts @@ -0,0 +1,81 @@ +import { isAbsolute } from "node:path"; +import { TRPCError } from "@trpc/server"; +import { + type AccountResumeHistory, + assertNativeResumeHistoryCurrent, +} from "../../../terminal-agents/saved-conversations/inspect-native-history"; +import { getHostWorkerPool } from "../../../workers/host-worker-pool"; +import { inspectSavedConversationTask } from "../../../workers/tasks/harness"; +import type { SessionAccount } from "../usage/session-account/session-account"; + +export type { AccountResumeHistory } from "../../../terminal-agents/saved-conversations/inspect-native-history"; + +function refuse(): never { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The exact saved conversation is unavailable or ambiguous in the selected account. Shared conversation history is required. Nothing was launched.", + }); +} + +export async function inspectAccountResumeHistory(input: { + source: SessionAccount; + target: SessionAccount; + sessionId: string; + cwd: string; + previous?: AccountResumeHistory; +}): Promise { + const { source, target, sessionId, cwd } = input; + if ( + !source.directory || + !target.directory || + !isAbsolute(source.directory) || + !isAbsolute(target.directory) || + source.agent !== target.agent || + !/^[\w-]+$/.test(sessionId) + ) + refuse(); + try { + const evidence = await getHostWorkerPool().run( + inspectSavedConversationTask, + { + provider: source.agent, + sourceDirectory: source.directory, + targetDirectory: target.directory, + sessionId, + cwd, + ...(input.previous ? { previous: input.previous } : {}), + }, + ); + if (!evidence) refuse(); + return evidence; + } catch { + refuse(); + } +} + +export function sameAccountResumeHistory( + left: AccountResumeHistory, + right: AccountResumeHistory, +): boolean { + return ( + left.path === right.path && + left.device === right.device && + left.inode === right.inode && + left.size === right.size && + left.modifiedAt === right.modifiedAt && + left.changedAt === right.changedAt && + left.sha256 === right.sha256 && + JSON.stringify(left.storeBindings) === JSON.stringify(right.storeBindings) + ); +} + +export function assertAccountResumeHistoryCurrent( + history: AccountResumeHistory, +): void { + try { + assertNativeResumeHistoryCurrent(history); + } catch { + refuse(); + } +} diff --git a/packages/host-service/src/trpc/router/terminal-agents/account-resume-processes.test.ts b/packages/host-service/src/trpc/router/terminal-agents/account-resume-processes.test.ts new file mode 100644 index 00000000000..e60b14eeab7 --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/account-resume-processes.test.ts @@ -0,0 +1,198 @@ +import { Database } from "bun:sqlite"; +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import type { HostDb } from "../../../db"; +import * as schema from "../../../db/schema"; +import { terminalSessions } from "../../../db/schema"; +import { + assertAccountResumeTerminalIdle, + assertNoRecordedClaudeWriter, +} from "./account-resume-processes"; + +const directories: string[] = []; +const databases: Database[] = []; +afterEach(async () => { + for (const db of databases.splice(0)) db.close(); + await Promise.all( + directories + .splice(0) + .map((path) => rm(path, { recursive: true, force: true })), + ); +}); +const startedAt = "Fri Oct 9 10:00:00 2026"; +async function writerFixture( + record: unknown = { + sessionId: "exact-id", + pid: 123, + procStart: startedAt, + pidDomain: process.platform, + }, +) { + const directory = await mkdtemp( + join(tmpdir(), "superset-account-resume-process-"), + ); + directories.push(directory); + await mkdir(join(directory, "sessions")); + await writeFile(join(directory, "sessions/123.json"), JSON.stringify(record)); + return { sessionId: "exact-id", directories: [directory], directory }; +} +function terminalFixture() { + const sqlite = new Database(":memory:"); + databases.push(sqlite); + const db = drizzle(sqlite, { schema }) as unknown as HostDb; + migrate(db as never, { + migrationsFolder: resolve(import.meta.dir, "../../../../drizzle"), + }); + db.insert(terminalSessions) + .values({ + id: "source", + status: "active", + originWorkspaceId: "workspace", + createdAt: 1, + }) + .run(); + return db; +} + +describe("known native writer detection", () => { + test("rejects a process with matching native ID, PID and start identity", async () => { + await expect( + assertNoRecordedClaudeWriter( + await writerFixture(), + async () => new Map([[123, startedAt]]), + ), + ).rejects.toThrow("still open"); + }); + test("refuses a live matching PID when its birth timestamp cannot be compared", async () => { + await expect( + assertNoRecordedClaudeWriter( + await writerFixture(), + async () => new Map([[123, "Fri Oct 9 11:00:00 2026"]]), + ), + ).rejects.toThrow("still open"); + }); + test("accepts a dead recorded writer without deleting its registry record", async () => { + const input = await writerFixture(); + await expect( + assertNoRecordedClaudeWriter(input, async () => new Map()), + ).resolves.toBeUndefined(); + expect( + (await stat(join(input.directory, "sessions/123.json"))).isFile(), + ).toBe(true); + }); + test("ignores a different native conversation", async () => { + const input = await writerFixture({ + sessionId: "different", + pid: 123, + procStart: startedAt, + pidDomain: process.platform, + }); + await expect( + assertNoRecordedClaudeWriter(input, async (pids) => { + expect(pids).toEqual([]); + return new Map([[123, startedAt]]); + }), + ).resolves.toBeUndefined(); + }); + test.each([ + null, + { sessionId: "exact-id", pid: 123 }, + { + sessionId: "exact-id", + pid: 456, + procStart: startedAt, + pidDomain: process.platform, + }, + ])("refuses malformed ownership evidence", async (record) => { + await expect( + assertNoRecordedClaudeWriter( + await writerFixture(record), + async () => new Map(), + ), + ).rejects.toThrow("exit could not be verified"); + }); + test("propagates a failed process inventory rather than treating it as empty", async () => { + await expect( + assertNoRecordedClaudeWriter(await writerFixture(), async () => { + throw new Error("inventory failed"); + }), + ).rejects.toThrow("inventory failed"); + }); +}); + +describe("source terminal remains intact", () => { + test("allows an idle shell and leaves its session row unchanged", async () => { + const db = terminalFixture(); + const before = db.select().from(terminalSessions).all(); + await expect( + assertAccountResumeTerminalIdle(db, "source", "workspace", { + listSessions: async () => [{ id: "source", pid: 12, alive: true }], + foregroundGroups: async () => "12 12\n", + }), + ).resolves.toBeUndefined(); + expect(db.select().from(terminalSessions).all()).toEqual(before); + }); + test.each([ + "13 12", + "-1 12", + "garbage", + "12", + "", + ])("refuses non-idle or unavailable process groups: %s", async (groups) => { + await expect( + assertAccountResumeTerminalIdle( + terminalFixture(), + "source", + "workspace", + { + listSessions: async () => [{ id: "source", pid: 12, alive: true }], + foregroundGroups: async () => groups, + }, + ), + ).rejects.toThrow("exit could not be verified"); + }); + test("allows a missing daemon session only after a successful inventory", async () => { + await expect( + assertAccountResumeTerminalIdle( + terminalFixture(), + "source", + "workspace", + { + listSessions: async () => [], + foregroundGroups: async () => { + throw new Error("must not inspect"); + }, + }, + ), + ).resolves.toBeUndefined(); + }); + test("refuses an unavailable daemon inventory", async () => { + await expect( + assertAccountResumeTerminalIdle( + terminalFixture(), + "source", + "workspace", + { + listSessions: async () => { + throw new Error("offline"); + }, + foregroundGroups: async () => "12 12", + }, + ), + ).rejects.toThrow("exit could not be verified"); + }); + test("refuses a source that belongs to another workspace", async () => { + await expect( + assertAccountResumeTerminalIdle( + terminalFixture(), + "source", + "wrong-workspace", + { listSessions: async () => [], foregroundGroups: async () => "12 12" }, + ), + ).rejects.toThrow("exit could not be verified"); + }); +}); diff --git a/packages/host-service/src/trpc/router/terminal-agents/account-resume-processes.ts b/packages/host-service/src/trpc/router/terminal-agents/account-resume-processes.ts new file mode 100644 index 00000000000..1a298d7b982 --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/account-resume-processes.ts @@ -0,0 +1,152 @@ +import { execFile } from "node:child_process"; +import { readdir, realpath } from "node:fs/promises"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { TRPCError } from "@trpc/server"; +import { eq } from "drizzle-orm"; +import type { HostDb } from "../../../db"; +import { terminalSessions } from "../../../db/schema"; +import { getDaemonClient } from "../../../terminal/daemon-client-singleton"; +import { + processStartFingerprint, + readProcessStarts, +} from "../../../terminal-agents/claude-session-writers"; +import { readProfileFile } from "../usage/profile-file"; + +const execFileAsync = promisify(execFile); + +function refuse(): never { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The previous agent's exit could not be verified. Exit it normally before choosing another account. Nothing was launched.", + }); +} + +interface IdleTerminalDeps { + listSessions: () => Promise< + Array<{ id: string; alive: boolean; pid: number }> + >; + foregroundGroups: (pid: number) => Promise; +} +const idleTerminalDeps: IdleTerminalDeps = { + listSessions: async () => (await getDaemonClient()).list(), + foregroundGroups: async (pid) => + ( + await execFileAsync( + "/bin/ps", + ["-o", "tpgid=", "-o", "pgid=", "-p", String(pid)], + { timeout: 2000, maxBuffer: 4096 }, + ) + ).stdout, +}; + +export async function assertAccountResumeTerminalIdle( + db: HostDb, + terminalId: string, + workspaceId: string, + deps: IdleTerminalDeps = idleTerminalDeps, +): Promise { + const terminal = db + .select() + .from(terminalSessions) + .where(eq(terminalSessions.id, terminalId)) + .get(); + if ( + !terminal || + terminal.originWorkspaceId !== workspaceId || + (terminal.disposeRequestedAt !== null && terminal.status !== "disposed") + ) + refuse(); + try { + const session = (await deps.listSessions()).find( + (item) => item.id === terminalId && item.alive, + ); + if (!session) return; + const groups = (await deps.foregroundGroups(session.pid)) + .trim() + .split(/\s+/) + .map(Number); + if ( + groups.length !== 2 || + groups.some((group) => !Number.isSafeInteger(group) || group <= 0) || + groups[0] !== groups[1] + ) + refuse(); + } catch { + refuse(); + } +} + +export async function readAccountResumeProcessStarts( + pids: number[], +): Promise> { + try { + return await readProcessStarts(pids); + } catch { + refuse(); + } +} + +/** + * Native Claude records detect known writers; they are not an exclusive lock. + * procStart has no documented timezone, so a live matching PID is conservatively + * refused even when its birth text differs. PID reuse must not look like proof. + */ +export async function assertNoRecordedClaudeWriter( + input: { sessionId: string; directories: string[] }, + processStarts = readAccountResumeProcessStarts, +): Promise { + if (process.platform !== "darwin" && process.platform !== "linux") refuse(); + const roots = new Set(); + const records: Array<{ pid: number; start: string }> = []; + let visited = 0; + for (const directory of new Set(input.directories)) { + let root: string; + try { + root = await realpath(join(directory, "sessions")); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + refuse(); + } + if (roots.has(root)) continue; + roots.add(root); + for (const entry of await readdir(root, { withFileTypes: true })) { + if (++visited > 1024) refuse(); + if (!/^\d+\.json$/.test(entry.name)) continue; + if (!entry.isFile()) refuse(); + const file = await readProfileFile(join(root, entry.name), 64 * 1024); + if (!file) refuse(); + let record: Record; + try { + record = JSON.parse(file.content); + } catch { + refuse(); + } + if (!record || typeof record.sessionId !== "string") refuse(); + if (record.sessionId !== input.sessionId) continue; + const start = processStartFingerprint(record.procStart); + const pid = record.pid; + if ( + typeof pid !== "number" || + !Number.isSafeInteger(pid) || + pid <= 0 || + pid > 2_147_483_647 || + entry.name !== `${pid}.json` || + !start || + record.pidDomain !== process.platform + ) + refuse(); + records.push({ pid, start }); + } + } + const starts = await processStarts([ + ...new Set(records.map((record) => record.pid)), + ]); + if (records.some((record) => starts.has(record.pid))) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "This conversation is still open in another Claude process. Exit it normally before choosing another account. Nothing was launched.", + }); +} diff --git a/packages/host-service/src/trpc/router/terminal-agents/background-reconnect-adapter.test.ts b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect-adapter.test.ts new file mode 100644 index 00000000000..40d0ee7b0b0 --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect-adapter.test.ts @@ -0,0 +1,652 @@ +import { Database } from "bun:sqlite"; +import { afterEach, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { eq } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import type { HostDb } from "../../../db"; +import * as schema from "../../../db/schema"; +import { + hostAgentConfigs, + terminalAgentBindings, + terminalSessions, + workspaces, +} from "../../../db/schema"; +import { + SqliteTerminalAgentBindingPersistence, + TerminalAgentStore, +} from "../../../terminal-agents"; +import type { ClaudeBackgroundAttachProof } from "../../../terminal-agents/claude-background-session"; +import type { NativeClaudeTerminalClient } from "../../../terminal-agents/native-claude-process"; +import { createBackgroundReconnect } from "./background-reconnect"; +import { + backgroundAttachmentCommand, + backgroundReconnectAdapter, + backgroundReconnectSource, +} from "./background-reconnect-adapter"; +import { accountResumeSource } from "./resume-account"; + +const databases: Database[] = []; +afterEach(() => { + for (const database of databases.splice(0)) database.close(); +}); +function fixture() { + const sqlite = new Database(":memory:"); + databases.push(sqlite); + const db = drizzle(sqlite, { schema }) as unknown as HostDb; + migrate(db as never, { + migrationsFolder: resolve(import.meta.dir, "../../../../drizzle"), + }); + db.insert(workspaces) + .values({ + id: "workspace", + worktreePath: "/fixture/project", + branch: "main", + }) + .run(); + db.insert(hostAgentConfigs) + .values({ + id: "custom:fixture", + presetId: "claude", + label: "Claude", + command: "claude", + promptTransport: "argv", + resumeArgsJson: '["--resume"]', + displayOrder: 0, + }) + .run(); + db.insert(terminalSessions) + .values({ + id: "original", + originWorkspaceId: "workspace", + status: "exited", + createdAt: 1, + }) + .run(); + const account = { + pinned: true as const, + agent: "claude" as const, + selection: "/fixture/profile", + directory: "/fixture/profile", + credentialKind: "subscription" as const, + identity: "a".repeat(64), + }; + const sessionId = "11111111-2222-4333-8444-555555555555"; + db.insert(terminalAgentBindings) + .values({ + terminalId: "original", + workspaceId: "workspace", + agentId: "claude", + definitionId: "custom:fixture", + launchId: "fixture-original-launch", + agentSessionId: sessionId, + accountJson: JSON.stringify(account), + startedAt: 1, + lastEventAt: 2, + lastEventType: "Stop", + endedAt: 3, + endReason: "terminal-exited", + }) + .run(); + type Context = Parameters[0]; + const events: unknown[] = []; + const ctx: Context = { + db, + organizationId: "fixture-org", + eventBus: { + broadcastTerminalLifecycle: (event: unknown) => { + events.push(event); + }, + } as Context["eventBus"], + terminalAgentStore: new TerminalAgentStore( + new SqliteTerminalAgentBindingPersistence(db), + ), + }; + const selection = { workspaceId: "workspace", terminalId: "original" }; + const source = backgroundReconnectSource(ctx, selection); + if (!source) throw new Error("Missing fixture source"); + const input = { ...selection, expectedRevision: source.revision }; + const adapter = backgroundReconnectAdapter(ctx); + const worker = { + pid: 123, + birth: "worker-birth", + executable: "/fixture/claude", + configDir: account.directory, + worktreePath: "/fixture/project", + sessionId, + backgroundId: "aabbccdd", + }; + const proof: ClaudeBackgroundAttachProof = { + target: { + sessionId, + configDir: account.directory, + worktreePath: "/fixture/project", + }, + candidate: { + id: "aabbccdd", + name: "Fixture exact worker", + sessionId, + cwd: "/fixture/project", + startedAt: 1, + state: "done", + status: "idle", + pid: 123, + }, + workerBefore: worker, + workerAfter: worker, + attachArgs: ["attach", "aabbccdd"], + observedAt: 2, + nonAtomicAttach: true, + }; + const client: NativeClaudeTerminalClient = { + pid: 501, + parentPid: 500, + uid: 501, + birth: "client-birth", + executable: worker.executable, + cwd: "/fixture/project", + configDir: account.directory, + args: [], + ancestors: [{ pid: 500, parentPid: 1, uid: 501, birth: "root-birth" }], + }; + const original = () => + db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, "original")) + .get(); + return { + db, + ctx, + account, + sessionId, + adapter, + input, + proof, + client, + original, + events, + }; +} + +test("a reservation survives a new adapter with the same original revision and target", () => { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + const queued = f.adapter.reserve(source, "attachment"); + expect(queued.expectedRevision).toBe(f.input.expectedRevision); + expect(backgroundReconnectAdapter(f.ctx).read(f.input)).toEqual(queued); + expect(f.original()?.endReason).toStartWith("background-attach:queued:"); + const started = f.adapter.authorize(queued); + expect(started.reservation).toEqual({ + terminalId: "attachment", + authorized: true, + }); + f.adapter.unclaim(started); + expect(f.original()?.endReason).toStartWith("background-attach:started:"); +}); + +test("unclaim cannot overwrite a source changed by another actor", () => { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + const queued = f.adapter.reserve(source, "attachment"); + f.db + .update(terminalAgentBindings) + .set({ agentSessionId: "replacement" }) + .where(eq(terminalAgentBindings.terminalId, "original")) + .run(); + f.adapter.unclaim(queued); + expect(f.original()?.agentSessionId).toBe("replacement"); + expect(f.original()?.resumedIntoTerminalId).toBe("attachment"); +}); + +test("a config or sibling ownership change cannot consume the source", () => { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + f.db + .update(hostAgentConfigs) + .set({ argsJson: '["--model","changed"]' }) + .where(eq(hostAgentConfigs.id, "custom:fixture")) + .run(); + expect(() => f.adapter.reserve(source, "attachment")).toThrow( + "could not be verified", + ); + expect(f.original()?.endReason).toBe("terminal-exited"); +}); + +test("synthetic native admission adopts one exact SQLite successor and preserves its durable provenance", async () => { + const f = fixture(); + let creates = 0; + f.adapter.verifyAccount = async () => f.account; + f.adapter.assertIdle = async () => {}; + f.adapter.prove = async () => f.proof; + f.adapter.attachArgs = async () => ["attach", "Fixture exact worker"]; + f.adapter.create = async (request) => { + creates++; + await request.beforeInitialCommand(); + f.db + .insert(terminalSessions) + .values({ + id: request.terminalId, + originWorkspaceId: "workspace", + status: "active", + createdAt: 4, + }) + .run(); + request.onInitialCommandReady(); + }; + f.adapter.admission = async () => ({ + rootPid: 500, + client: f.client, + bytes: new TextEncoder().encode( + "Session aabbccdd · Fixture exact worker\n", + ), + }); + f.adapter.uuid = () => "attachment"; + const reconnect = createBackgroundReconnect(f.adapter); + expect(await reconnect(f.input)).toMatchObject({ + reconnected: true, + confirmed: true, + terminalId: "attachment", + }); + const target = f.db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, "attachment")) + .get(); + expect(target?.agentSessionId).toBe(f.sessionId); + expect(JSON.parse(target?.accountJson ?? "null")).toEqual(f.account); + expect(f.original()).toMatchObject({ + endReason: "resumed", + resumedIntoTerminalId: "attachment", + }); + expect(f.ctx.terminalAgentStore.getProvenance("original")?.endReason).toBe( + "resumed", + ); + expect(f.ctx.terminalAgentStore.get("attachment")?.account?.identity).toBe( + f.account.identity, + ); + expect(await reconnect(f.input)).toMatchObject({ + attachmentPending: true, + terminalId: "attachment", + }); + expect(creates).toBe(1); + expect(f.events).toHaveLength(1); +}); + +test("a wrong destination workspace is never adopted or written", () => { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + const queued = f.adapter.reserve(source, "attachment"); + const started = f.adapter.authorize(queued); + f.db + .insert(terminalSessions) + .values({ + id: "attachment", + originWorkspaceId: "different-workspace", + status: "active", + createdAt: 4, + }) + .run(); + expect(() => f.adapter.commit(started, f.proof, f.client)).toThrow( + "could not be verified", + ); + expect(f.original()?.endReason).toStartWith("background-attach:started:"); + expect( + f.db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, "attachment")) + .get(), + ).toBeUndefined(); +}); + +// Continue's saved-history fallback must use the identical immutable source. +test("background and exact saved-history recovery share the unreserved source revision", () => { + const f = fixture(); + expect(accountResumeSource(f.db, f.input)?.revision).toBe( + f.input.expectedRevision, + ); +}); + +test("ordinary Claude configurations outside attachment scope keep normal Continue available", () => { + const custom = fixture(); + custom.db + .update(hostAgentConfigs) + .set({ argsJson: '["--model","custom-model"]' }) + .where(eq(hostAgentConfigs.id, "custom:fixture")) + .run(); + expect(backgroundReconnectSource(custom.ctx, custom.input)).toBeNull(); + expect(() => custom.adapter.read(custom.input)).toThrow( + "could not be verified", + ); + + const api = fixture(); + api.db + .update(terminalAgentBindings) + .set({ + accountJson: JSON.stringify({ + ...api.account, + pinned: undefined, + credentialKind: "api_key", + }), + }) + .where(eq(terminalAgentBindings.terminalId, "original")) + .run(); + expect(backgroundReconnectSource(api.ctx, api.input)).toBeNull(); + expect(() => api.adapter.read(api.input)).toThrow("could not be verified"); +}); + +test("discovery never hides an invalid or now-unsupported pending attachment", () => { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + f.adapter.authorize(f.adapter.reserve(source, "attachment")); + f.db + .update(hostAgentConfigs) + .set({ argsJson: '["--model","changed"]' }) + .where(eq(hostAgentConfigs.id, "custom:fixture")) + .run(); + expect(() => backgroundReconnectSource(f.ctx, f.input)).toThrow( + "could not be verified", + ); +}); + +test("a failed owned attachment's known terminal exit restores the original recovery revision", async () => { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + const started = f.adapter.authorize(f.adapter.reserve(source, "attachment")); + f.db + .insert(terminalSessions) + .values({ + id: "attachment", + originWorkspaceId: "workspace", + status: "exited", + createdAt: 4, + endedAt: 5, + }) + .run(); + const restarted = backgroundReconnectAdapter(f.ctx, { + listSessions: async () => [], + }); + const recovered = await restarted.reconcileExitedReservation?.(started); + expect(recovered).toEqual(source); + expect(f.original()?.endReason).toBe("terminal-exited"); + expect(f.original()?.resumedIntoTerminalId).toBeNull(); + expect(accountResumeSource(f.db, f.input)?.ready).toBe(true); + expect(f.events).toEqual([]); +}); + +test("unknown daemon state or a live attachment never releases an authorized reservation", async () => { + for (const live of [null, [{ id: "attachment", alive: true }]]) { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + const started = f.adapter.authorize( + f.adapter.reserve(source, "attachment"), + ); + f.db + .insert(terminalSessions) + .values({ + id: "attachment", + originWorkspaceId: "workspace", + status: "exited", + createdAt: 4, + endedAt: 5, + }) + .run(); + const adapter = backgroundReconnectAdapter(f.ctx, { + listSessions: async () => live, + }); + expect(await adapter.reconcileExitedReservation?.(started)).toEqual( + started, + ); + expect(f.original()?.endReason).toStartWith("background-attach:started:"); + } +}); + +test("an alive or differently owned terminal cannot be treated as an exited attachment", async () => { + for (const destination of [ + { status: "active", originWorkspaceId: "workspace" }, + { status: "exited", originWorkspaceId: "different-workspace" }, + ]) { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + const started = f.adapter.authorize( + f.adapter.reserve(source, "attachment"), + ); + f.db + .insert(terminalSessions) + .values({ id: "attachment", ...destination, createdAt: 4 }) + .run(); + const adapter = backgroundReconnectAdapter(f.ctx, { + listSessions: async () => [], + }); + expect(await adapter.reconcileExitedReservation?.(started)).toEqual( + started, + ); + expect(f.original()?.resumedIntoTerminalId).toBe("attachment"); + } +}); + +test("a source or terminal changed during the exit probe cannot be reclaimed", async () => { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing source"); + const started = f.adapter.authorize(f.adapter.reserve(source, "attachment")); + f.db + .insert(terminalSessions) + .values({ + id: "attachment", + originWorkspaceId: "workspace", + status: "exited", + createdAt: 4, + endedAt: 5, + }) + .run(); + const adapter = backgroundReconnectAdapter(f.ctx, { + listSessions: async () => { + f.db + .update(terminalSessions) + .set({ status: "active" }) + .where(eq(terminalSessions.id, "attachment")) + .run(); + return []; + }, + }); + await expect(adapter.reconcileExitedReservation?.(started)).rejects.toThrow( + "could not be verified", + ); + expect(f.original()?.endReason).toStartWith("background-attach:started:"); +}); + +test("a dedicated attachment exits its view with the child's status and quoted argv", () => { + const root = mkdtempSync(join(tmpdir(), "attachment-view-exit-")); + try { + const cli = join(root, "fixture cli's"); + writeFileSync( + cli, + '#!/bin/sh\nprintf "%s|%s|%s" "$1" "$2" "$CLAUDE_CONFIG_DIR"\nexit 23\n', + { mode: 0o700 }, + ); + const f = fixture(); + const name = "worker's exact name; no shell expansion"; + const command = backgroundAttachmentCommand(f.account, cli, [ + "attach", + name, + ]); + for (const shell of ["/bin/sh", "/bin/bash", "/bin/zsh"]) { + if (!existsSync(shell)) continue; + const result = spawnSync( + shell, + ["-c", `${command}\nprintf SHOULD_NOT_RUN`], + { + encoding: "utf8", + env: { PATH: process.env.PATH, HOME: root }, + }, + ); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(23); + expect(result.stdout).toBe(`attach|${name}|${f.account.directory}`); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("Continue retries an exited failed view and adopts the same live worker without manual shell closure", async () => { + const f = fixture(); + const adapter = backgroundReconnectAdapter(f.ctx, { + listSessions: async () => [], + }); + let creates = 0; + let now = 0; + adapter.verifyAccount = async () => f.account; + adapter.assertIdle = async () => {}; + adapter.prove = async () => f.proof; + adapter.attachArgs = async () => ["attach", "Fixture exact worker"]; + adapter.uuid = () => (creates === 0 ? "failed-view" : "working-view"); + adapter.now = () => now; + adapter.wait = async () => { + now += 100; + }; + adapter.create = async (request) => { + creates++; + await request.beforeInitialCommand(); + f.db + .insert(terminalSessions) + .values({ + id: request.terminalId, + originWorkspaceId: "workspace", + status: "active", + createdAt: 4, + }) + .run(); + request.onInitialCommandReady(); + if (creates === 1) + f.db + .update(terminalSessions) + .set({ status: "exited", endedAt: 5 }) + .where(eq(terminalSessions.id, request.terminalId)) + .run(); + }; + adapter.admission = async () => + creates === 1 + ? null + : { + rootPid: 500, + client: f.client, + bytes: new TextEncoder().encode( + "Session aabbccdd · Fixture exact worker\n", + ), + }; + const reconnect = createBackgroundReconnect(adapter); + await expect(reconnect(f.input)).resolves.toMatchObject({ + attachmentPending: true, + terminalId: "failed-view", + }); + await expect(reconnect(f.input)).resolves.toMatchObject({ + reconnected: true, + confirmed: true, + terminalId: "working-view", + }); + expect(creates).toBe(2); + expect(f.original()?.resumedIntoTerminalId).toBe("working-view"); + expect( + f.db + .select() + .from(terminalSessions) + .where(eq(terminalSessions.id, "failed-view")) + .get()?.status, + ).toBe("exited"); + expect( + f.db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, "working-view")) + .get()?.agentSessionId, + ).toBe(f.sessionId); + expect(f.events).toHaveLength(1); +}); + +test("an unmarked account-resume reservation is not offered as background attachment", () => { + for (const reason of ["detached", "terminal-exited", "disposed"]) { + const f = fixture(); + f.db + .update(terminalAgentBindings) + .set({ endReason: `account-resume-preparing:${reason}` }) + .where(eq(terminalAgentBindings.terminalId, "original")) + .run(); + expect(backgroundReconnectSource(f.ctx, f.input)).toBeNull(); + expect(() => f.adapter.read(f.input)).toThrow("could not be verified"); + } +}); + +test("verified native admission adopts an early matching hook but refuses conflicting provenance", () => { + for (const kind of [ + "unattributed-hook", + "matching-account", + "wrong-session", + "wrong-account", + ]) { + const f = fixture(); + const source = f.adapter.read(f.input); + if (!source) throw new Error("Missing fixture source"); + const started = f.adapter.authorize( + f.adapter.reserve(source, "attachment"), + ); + f.db + .insert(terminalSessions) + .values({ + id: "attachment", + originWorkspaceId: "workspace", + status: "active", + createdAt: 4, + }) + .run(); + f.db + .insert(terminalAgentBindings) + .values({ + terminalId: "attachment", + workspaceId: "workspace", + agentId: "claude", + agentSessionId: + kind === "wrong-session" ? "another-session" : f.sessionId, + accountJson: + kind === "unattributed-hook" + ? null + : JSON.stringify( + kind === "wrong-account" + ? { ...f.account, identity: "b".repeat(64) } + : f.account, + ), + startedAt: 4, + lastEventAt: 5, + lastEventType: "SessionStart", + }) + .run(); + if (kind.startsWith("wrong")) { + expect(() => f.adapter.commit(started, f.proof, f.client)).toThrow( + "could not be verified", + ); + expect(f.original()?.endReason).toStartWith("background-attach:started:"); + } else { + expect(f.adapter.commit(started, f.proof, f.client)).toMatchObject({ + reconnected: true, + terminalId: "attachment", + }); + expect( + f.ctx.terminalAgentStore.get("attachment")?.account?.identity, + ).toBe(f.account.identity); + expect(f.original()?.endReason).toBe("resumed"); + } + } +}); diff --git a/packages/host-service/src/trpc/router/terminal-agents/background-reconnect-adapter.ts b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect-adapter.ts new file mode 100644 index 00000000000..b89eff92d97 --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect-adapter.ts @@ -0,0 +1,687 @@ +import { execFile } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { realpath } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { isDeepStrictEqual, promisify } from "node:util"; +import { buildArgvCommand } from "@superset/shared/agent-prompt-launch"; +import { and, eq, isNull, like, ne, or } from "drizzle-orm"; +import { getSupervisor } from "../../../daemon"; +import { + terminalAgentBindings, + terminalSessions, + workspaces, +} from "../../../db/schema"; +import { + createTerminalSessionInternal, + readFreshTerminalAdmission, +} from "../../../terminal/terminal"; +import { resolveHostAgentConfig } from "../../../terminal-agents/agent-config"; +import { + backgroundAdoptionLaunchId, + backgroundWorkerBirthHash, +} from "../../../terminal-agents/background-adoption"; +import { + discoverClaudeBackgroundSession, + liveClaudeAttachmentName, + supportsLiveClaudeAttachment, +} from "../../../terminal-agents/claude-background-session"; +import { findClaudeSessionWriters } from "../../../terminal-agents/claude-session-writers"; +import { + findNativeClaudeTerminalClient, + observeNativeClaudeProcess, + resolveTrustedNativeClaudeExecutable, +} from "../../../terminal-agents/native-claude-process"; +import type { HostServiceContext } from "../../../types"; +import { validateAccountAuthRouting } from "../agents/account-auth-routing"; +import { + accountLaunchUnsupportedReason, + pinnedAccountCommandPrefix, + pinnedAccountEnv, + resolveLaunchAccount, +} from "../agents/launch-account"; +import { + parsePersistedSessionAccount, + type SessionAccount, +} from "../usage/session-account/session-account"; +import { assertAccountResumeTerminalIdle } from "./account-resume-processes"; +import { + type BackgroundReconnectInput, + type BackgroundReconnectIO, + type BackgroundReconnectSource, + createBackgroundReconnect, +} from "./background-reconnect"; + +type Context = Pick< + HostServiceContext, + "db" | "eventBus" | "terminalAgentStore" | "organizationId" +>; +const execute = promisify(execFile); +const PREFIX = "background-attach:"; +const AUTH_OVERRIDES = [ + "CLAUDE_CONFIG_DIR", + "SUPERSET_DEFAULT_CLAUDE_CONFIG_DIR", + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "ANTHROPIC_CUSTOM_HEADERS", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", + "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + "CLAUDE_CODE_USE_ANTHROPIC_AWS", + "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", +]; +function refuse(): never { + throw new Error( + "The exact background conversation changed or could not be verified. Nothing was restarted.", + ); +} +function hash(value: unknown) { + return createHash("sha256").update(JSON.stringify(value)).digest("hex"); +} +function context( + ctx: Context, + input: BackgroundReconnectInput, + discovery = false, +) { + const binding = ctx.db + .select() + .from(terminalAgentBindings) + .where( + and( + eq(terminalAgentBindings.terminalId, input.terminalId), + eq(terminalAgentBindings.workspaceId, input.workspaceId), + ), + ) + .get(); + if ( + !binding || + binding.agentId !== "claude" || + !binding.agentSessionId || + !binding.launchId + ) + return null; + const workspace = ctx.db + .select({ path: workspaces.worktreePath }) + .from(workspaces) + .where( + and(eq(workspaces.id, input.workspaceId), isNull(workspaces.archivedAt)), + ) + .get(); + const config = resolveHostAgentConfig( + ctx.db, + binding.definitionId ?? binding.agentId, + ); + const account = parsePersistedSessionAccount(binding.accountJson); + if ( + !workspace || + !config || + config.presetId !== "claude" || + accountLaunchUnsupportedReason(config) || + !account?.directory || + account.agent !== "claude" || + account.conflict || + account.credentialKind !== "subscription" + ) { + if (discovery && !binding.endReason?.startsWith(PREFIX)) return null; + return refuse(); + } + const marker = binding.endReason?.startsWith(PREFIX) + ? binding.endReason.slice(PREFIX.length).split(":") + : null; + if (binding.endReason === "resumed") return null; + if ( + marker && + (marker.length !== 3 || + !["queued", "started"].includes(marker[0] ?? "") || + !/^[a-f0-9]{64}$/.test(marker[2] ?? "")) + ) + return refuse(); + const originalReason = marker + ? marker[1] === "none" + ? null + : (marker[1] ?? refuse()) + : binding.endReason; + if ( + originalReason !== null && + !["detached", "terminal-exited", "disposed"].includes(originalReason) + ) { + if (discovery && !marker) return null; + return refuse(); + } + const original = marker + ? { ...binding, endReason: originalReason, resumedIntoTerminalId: null } + : binding; + const expectedRevision = hash([original, workspace, config]); + if (marker && marker[2] !== expectedRevision) return refuse(); + const source: BackgroundReconnectSource = { + workspaceId: input.workspaceId, + terminalId: input.terminalId, + expectedRevision, + sessionId: binding.agentSessionId, + account, + cwd: workspace.path, + label: config.label, + ...(marker && binding.resumedIntoTerminalId + ? { + reservation: { + terminalId: binding.resumedIntoTerminalId, + authorized: marker[0] === "started", + }, + } + : {}), + }; + if (marker && !source.reservation) return refuse(); + return { binding, workspace, config, source, originalReason }; +} +function selectedEnvironment(source: BackgroundReconnectSource) { + const env = { ...process.env }; + for (const key of Object.keys(env)) + if (AUTH_OVERRIDES.includes(key) || key.startsWith("CLAUDE_CODE_USE_")) + delete env[key]; + return { ...env, ...pinnedAccountEnv(source.account) }; +} +async function run( + cli: string, + args: string[], + source: BackgroundReconnectSource, + signal?: AbortSignal, +) { + return ( + await execute(cli, args, { + env: selectedEnvironment(source), + cwd: source.cwd, + signal, + timeout: 1_500, + maxBuffer: 256 * 1024, + encoding: "utf8", + }) + ).stdout; +} + +export async function supportsBackgroundReconnect(): Promise { + if (process.platform !== "darwin" && process.platform !== "linux") + return false; + try { + const cli = await resolveTrustedNativeClaudeExecutable( + join(homedir(), ".local/bin/claude"), + ); + const output = await execute(cli, ["--version"], { + timeout: 1_500, + maxBuffer: 4_096, + encoding: "utf8", + }); + return supportsLiveClaudeAttachment(output.stdout); + } catch { + return false; + } +} + +export function backgroundReconnectSource( + ctx: Context, + input: { workspaceId: string; terminalId: string }, +) { + const source = context(ctx, { ...input, expectedRevision: "" }, true)?.source; + return source + ? { provider: "claude" as const, revision: source.expectedRevision } + : null; +} + +export function backgroundAttachmentCommand( + account: SessionAccount, + executable: string, + args: readonly ["attach", string], +): string { + const command = `${buildArgvCommand([executable, ...args])}; exit "$?"`; + return `exec ${pinnedAccountCommandPrefix(account, {})}${buildArgvCommand(["/bin/sh", "-c", command])}`; +} + +export function backgroundReconnectAdapter( + ctx: Context, + dependencies: { + listSessions?: () => Promise | null>; + } = {}, +): BackgroundReconnectIO { + const listSessions = + dependencies.listSessions ?? + (() => getSupervisor().listSessions(ctx.organizationId, 1_500)); + const requireSource = (source: BackgroundReconnectSource) => { + const current = context(ctx, source); + if (!current || !isDeepStrictEqual(current.source, source)) return refuse(); + return current; + }; + const account = async (source: BackgroundReconnectSource) => { + const current = requireSource(source); + const target = await resolveLaunchAccount(current.config, source.account); + await validateAccountAuthRouting(target, source.cwd); + if ( + (await realpath(target.directory as string)) !== + (await realpath(source.account.directory as string)) + ) + return refuse(); + return target; + }; + const adapter: BackgroundReconnectIO = { + read: (input) => context(ctx, input)?.source ?? null, + successor(input) { + const prior = ctx.db + .select() + .from(terminalAgentBindings) + .where( + and( + eq(terminalAgentBindings.terminalId, input.terminalId), + eq(terminalAgentBindings.workspaceId, input.workspaceId), + ), + ) + .get(); + if (prior?.endReason !== "resumed" || !prior.resumedIntoTerminalId) + return null; + const successor = ctx.db + .select() + .from(terminalAgentBindings) + .where( + and( + eq(terminalAgentBindings.terminalId, prior.resumedIntoTerminalId), + eq(terminalAgentBindings.workspaceId, input.workspaceId), + ), + ) + .get(); + const priorAccount = parsePersistedSessionAccount(prior.accountJson); + const successorAccount = + successor && parsePersistedSessionAccount(successor.accountJson); + const terminal = + successor && + ctx.db + .select() + .from(terminalSessions) + .where(eq(terminalSessions.id, successor.terminalId)) + .get(); + if ( + !successor || + successor.endedAt !== null || + !terminal || + terminal.originWorkspaceId !== input.workspaceId || + terminal.status !== "active" || + terminal.disposeRequestedAt !== null || + !priorAccount || + !successorAccount || + successor.agentId !== "claude" || + successor.agentSessionId !== prior.agentSessionId || + !isDeepStrictEqual(successorAccount, priorAccount) + ) + return null; + return { + reconnected: false, + attachmentPending: true, + terminalId: successor.terminalId, + label: "Claude", + }; + }, + verifyAccount: account, + assertIdle: (source) => + assertAccountResumeTerminalIdle( + ctx.db, + source.terminalId, + source.workspaceId, + ), + async prove(source, signal) { + const profile = await realpath(source.account.directory as string); + const cwd = await realpath(source.cwd); + const cli = await resolveTrustedNativeClaudeExecutable( + join(homedir(), ".local/bin/claude"), + ); + return discoverClaudeBackgroundSession( + { sessionId: source.sessionId, configDir: profile, worktreePath: cwd }, + { + signal, + runDiscovery: (request) => + run(cli, [...request.args], source, request.signal), + validateScope: async () => { + await account(source); + return isDeepStrictEqual(context(ctx, source)?.source, source); + }, + verifyWorker: async (expected, signal) => { + const worker = await observeNativeClaudeProcess(expected.pid, { + signal, + }); + if ( + worker.configDir !== profile || + worker.cwd !== cwd || + !( + await findClaudeSessionWriters({ + sessionId: source.sessionId, + directories: [profile], + }) + ).includes(worker.pid) + ) + return null; + return { + pid: worker.pid, + birth: worker.birth, + executable: worker.executable, + configDir: profile, + worktreePath: cwd, + sessionId: source.sessionId, + backgroundId: expected.backgroundId, + }; + }, + }, + ); + }, + async attachArgs(proof, source, signal) { + const cli = await resolveTrustedNativeClaudeExecutable( + proof.workerAfter.executable, + ); + const env = selectedEnvironment(source); + const options = { + env, + signal, + cwd: proof.target.worktreePath, + timeout: 1_500, + maxBuffer: 256 * 1024, + encoding: "utf8" as const, + }; + const version = await execute(cli, ["--version"], options); + const all = await execute(cli, ["agents", "--json"], options); + return [ + "attach", + liveClaudeAttachmentName(all.stdout, proof.candidate, version.stdout), + ]; + }, + reserve(source, terminalId) { + ctx.db.transaction(() => { + const current = requireSource(source); + if (source.reservation) return refuse(); + const other = ctx.db + .select({ terminalId: terminalAgentBindings.terminalId }) + .from(terminalAgentBindings) + .where( + and( + eq(terminalAgentBindings.agentId, "claude"), + eq(terminalAgentBindings.agentSessionId, source.sessionId), + ne(terminalAgentBindings.terminalId, source.terminalId), + or( + isNull(terminalAgentBindings.endedAt), + like( + terminalAgentBindings.endReason, + "account-resume-preparing:%", + ), + like(terminalAgentBindings.endReason, `${PREFIX}%`), + ), + ), + ) + .get(); + if (other) return refuse(); + ctx.db + .update(terminalAgentBindings) + .set({ + endReason: `${PREFIX}queued:${current.originalReason ?? "none"}:${source.expectedRevision}`, + resumedIntoTerminalId: terminalId, + }) + .where(eq(terminalAgentBindings.terminalId, source.terminalId)) + .run(); + }); + return context(ctx, source)?.source ?? refuse(); + }, + assertReserved: (source) => { + if (!requireSource(source).source.reservation) return refuse(); + }, + authorize(source) { + const current = requireSource(source); + if (!source.reservation) return refuse(); + ctx.db + .update(terminalAgentBindings) + .set({ + endReason: `${PREFIX}started:${current.originalReason ?? "none"}:${source.expectedRevision}`, + }) + .where(eq(terminalAgentBindings.terminalId, source.terminalId)) + .run(); + return context(ctx, source)?.source ?? refuse(); + }, + unclaim(source) { + let current: ReturnType; + try { + current = context(ctx, source); + } catch { + return; + } + if ( + !current || + !isDeepStrictEqual(current.source, source) || + source.reservation?.authorized + ) + return; + ctx.db + .update(terminalAgentBindings) + .set({ endReason: current.originalReason, resumedIntoTerminalId: null }) + .where(eq(terminalAgentBindings.terminalId, source.terminalId)) + .run(); + }, + async reconcileExitedReservation(source, signal) { + const current = requireSource(source); + const terminalId = source.reservation?.terminalId; + if (!terminalId || !source.reservation?.authorized || signal?.aborted) + return source; + const terminal = ctx.db + .select() + .from(terminalSessions) + .where(eq(terminalSessions.id, terminalId)) + .get(); + if ( + !terminal || + terminal.originWorkspaceId !== source.workspaceId || + !["exited", "disposed"].includes(terminal.status) + ) + return source; + const sessions = await listSessions(); + if ( + signal?.aborted || + !sessions || + sessions.some((row) => row.id === terminalId && row.alive) + ) + return source; + ctx.db.transaction(() => { + requireSource(source); + const latest = ctx.db + .select() + .from(terminalSessions) + .where(eq(terminalSessions.id, terminalId)) + .get(); + const bound = ctx.db + .select({ terminalId: terminalAgentBindings.terminalId }) + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, terminalId)) + .get(); + if (!isDeepStrictEqual(latest, terminal) || bound) return refuse(); + ctx.db + .update(terminalAgentBindings) + .set({ + endReason: current.originalReason, + resumedIntoTerminalId: null, + }) + .where(eq(terminalAgentBindings.terminalId, source.terminalId)) + .run(); + }); + return context(ctx, source)?.source ?? refuse(); + }, + async create(input) { + const result = await createTerminalSessionInternal({ + terminalId: input.terminalId, + workspaceId: input.source.workspaceId, + db: ctx.db, + eventBus: ctx.eventBus, + initialCommand: backgroundAttachmentCommand( + input.source.account, + input.executable, + input.args, + ), + beforeInitialCommand: input.beforeInitialCommand, + onInitialCommandReady: input.onInitialCommandReady, + }); + if ("error" in result) throw new Error(result.error); + }, + async admission(source, terminalId, signal) { + if (signal?.aborted) return null; + const sessions = await getSupervisor().listSessions( + ctx.organizationId, + 1_500, + ); + if (signal?.aborted) return null; + if (!sessions) return null; + const row = sessions.find((item) => item.id === terminalId && item.alive); + if (!row) return null; + const client = await findNativeClaudeTerminalClient(row.pid, { signal }); + const bytes = readFreshTerminalAdmission({ + terminalId, + workspaceId: source.workspaceId, + }); + return client && bytes ? { rootPid: row.pid, client, bytes } : null; + }, + commit(source, proof, client) { + const terminalId = source.reservation?.terminalId; + if (!terminalId) return refuse(); + const now = Date.now(); + const current = requireSource(source); + if (!current.binding.launchId) return refuse(); + const launchId = backgroundAdoptionLaunchId({ + source: { + terminalId: source.terminalId, + workspaceId: source.workspaceId, + launchId: current.binding.launchId, + sessionId: source.sessionId, + account: source.account, + definitionId: current.binding.definitionId, + startedAt: current.binding.startedAt, + }, + terminalId, + cwd: proof.target.worktreePath, + adoptedAt: now, + worker: { + pid: proof.workerAfter.pid, + birthHash: backgroundWorkerBirthHash(proof.workerAfter.birth), + }, + }); + ctx.db.transaction(() => { + requireSource(source); + const terminal = ctx.db + .select() + .from(terminalSessions) + .where(eq(terminalSessions.id, terminalId)) + .get(); + if ( + !terminal || + terminal.originWorkspaceId !== source.workspaceId || + terminal.status !== "active" || + terminal.disposeRequestedAt !== null || + client.configDir !== proof.target.configDir || + client.cwd !== proof.target.worktreePath + ) + return refuse(); + const existing = ctx.db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, terminalId)) + .get(); + if ( + existing && + (existing.workspaceId !== source.workspaceId || + existing.agentId !== "claude" || + existing.agentSessionId !== source.sessionId || + existing.endedAt !== null || + existing.endReason !== null || + existing.resumedIntoTerminalId !== null || + (existing.definitionId !== null && + existing.definitionId !== current.binding.definitionId) || + (existing.launchId !== null && existing.launchId !== launchId) || + (existing.accountJson !== null && + !isDeepStrictEqual( + parsePersistedSessionAccount(existing.accountJson), + source.account, + ))) + ) + return refuse(); + const adopted = { + terminalId, + workspaceId: source.workspaceId, + agentId: "claude" as const, + agentSessionId: source.sessionId, + definitionId: current.binding.definitionId, + launchId, + accountJson: JSON.stringify(source.account), + startedAt: existing?.startedAt ?? now, + lastEventAt: now, + lastEventType: "Attached", + }; + if (existing) + ctx.db + .update(terminalAgentBindings) + .set(adopted) + .where(eq(terminalAgentBindings.terminalId, terminalId)) + .run(); + else ctx.db.insert(terminalAgentBindings).values(adopted).run(); + ctx.db + .update(terminalAgentBindings) + .set({ + endedAt: now, + endReason: "resumed", + resumedIntoTerminalId: terminalId, + }) + .where(eq(terminalAgentBindings.terminalId, source.terminalId)) + .run(); + }); + ctx.terminalAgentStore.recordEvent({ + terminalId: source.terminalId, + workspaceId: source.workspaceId, + eventType: "Detached", + occurredAt: now, + }); + ctx.terminalAgentStore.recordEvent({ + terminalId, + workspaceId: source.workspaceId, + agentId: "claude", + agentSessionId: source.sessionId, + account: source.account, + launchId, + eventType: "Attached", + occurredAt: now, + }); + ctx.eventBus.broadcastTerminalLifecycle({ + workspaceId: source.workspaceId, + terminalId: source.terminalId, + eventType: "resumed", + resumedTerminalId: terminalId, + label: source.label, + occurredAt: now, + }); + return { + reconnected: true, + confirmed: true, + terminalId, + label: source.label, + }; + }, + now: Date.now, + uuid: randomUUID, + wait: () => new Promise((resolve) => setTimeout(resolve, 75)), + }; + return adapter; +} + +const reconnectors = new WeakMap< + Context["db"], + ReturnType +>(); +export function reconnectTerminalBackgroundSession( + ctx: Context, + input: BackgroundReconnectInput, +) { + let reconnect = reconnectors.get(ctx.db); + if (!reconnect) { + reconnect = createBackgroundReconnect(backgroundReconnectAdapter(ctx)); + reconnectors.set(ctx.db, reconnect); + } + return reconnect(input); +} diff --git a/packages/host-service/src/trpc/router/terminal-agents/background-reconnect.test.ts b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect.test.ts new file mode 100644 index 00000000000..f3e828d462c --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect.test.ts @@ -0,0 +1,391 @@ +import { expect, test } from "bun:test"; +import type { ClaudeBackgroundAttachProof } from "../../../terminal-agents/claude-background-session"; +import { + admitsBackgroundAttachment, + type BackgroundReconnectIO, + type BackgroundReconnectResult, + type BackgroundReconnectSource, + createBackgroundReconnect, +} from "./background-reconnect"; + +function fixture() { + const sessionId = "11111111-2222-4333-8444-555555555555"; + const account = { + agent: "claude" as const, + selection: "/fixture/profile", + directory: "/fixture/profile", + identity: "a".repeat(64), + credentialKind: "subscription" as const, + }; + let source: BackgroundReconnectSource = { + workspaceId: "workspace", + terminalId: "original", + expectedRevision: "revision", + sessionId, + account, + cwd: "/fixture/project", + label: "Claude", + }; + const input = { + workspaceId: source.workspaceId, + terminalId: source.terminalId, + expectedRevision: source.expectedRevision, + }; + const worker = { + pid: 123, + birth: "birth-a", + executable: "/fixture/claude", + configDir: account.directory, + worktreePath: source.cwd, + sessionId, + backgroundId: "aabbccdd", + }; + const proof: ClaudeBackgroundAttachProof = { + target: { + sessionId, + configDir: account.directory, + worktreePath: source.cwd, + }, + candidate: { + id: "aabbccdd", + sessionId, + name: "Exact worker", + cwd: source.cwd, + startedAt: 100, + state: "working", + status: "busy", + pid: worker.pid, + }, + workerBefore: worker, + workerAfter: worker, + attachArgs: ["attach", "aabbccdd"], + observedAt: 100, + nonAtomicAttach: true, + }; + const ancestor = { pid: 500, parentPid: 1, birth: "root-birth", uid: 501 }; + const client = { + pid: 501, + parentPid: 500, + birth: "client-birth", + uid: 501, + executable: worker.executable, + cwd: source.cwd, + configDir: account.directory, + args: [], + ancestors: [ancestor], + }; + let now = 100; + let saved: BackgroundReconnectResult | null = null; + let bytes = new TextEncoder().encode( + "Session aabbccdd · Exact worker\r\n\x1b[?1049hUI", + ); + let creates = 0; + let commits = 0; + let unclaims = 0; + const commands: unknown[] = []; + const io: BackgroundReconnectIO = { + read: () => structuredClone(source), + successor: () => saved, + verifyAccount: async () => ({ ...account, pinned: true }), + assertIdle: async () => {}, + prove: async () => structuredClone(proof), + attachArgs: async () => ["attach", "Exact worker"], + reserve: (expected, terminalId) => { + expect(source).toEqual(expected); + source = { ...source, reservation: { terminalId, authorized: false } }; + return structuredClone(source); + }, + assertReserved: (expected) => { + expect(source).toEqual(expected); + }, + authorize: (expected) => { + expect(source).toEqual(expected); + if (!source.reservation) throw new Error("Expected reservation"); + source = { + ...source, + reservation: { ...source.reservation, authorized: true }, + }; + return structuredClone(source); + }, + unclaim: (expected) => { + if (JSON.stringify(source) !== JSON.stringify(expected)) return; + unclaims++; + const { reservation: _reservation, ...rest } = source; + source = rest; + }, + create: async (request) => { + creates++; + commands.push(request.args); + await request.beforeInitialCommand(); + request.onInitialCommandReady(); + }, + admission: async () => ({ rootPid: ancestor.pid, client, bytes }), + commit: (expected) => { + expect(source).toEqual(expected); + commits++; + saved = { + reconnected: true, + confirmed: true, + terminalId: "attachment", + label: "Claude", + }; + return saved; + }, + now: () => now, + uuid: () => "attachment", + wait: async () => { + now += 100; + }, + }; + return { + io, + input, + proof, + client, + commands, + setBytes(value: string) { + bytes = new TextEncoder().encode(value); + }, + changeSource() { + source = { ...source, expectedRevision: "changed" }; + }, + counts: () => ({ creates, commits, unclaims }), + }; +} + +test("Continue attaches the exact live worker and atomically records its existing identity without a prompt", async () => { + const f = fixture(); + const reconnect = createBackgroundReconnect(f.io); + const [first, second] = await Promise.all([ + reconnect(f.input), + reconnect(f.input), + ]); + expect(first).toEqual({ + reconnected: true, + confirmed: true, + terminalId: "attachment", + label: "Claude", + }); + expect(second).toEqual(first); + expect(f.commands).toEqual([["attach", "Exact worker"]]); + expect(f.counts()).toEqual({ creates: 1, commits: 1, unclaims: 0 }); + expect(await reconnect(f.input)).toEqual(first); + expect(f.counts().creates).toBe(1); +}); + +test("a pending native view is reused after a lost reply instead of opening another client", async () => { + const f = fixture(); + f.setBytes(""); + const reconnect = createBackgroundReconnect(f.io); + expect(await reconnect(f.input)).toMatchObject({ + reconnected: false, + attachmentPending: true, + terminalId: "attachment", + }); + f.setBytes("Session aabbccdd · Exact worker\n"); + expect(await reconnect(f.input)).toMatchObject({ + reconnected: true, + confirmed: true, + }); + expect(f.counts()).toEqual({ creates: 1, commits: 1, unclaims: 0 }); +}); + +test("an account or source change before launch refuses without consuming its replacement", async () => { + const f = fixture(); + f.io.verifyAccount = async () => ({ + ...f.proof.target, + agent: "claude", + directory: "/other/profile", + selection: "/other/profile", + identity: "b".repeat(64), + credentialKind: "subscription", + }); + await expect(createBackgroundReconnect(f.io)(f.input)).rejects.toThrow( + "could not be verified", + ); + expect(f.counts().creates).toBe(0); +}); + +test("a worker incarnation change during preflight cannot launch a client", async () => { + const f = fixture(); + const create = f.io.create; + f.io.create = async (input) => { + f.proof.workerAfter = { ...f.proof.workerAfter, birth: "reused-pid" }; + return create(input); + }; + await expect(createBackgroundReconnect(f.io)(f.input)).rejects.toThrow( + "could not be verified", + ); + expect(f.counts()).toEqual({ creates: 1, commits: 0, unclaims: 1 }); +}); + +test("a changed client or wrong admission banner cannot be adopted", async () => { + const f = fixture(); + f.setBytes("Session wrong · Other worker\n"); + const result = await createBackgroundReconnect(f.io)(f.input); + expect(result).toMatchObject({ reconnected: false, attachmentPending: true }); + expect(f.counts().commits).toBe(0); +}); + +test("a source replaced after command authorization is left intact and never adopted", async () => { + const f = fixture(); + const create = f.io.create; + f.io.create = async (input) => { + await create(input); + f.changeSource(); + }; + await expect(createBackgroundReconnect(f.io)(f.input)).rejects.toThrow( + "could not be verified", + ); + expect(f.counts().commits).toBe(0); + expect(f.counts().unclaims).toBe(0); +}); + +test("no exact running background match leaves ordinary resume to its guarded caller", async () => { + const f = fixture(); + f.io.prove = async () => null; + expect(await createBackgroundReconnect(f.io)(f.input)).toEqual({ + reconnected: false, + }); + expect(f.counts().creates).toBe(0); +}); + +test("only fresh initial native banners before alternate screen can prove admission", () => { + const encode = (value: string) => new TextEncoder().encode(value); + expect( + admitsBackgroundAttachment( + encode("Session aabbccdd · Exact\n\x1b[?1049hUI"), + "aabbccdd", + ), + ).toBe(true); + expect( + admitsBackgroundAttachment( + encode("\x1b[?1049hSession aabbccdd · transcript text"), + "aabbccdd", + ), + ).toBe(false); + expect( + admitsBackgroundAttachment( + encode("Session aabbccdd · Exact\nSession other · Wrong\n"), + "aabbccdd", + ), + ).toBe(false); + expect( + admitsBackgroundAttachment(new Uint8Array(16 * 1024 + 1), "aabbccdd"), + ).toBe(false); +}); + +test("a deadline aborts late proof and cannot authorize a delayed command", async () => { + const f = fixture(); + let fire: (() => void) | undefined; + let release: + | ((value: ClaudeBackgroundAttachProof | null) => void) + | undefined; + f.io.schedule = (callback, milliseconds) => { + expect(milliseconds).toBe(12_000); + fire = callback; + return () => {}; + }; + f.io.prove = async () => + new Promise((resolve) => { + release = resolve; + }); + const work = createBackgroundReconnect(f.io)(f.input); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + if (!fire) throw new Error("Expected deadline"); + fire(); + await expect(work).rejects.toThrow("timed out"); + if (release) release(f.proof); + await Promise.resolve(); + await Promise.resolve(); + expect(f.counts()).toEqual({ creates: 0, commits: 0, unclaims: 0 }); +}); + +test("separate controllers share one native conversation claim", async () => { + const f = fixture(); + let release: + | ((value: ClaudeBackgroundAttachProof | null) => void) + | undefined; + const original = f.io.prove; + f.io.prove = async () => + new Promise((resolve) => { + release = resolve; + }); + const one = createBackgroundReconnect(f.io)(f.input); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + await expect(createBackgroundReconnect(f.io)(f.input)).rejects.toThrow( + "already opening", + ); + f.io.prove = original; + if (!release) throw new Error("Expected proof wait"); + release(f.proof); + expect(await one).toMatchObject({ reconnected: true }); +}); + +test("normal UI output growth cannot invalidate the same fresh native admission", async () => { + const f = fixture(); + const admission = f.io.admission; + let reads = 0; + f.io.admission = async (...args) => { + const result = await admission(...args); + if (++reads > 1 && result) + return { + ...result, + bytes: new TextEncoder().encode( + "Session aabbccdd · Exact worker\n\x1b[?1049hNew UI output", + ), + }; + return result; + }; + expect(await createBackgroundReconnect(f.io)(f.input)).toMatchObject({ + reconnected: true, + confirmed: true, + }); + expect(f.counts().commits).toBe(1); +}); + +test("a retry replaces only a failed attachment after verified exit, without closing the worker", async () => { + const f = fixture(); + f.setBytes(""); + const reconnect = createBackgroundReconnect(f.io); + await expect(reconnect(f.input)).resolves.toMatchObject({ + attachmentPending: true, + }); + let reconciled = 0; + f.io.reconcileExitedReservation = async (source) => { + reconciled++; + if (!source.reservation?.authorized) + throw new Error("Expected authorized view"); + f.io.unclaim(source); + const replacement = f.io.read(f.input); + if (!replacement) throw new Error("Expected original source"); + return replacement; + }; + f.setBytes("Session aabbccdd · Exact worker\n"); + await expect(reconnect(f.input)).resolves.toMatchObject({ + reconnected: true, + confirmed: true, + }); + expect(reconciled).toBe(1); + expect(f.counts()).toEqual({ creates: 2, commits: 1, unclaims: 1 }); + expect(f.commands).toEqual([ + ["attach", "Exact worker"], + ["attach", "Exact worker"], + ]); +}); + +test("an unknown attachment exit keeps the same authorized view pending", async () => { + const f = fixture(); + f.setBytes(""); + const reconnect = createBackgroundReconnect(f.io); + await reconnect(f.input); + f.io.reconcileExitedReservation = async (source) => source; + await expect(reconnect(f.input)).resolves.toMatchObject({ + attachmentPending: true, + }); + expect(f.counts()).toEqual({ creates: 1, commits: 0, unclaims: 0 }); +}); diff --git a/packages/host-service/src/trpc/router/terminal-agents/background-reconnect.ts b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect.ts new file mode 100644 index 00000000000..dca842eee5b --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/background-reconnect.ts @@ -0,0 +1,355 @@ +import { isDeepStrictEqual, stripVTControlCharacters } from "node:util"; +import type { ClaudeBackgroundAttachProof } from "../../../terminal-agents/claude-background-session"; +import type { NativeClaudeTerminalClient } from "../../../terminal-agents/native-claude-process"; +import { claimNativeSession } from "../../../terminal-agents/native-session-lease"; +import type { SessionAccount } from "../usage/session-account/session-account"; + +export interface BackgroundReconnectInput { + workspaceId: string; + terminalId: string; + expectedRevision: string; +} +export interface BackgroundReconnectSource extends BackgroundReconnectInput { + sessionId: string; + account: SessionAccount; + cwd: string; + label: string; + reservation?: { terminalId: string; authorized: boolean }; +} +export type BackgroundReconnectResult = + | { reconnected: false } + | { + reconnected: true; + confirmed: true; + terminalId: string; + label: string; + } + | { + reconnected: false; + attachmentPending: true; + terminalId: string; + label: string; + }; +export interface BackgroundReconnectIO { + read(input: BackgroundReconnectInput): BackgroundReconnectSource | null; + successor(input: BackgroundReconnectInput): BackgroundReconnectResult | null; + verifyAccount( + source: BackgroundReconnectSource, + signal?: AbortSignal, + ): Promise; + assertIdle( + source: BackgroundReconnectSource, + signal?: AbortSignal, + ): Promise; + prove( + source: BackgroundReconnectSource, + signal?: AbortSignal, + ): Promise; + attachArgs( + proof: ClaudeBackgroundAttachProof, + source: BackgroundReconnectSource, + signal?: AbortSignal, + ): Promise; + reserve( + source: BackgroundReconnectSource, + terminalId: string, + ): BackgroundReconnectSource; + assertReserved(source: BackgroundReconnectSource): void; + authorize(source: BackgroundReconnectSource): BackgroundReconnectSource; + unclaim(source: BackgroundReconnectSource): void; + reconcileExitedReservation?( + source: BackgroundReconnectSource, + signal?: AbortSignal, + ): Promise; + create(input: { + source: BackgroundReconnectSource; + terminalId: string; + executable: string; + args: readonly ["attach", string]; + beforeInitialCommand(): Promise; + onInitialCommandReady(): void; + }): Promise; + admission( + source: BackgroundReconnectSource, + terminalId: string, + signal?: AbortSignal, + ): Promise<{ + rootPid: number; + client: NativeClaudeTerminalClient; + bytes: Uint8Array; + } | null>; + commit( + source: BackgroundReconnectSource, + proof: ClaudeBackgroundAttachProof, + client: NativeClaudeTerminalClient, + ): BackgroundReconnectResult; + now(): number; + uuid(): string; + wait(): Promise; + schedule?(callback: () => void, milliseconds: number): () => void; +} + +function refuse(): never { + throw new Error( + "The exact background conversation changed or could not be verified. Nothing was restarted.", + ); +} +function accountKey(account: SessionAccount) { + return JSON.stringify([ + account.agent, + account.selection, + account.directory, + account.identity, + account.email, + account.credentialKind, + account.conflict, + ]); +} +export function admitsBackgroundAttachment( + bytes: Uint8Array, + id: string, +): boolean { + if ( + bytes.byteLength === 0 || + bytes.byteLength > 16 * 1024 || + !/^[a-zA-Z0-9_-]{1,64}$/.test(id) + ) + return false; + let raw: string; + try { + raw = new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + return false; + } + const positions = ["[?1049h", "[?1047h", "[?47h"] + .map((suffix) => raw.indexOf(String.fromCharCode(27) + suffix)) + .filter((position) => position >= 0); + const prefix = raw.slice( + 0, + positions.length ? Math.min(...positions) : raw.length, + ); + const text = stripVTControlCharacters(prefix).replaceAll("\r\n", "\n"); + const banners = [...text.matchAll(/^Session ([a-zA-Z0-9_-]+) ·[^\r\n]*$/gm)]; + return ( + banners.length > 0 && + banners.length <= 8 && + banners.every((match) => match[1] === id) + ); +} + +export function createBackgroundReconnect(io: BackgroundReconnectIO) { + const operations = new Map>(); + return async ( + request: BackgroundReconnectInput, + ): Promise => { + const input = Object.freeze({ ...request }); + const key = JSON.stringify([ + input.workspaceId, + input.terminalId, + input.expectedRevision, + ]); + const existing = operations.get(key); + if (existing) return existing; + if (operations.size >= 128) return refuse(); + const operation = boundedReconnect(input); + operations.set(key, operation); + try { + return await operation; + } finally { + if (operations.get(key) === operation) operations.delete(key); + } + }; + + async function boundedReconnect( + input: BackgroundReconnectInput, + ): Promise { + const controller = new AbortController(); + let current: BackgroundReconnectSource | null = null; + let authorized = false; + const guard = () => { + if (controller.signal.aborted) return refuse(); + }; + let cancel: (() => void) | undefined; + const timeout = new Promise( + (resolve, reject) => { + const expired = () => { + controller.abort(); + if (authorized && current?.reservation) + resolve({ + reconnected: false, + attachmentPending: true, + terminalId: current.reservation.terminalId, + label: current.label, + }); + else + reject( + new Error( + "Background verification timed out. Nothing was restarted.", + ), + ); + }; + if (io.schedule) cancel = io.schedule(expired, 12_000); + else { + const timer = setTimeout(expired, 12_000); + cancel = () => clearTimeout(timer); + } + }, + ); + const work = reconnect( + input, + controller.signal, + guard, + (source, started) => { + current = source; + authorized = started; + }, + ); + try { + return await Promise.race([work, timeout]); + } finally { + cancel?.(); + controller.abort(); + } + } + + async function reconnect( + input: BackgroundReconnectInput, + signal: AbortSignal, + guard: () => void, + update: (source: BackgroundReconnectSource, authorized: boolean) => void, + ): Promise { + const successor = io.successor(input); + if (successor) return successor; + const discoveredSource = io.read(input); + let source = discoveredSource && structuredClone(discoveredSource); + if (!source) return { reconnected: false }; + if ( + source.expectedRevision !== input.expectedRevision || + source.account.agent !== "claude" || + source.account.credentialKind !== "subscription" || + !source.account.directory || + source.account.conflict + ) + return refuse(); + const release = claimNativeSession("claude", source.sessionId); + let authorized = source.reservation?.authorized ?? false; + update(source, authorized); + try { + const check = async () => { + if ( + !source || + accountKey(await io.verifyAccount(source, signal)) !== + accountKey(source.account) + ) + return refuse(); + guard(); + const current = io.read(input); + if (!isDeepStrictEqual(current, source)) return refuse(); + }; + await check(); + if (source.reservation?.authorized && io.reconcileExitedReservation) { + source = await io.reconcileExitedReservation(source, signal); + guard(); + authorized = source.reservation?.authorized ?? false; + update(source, authorized); + await check(); + } + await io.assertIdle(source, signal); + guard(); + let proof = await io.prove(source, signal); + guard(); + if (!proof) { + if (source.reservation) return refuse(); + return { reconnected: false }; + } + const args = Object.freeze(await io.attachArgs(proof, source, signal)); + guard(); + if ( + args[0] !== "attach" || + args.length !== 2 || + !args[1] || + args[1].startsWith("-") || + /[\r\n\0]/.test(args[1]) + ) + return refuse(); + const sameWorker = async () => { + if (!source || !proof) return refuse(); + const fresh = await io.prove(source, signal); + if ( + !fresh || + !isDeepStrictEqual(fresh.workerAfter, proof.workerAfter) || + !isDeepStrictEqual(await io.attachArgs(fresh, source, signal), args) + ) + return refuse(); + proof = fresh; + await check(); + }; + if (!source.reservation) { + const terminalId = io.uuid(); + guard(); + source = io.reserve(source, terminalId); + update(source, authorized); + await io.create({ + source, + terminalId, + executable: proof.workerAfter.executable, + args, + beforeInitialCommand: async () => { + await sameWorker(); + if (!source) return refuse(); + await io.assertIdle(source, signal); + guard(); + io.assertReserved(source); + }, + onInitialCommandReady: () => { + guard(); + if (!source) return refuse(); + source = io.authorize(source); + authorized = true; + update(source, true); + }, + }); + } + const terminalId = source.reservation?.terminalId; + if (!terminalId || !authorized) return refuse(); + const deadline = io.now() + 4_000; + for (let attempt = 0; attempt < 40 && io.now() <= deadline; attempt++) { + const admitted = await io.admission(source, terminalId, signal); + guard(); + if ( + admitted && + admitted.client.executable === proof.workerAfter.executable && + admitted.client.configDir === proof.target.configDir && + admitted.client.cwd === proof.target.worktreePath && + admitted.client.ancestors.at(-1)?.pid === admitted.rootPid && + admitsBackgroundAttachment(admitted.bytes, proof.candidate.id) + ) { + await sameWorker(); + const confirmed = await io.admission(source, terminalId, signal); + if ( + !confirmed || + confirmed.rootPid !== admitted.rootPid || + !isDeepStrictEqual(confirmed.client, admitted.client) || + !admitsBackgroundAttachment(confirmed.bytes, proof.candidate.id) + ) + return refuse(); + guard(); + io.assertReserved(source); + return io.commit(source, proof, admitted.client); + } + await io.wait(); + } + return { + reconnected: false, + attachmentPending: true, + terminalId, + label: source.label, + }; + } catch (error) { + if (!authorized && source.reservation) io.unclaim(source); + throw error; + } finally { + release(); + } + } +} diff --git a/packages/host-service/src/trpc/router/terminal-agents/resume-account.test.ts b/packages/host-service/src/trpc/router/terminal-agents/resume-account.test.ts new file mode 100644 index 00000000000..790ed76a5f3 --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/resume-account.test.ts @@ -0,0 +1,609 @@ +import { Database } from "bun:sqlite"; +import { afterEach, describe, expect, test } from "bun:test"; +import { resolve } from "node:path"; +import { eq } from "drizzle-orm"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { migrate } from "drizzle-orm/bun-sqlite/migrator"; +import type { HostDb } from "../../../db"; +import * as schema from "../../../db/schema"; +import { + hostAgentConfigs, + terminalAgentBindings, + terminalSessions, + workspaces, +} from "../../../db/schema"; +import type { SessionAccount } from "../usage/session-account/session-account"; +import { + accountResumeSource, + type ResumeWithAccountDeps, + resumeTerminalWithAccount, +} from "./resume-account"; + +const databases: Database[] = []; +afterEach(() => { + for (const db of databases.splice(0)) db.close(); +}); +const sourceAccount: SessionAccount = { + agent: "claude", + selection: "/fixture/source", + directory: "/fixture/source", + identity: "a".repeat(64), + credentialKind: "subscription", +}; +const targetAccount: SessionAccount = { + ...sourceAccount, + selection: "/fixture/target", + directory: "/fixture/target", + identity: "b".repeat(64), + pinned: true, +}; +const sourceInput = { workspaceId: "workspace", terminalId: "source" }; +const history = { + path: "/fixture/shared/exact-session.jsonl", + device: 1, + inode: 2, + size: 50, + modifiedAt: 3, + changedAt: 4, + sha256: "c".repeat(64), +}; +function fixture(provider: "claude" | "codex" = "claude") { + const sqlite = new Database(":memory:"); + databases.push(sqlite); + const db = drizzle(sqlite, { schema }) as unknown as HostDb; + migrate(db as never, { + migrationsFolder: resolve(import.meta.dir, "../../../../drizzle"), + }); + db.insert(workspaces) + .values({ + id: "workspace", + worktreePath: "/fixture/workspace", + branch: "main", + }) + .run(); + db.insert(hostAgentConfigs) + .values({ + id: "custom:fixture", + presetId: provider, + label: provider, + command: provider, + promptTransport: "argv", + resumeArgsJson: JSON.stringify( + provider === "claude" ? ["--resume"] : ["resume"], + ), + displayOrder: 0, + }) + .run(); + db.insert(terminalSessions) + .values({ + id: "source", + originWorkspaceId: "workspace", + status: "active", + createdAt: 1, + }) + .run(); + db.insert(terminalAgentBindings) + .values({ + terminalId: "source", + workspaceId: "workspace", + definitionId: "custom:fixture", + agentId: provider, + agentSessionId: "exact-session", + accountJson: JSON.stringify({ ...sourceAccount, agent: provider }), + startedAt: 1, + lastEventAt: 2, + lastEventType: "Stop", + endedAt: 3, + endReason: "detached", + }) + .run(); + const calls: Parameters[0][] = []; + const events: Parameters< + ResumeWithAccountDeps["eventBus"]["broadcastTerminalLifecycle"] + >[0][] = []; + const deps: ResumeWithAccountDeps = { + db, + runAgent: async (input) => { + if (!input.terminalLaunch) throw new Error("Expected guarded launch"); + await input.terminalLaunch.beforeInitialCommand(); + input.terminalLaunch.onInitialCommandReady(); + calls.push(input); + return { + kind: "terminal", + sessionId: input.terminalLaunch.terminalId, + label: provider, + }; + }, + eventBus: { + broadcastTerminalLifecycle: (event) => { + events.push(event); + }, + }, + resolveAccount: async () => ({ ...targetAccount, agent: provider }), + validateRouting: async () => {}, + assertIdle: async () => {}, + assertNoClaudeWriter: async () => {}, + inspectHistory: async () => history, + assertHistoryCurrent: () => {}, + }; + const input = () => ({ + ...sourceInput, + expectedRevision: + accountResumeSource(db, sourceInput)?.revision ?? "missing", + account: { + selection: targetAccount.selection, + identity: targetAccount.identity, + }, + }); + const binding = () => + db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, "source")) + .get(); + return { db, deps, calls, events, input, binding }; +} + +function authorizePersistedSuccessor( + f: ReturnType, + input: Parameters[0], + mutate?: () => void, + overrides: Partial = {}, +) { + const launch = input.terminalLaunch; + const source = f.binding(); + if (!launch || !source) throw new Error("Expected recovery reservation"); + f.db.transaction(() => { + f.db + .insert(terminalSessions) + .values({ + id: launch.terminalId, + originWorkspaceId: "workspace", + createdAt: 4, + }) + .run(); + f.db + .insert(terminalAgentBindings) + .values({ + ...source, + terminalId: launch.terminalId, + accountJson: JSON.stringify(input.account), + startedAt: 4, + lastEventAt: 4, + lastEventType: "Attached", + endedAt: null, + endReason: null, + resumedIntoTerminalId: null, + ...overrides, + }) + .run(); + mutate?.(); + launch.onInitialCommandReady(); + }); + return { + kind: "terminal" as const, + sessionId: launch.terminalId, + label: "Claude", + }; +} + +describe("resume an ended native conversation with a selected account", () => { + test("authorizes its exact successor persisted before the command callback", async () => { + const f = fixture(); + f.deps.runAgent = async (input) => { + await input.terminalLaunch?.beforeInitialCommand(); + return authorizePersistedSuccessor(f, input); + }; + const result = await resumeTerminalWithAccount(f.deps, f.input()); + expect(f.binding()?.endReason).toBe("resumed"); + expect(f.binding()?.resumedIntoTerminalId).toBe(result.terminalId); + expect( + f.db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, result.terminalId)) + .get(), + ).toMatchObject({ + agentSessionId: "exact-session", + accountJson: JSON.stringify(targetAccount), + }); + }); + + test.each([ + { workspaceId: "other-workspace" }, + { agentId: "codex" }, + { agentSessionId: "different-session" }, + { definitionId: "claude" }, + { accountJson: JSON.stringify(sourceAccount) }, + { accountJson: JSON.stringify({ ...targetAccount, conflict: true }) }, + { endedAt: 5, endReason: "detached" }, + ] satisfies Array< + Partial + >)("does not exempt a mismatched persisted successor %#", async (overrides) => { + const f = fixture(); + f.deps.runAgent = async (input) => { + await input.terminalLaunch?.beforeInitialCommand(); + return authorizePersistedSuccessor(f, input, undefined, overrides); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "changed", + ); + expect(f.binding()?.endReason).toBe("detached"); + expect(f.db.select().from(terminalAgentBindings).all()).toHaveLength(1); + }); + + test("still refuses another binding appearing beside its own successor", async () => { + const f = fixture(); + f.deps.runAgent = async (input) => { + await input.terminalLaunch?.beforeInitialCommand(); + return authorizePersistedSuccessor(f, input, () => { + const source = f.binding(); + if (!source) throw new Error("Expected source binding"); + f.db + .insert(terminalSessions) + .values({ + id: "racing-writer", + originWorkspaceId: "workspace", + createdAt: 4, + }) + .run(); + f.db + .insert(terminalAgentBindings) + .values({ + ...source, + terminalId: "racing-writer", + endedAt: null, + endReason: null, + resumedIntoTerminalId: null, + }) + .run(); + }); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "running agent", + ); + expect(f.binding()?.endReason).toBe("detached"); + expect(f.db.select().from(terminalAgentBindings).all()).toHaveLength(1); + }); + + test("rechecks the transcript at synchronous command authorization", async () => { + const f = fixture(); + let checkpoint = false; + f.deps.assertHistoryCurrent = () => { + checkpoint = true; + throw new Error("Saved history changed"); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "Saved history changed", + ); + expect(checkpoint).toBe(true); + expect(f.binding()?.endReason).toBe("detached"); + expect(f.calls).toHaveLength(0); + }); + + test("rechecks the workspace after asynchronous preflight but before consuming the claim", async () => { + const f = fixture(); + f.deps.runAgent = async (input) => { + if (!input.terminalLaunch) throw new Error("Expected guard"); + await input.terminalLaunch.beforeInitialCommand(); + f.db + .update(workspaces) + .set({ worktreePath: "/changed-before-send" }) + .run(); + input.terminalLaunch.onInitialCommandReady(); + throw new Error("Should not authorize"); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "changed", + ); + expect(f.binding()?.endReason).toBe("detached"); + expect(f.calls).toHaveLength(0); + }); + test.each([ + "claude", + "codex", + ] as const)("resumes exact %s identity without a prompt or source terminal disposal", async (provider) => { + const f = fixture(provider); + const before = f.db.select().from(terminalSessions).all(); + const result = await resumeTerminalWithAccount(f.deps, f.input()); + expect(result).toMatchObject({ resumed: true, label: provider }); + expect(result.terminalId).toMatch(/^[0-9a-f-]{36}$/); + expect(f.calls).toMatchObject([ + { + workspaceId: "workspace", + agent: "custom:fixture", + prompt: "", + surface: "terminal", + resumeSessionId: "exact-session", + account: { ...targetAccount, agent: provider }, + }, + ]); + expect(f.binding()?.resumedIntoTerminalId).toBe( + f.calls[0]?.terminalLaunch?.terminalId, + ); + expect(f.events[0]).toMatchObject({ + terminalId: "source", + eventType: "resumed", + resumedTerminalId: f.calls[0]?.terminalLaunch?.terminalId, + }); + expect(f.db.select().from(terminalSessions).all()).toEqual(before); + }); + + test.each([ + null, + "malformed", + JSON.stringify({ ...sourceAccount, conflict: true }), + ])("refuses unavailable or conflicting original account metadata", async (accountJson) => { + const f = fixture(); + f.db.update(terminalAgentBindings).set({ accountJson }).run(); + expect(accountResumeSource(f.db, sourceInput)).toMatchObject({ + ready: false, + }); + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "original account context", + ); + expect(f.calls).toHaveLength(0); + }); + + test("refuses an agent that has not exited normally", async () => { + const f = fixture(); + f.db + .update(terminalAgentBindings) + .set({ endedAt: null, endReason: null }) + .run(); + expect(accountResumeSource(f.db, sourceInput)).toMatchObject({ + ready: false, + }); + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "Exit this agent normally", + ); + expect(f.calls).toHaveLength(0); + }); + + test("refuses a stale source revision before resolving the destination", async () => { + const f = fixture(); + const input = f.input(); + f.db.update(terminalAgentBindings).set({ agentSessionId: "other" }).run(); + let resolved = false; + f.deps.resolveAccount = async () => { + resolved = true; + return targetAccount; + }; + await expect(resumeTerminalWithAccount(f.deps, input)).rejects.toThrow( + "changed", + ); + expect(resolved).toBe(false); + expect(f.calls).toHaveLength(0); + }); + + test.each([ + "resolveAccount", + "validateRouting", + "assertIdle", + "assertNoClaudeWriter", + "inspectHistory", + ] as const)("does not consume recovery when %s refuses", async (guard) => { + const f = fixture(); + const before = f.binding(); + f.deps[guard] = async () => { + throw new Error("refused"); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "refused", + ); + expect(f.binding()).toEqual(before); + expect(f.calls).toHaveLength(0); + }); + + test("refuses another known active binding for the exact conversation", async () => { + const f = fixture(); + const binding = f.binding(); + if (!binding) throw new Error("Expected fixture binding"); + f.db + .insert(terminalAgentBindings) + .values({ + ...binding, + terminalId: "other", + endedAt: null, + endReason: null, + }) + .run(); + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "running agent", + ); + expect(f.binding()?.endReason).toBe("detached"); + expect(f.calls).toHaveLength(0); + }); + + test("coalesces neither duplicate clicks nor silent fresh launches", async () => { + const f = fixture(); + const input = f.input(); + let release!: () => void; + const paused = new Promise((resolve) => { + release = resolve; + }); + f.deps.resolveAccount = async () => { + await paused; + return targetAccount; + }; + const first = resumeTerminalWithAccount(f.deps, input); + await expect(resumeTerminalWithAccount(f.deps, input)).rejects.toThrow( + "changed", + ); + release(); + await first; + expect(f.calls).toHaveLength(1); + await expect(resumeTerminalWithAccount(f.deps, input)).rejects.toThrow( + "changed", + ); + expect(f.calls).toHaveLength(1); + }); + + test.each([ + "detached", + "terminal-exited", + "disposed", + ])("restores the %s recovery claim when launch fails", async (endReason) => { + const f = fixture(); + f.db.update(terminalAgentBindings).set({ endReason }).run(); + const before = f.binding(); + f.deps.runAgent = async () => { + throw new Error("launch failed"); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "launch failed", + ); + expect(f.binding()).toEqual(before); + expect(f.events).toHaveLength(0); + }); + + test("refuses a transcript that grew during the claim without consuming recovery", async () => { + const f = fixture(); + let count = 0; + f.deps.inspectHistory = async () => ({ + ...history, + size: ++count === 1 ? 50 : 100, + }); + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "changed", + ); + expect(f.binding()?.endReason).toBe("detached"); + expect(f.calls).toHaveLength(0); + }); + + test.each([ + "workspace", + "config", + ])("refuses a changed %s after the final asynchronous guard", async (kind) => { + const f = fixture(); + let count = 0; + f.deps.inspectHistory = async () => { + if (++count === 2) { + if (kind === "workspace") + f.db + .update(workspaces) + .set({ worktreePath: "/other/workspace" }) + .run(); + else f.db.update(hostAgentConfigs).set({ label: "changed" }).run(); + } + return history; + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "changed", + ); + expect(f.binding()?.endReason).toBe("detached"); + expect(f.calls).toHaveLength(0); + }); + + test("does not roll back a newly observed source binding", async () => { + const f = fixture(); + let count = 0; + f.deps.inspectHistory = async () => { + if (++count === 2) + f.db + .update(terminalAgentBindings) + .set({ + lastEventAt: 8, + agentSessionId: "new-observed-id", + endReason: null, + endedAt: null, + }) + .run(); + return history; + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "changed", + ); + expect(f.binding()).toMatchObject({ + agentSessionId: "new-observed-id", + endReason: null, + endedAt: null, + lastEventAt: 8, + }); + expect(f.calls).toHaveLength(0); + }); + + test("retains the consumed claim if notification fails after launch", async () => { + const f = fixture(); + f.deps.eventBus.broadcastTerminalLifecycle = () => { + throw new Error("notification failed"); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "notification failed", + ); + expect(f.binding()?.endReason).toBe("resumed"); + expect(f.binding()?.resumedIntoTerminalId).toBe( + f.calls[0]?.terminalLaunch?.terminalId, + ); + expect(f.calls).toHaveLength(1); + }); + test("retries a pre-command crash claim without consuming or modifying the abandoned shell", async () => { + const f = fixture(); + f.db + .insert(terminalSessions) + .values({ + id: "abandoned-shell", + status: "active", + originWorkspaceId: "workspace", + createdAt: 4, + }) + .run(); + f.db + .update(terminalAgentBindings) + .set({ + endReason: "account-resume-preparing:detached", + resumedIntoTerminalId: "abandoned-shell", + }) + .run(); + const terminals = f.db.select().from(terminalSessions).all(); + expect(accountResumeSource(f.db, sourceInput)?.ready).toBe(true); + const result = await resumeTerminalWithAccount(f.deps, f.input()); + expect(result.terminalId).not.toBe("abandoned-shell"); + expect(f.db.select().from(terminalSessions).all()).toEqual(terminals); + }); + + test("preserves a durable successor if the host response fails after command authorization", async () => { + const f = fixture(); + f.deps.runAgent = async (input) => { + if (!input.terminalLaunch) throw new Error("Expected guard"); + await input.terminalLaunch.beforeInitialCommand(); + input.terminalLaunch.onInitialCommandReady(); + throw new Error("host response lost"); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "host response lost", + ); + expect(f.binding()?.endReason).toBe("resumed"); + expect(f.binding()?.resumedIntoTerminalId).toMatch(/^[0-9a-f-]{36}$/); + expect(accountResumeSource(f.db, sourceInput)?.ready).toBe(false); + }); + + test("revalidates after launcher preflight before authorizing the command", async () => { + const f = fixture(); + const launch = f.deps.runAgent; + f.deps.runAgent = async (input) => { + f.db + .update(workspaces) + .set({ worktreePath: "/changed-during-shell-start" }) + .run(); + return launch(input); + }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "changed", + ); + expect(f.calls).toHaveLength(0); + expect(f.binding()?.endReason).toBe("detached"); + }); + + test("refuses a destination identity that changes during launcher preflight", async () => { + const f = fixture(); + let reads = 0; + f.deps.resolveAccount = async () => + ++reads === 1 ? targetAccount : { ...targetAccount, identity: "changed" }; + await expect(resumeTerminalWithAccount(f.deps, f.input())).rejects.toThrow( + "changed", + ); + expect(f.calls).toHaveLength(0); + expect(f.binding()?.endReason).toBe("detached"); + }); +}); diff --git a/packages/host-service/src/trpc/router/terminal-agents/resume-account.ts b/packages/host-service/src/trpc/router/terminal-agents/resume-account.ts new file mode 100644 index 00000000000..87230a1b28b --- /dev/null +++ b/packages/host-service/src/trpc/router/terminal-agents/resume-account.ts @@ -0,0 +1,417 @@ +import { createHash, randomUUID } from "node:crypto"; +import { isAbsolute } from "node:path"; +import { TRPCError } from "@trpc/server"; +import { and, eq, inArray, isNull, like, ne, or } from "drizzle-orm"; +import type { HostDb } from "../../../db"; +import { terminalAgentBindings, workspaces } from "../../../db/schema"; +import type { EventBus } from "../../../events"; +import { resolveHostAgentConfig } from "../../../terminal-agents/agent-config"; +import { claimNativeSession } from "../../../terminal-agents/native-session-lease"; +import { validateAccountAuthRouting } from "../agents/account-auth-routing"; +import type { AgentRunInput, AgentRunResult } from "../agents/agents"; +import { + accountLaunchUnsupportedReason, + type LaunchAccountChoice, + resolveLaunchAccount, +} from "../agents/launch-account"; +import { + parsePersistedSessionAccount, + sameSessionAccountContext, +} from "../usage/session-account/session-account"; +import { + assertAccountResumeHistoryCurrent, + inspectAccountResumeHistory, + sameAccountResumeHistory, +} from "./account-resume-history"; +import { + assertAccountResumeTerminalIdle, + assertNoRecordedClaudeWriter, +} from "./account-resume-processes"; + +interface ResumeAccountSourceInput { + workspaceId: string; + terminalId: string; +} +export interface ResumeWithAccountInput extends ResumeAccountSourceInput { + expectedRevision: string; + account: LaunchAccountChoice; +} + +const ENDED_REASONS = ["detached", "terminal-exited", "disposed"]; +const PREPARING_REASONS = ENDED_REASONS.map( + (reason) => `account-resume-preparing:${reason}`, +); +function originalEndReason(reason: string | null): string | undefined { + if (reason && ENDED_REASONS.includes(reason)) return reason; + if (reason && PREPARING_REASONS.includes(reason)) + return reason.slice("account-resume-preparing:".length); + return undefined; +} + +function changed(): never { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The saved conversation changed or was already resumed. Reopen the account choice. Nothing was launched.", + }); +} + +function revisionOf( + binding: unknown, + workspace: unknown, + config: unknown, +): string { + return createHash("sha256") + .update(JSON.stringify([binding, workspace, config])) + .digest("hex"); +} + +function context(db: HostDb, input: ResumeAccountSourceInput) { + const binding = db + .select() + .from(terminalAgentBindings) + .where( + and( + eq(terminalAgentBindings.terminalId, input.terminalId), + eq(terminalAgentBindings.workspaceId, input.workspaceId), + ), + ) + .get(); + if ( + !binding || + (binding.agentId !== "claude" && binding.agentId !== "codex") || + !binding.agentSessionId + ) + return null; + const workspace = db + .select({ path: workspaces.worktreePath }) + .from(workspaces) + .where( + and(eq(workspaces.id, input.workspaceId), isNull(workspaces.archivedAt)), + ) + .get(); + const config = resolveHostAgentConfig( + db, + binding.definitionId ?? binding.agentId, + ); + const account = parsePersistedSessionAccount(binding.accountJson); + const revision = revisionOf(binding, workspace, config); + let reason: string | undefined; + if (!workspace || !config || config.presetId !== binding.agentId) + reason = "The original workspace or agent configuration is unavailable."; + else if ( + !account?.directory || + !isAbsolute(account.directory) || + account.agent !== binding.agentId || + account.conflict || + account.credentialKind !== "subscription" + ) + reason = + "The original account context is unavailable or conflicting. This conversation cannot be switched safely."; + else if (binding.endedAt === null) + reason = + "Exit this agent normally before choosing another account. Running tools and background jobs do not move."; + else if (!originalEndReason(binding.endReason)) + reason = "This conversation was already resumed or is being resumed."; + else if (process.platform !== "darwin" && process.platform !== "linux") + reason = "Account recovery is not available on this platform."; + else reason = accountLaunchUnsupportedReason(config); + return { binding, workspace, config, account, revision, reason }; +} + +export function accountResumeSource( + db: HostDb, + input: ResumeAccountSourceInput, +) { + const source = context(db, input); + if (!source) return null; + return { + provider: source.binding.agentId as "claude" | "codex", + agent: source.config?.id ?? source.binding.agentId, + sessionId: source.binding.agentSessionId as string, + revision: source.revision, + ready: source.reason === undefined, + ...(source.reason ? { reason: source.reason } : {}), + account: source.account ?? null, + }; +} + +function assertNoCompetingBinding( + db: HostDb, + source: typeof terminalAgentBindings.$inferSelect, + authorizedSuccessorTerminalId?: string, +): void { + const competing = db + .select({ terminalId: terminalAgentBindings.terminalId }) + .from(terminalAgentBindings) + .where( + and( + eq(terminalAgentBindings.agentId, source.agentId), + eq( + terminalAgentBindings.agentSessionId, + source.agentSessionId as string, + ), + ne(terminalAgentBindings.terminalId, source.terminalId), + authorizedSuccessorTerminalId + ? ne(terminalAgentBindings.terminalId, authorizedSuccessorTerminalId) + : undefined, + or( + inArray(terminalAgentBindings.endReason, PREPARING_REASONS), + like(terminalAgentBindings.endReason, "background-attach:%"), + isNull(terminalAgentBindings.endedAt), + and( + eq(terminalAgentBindings.endReason, "resumed"), + isNull(terminalAgentBindings.resumedIntoTerminalId), + ), + ), + ), + ) + .get(); + if (competing) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "This conversation already has a running agent or a pending recovery. Nothing was launched.", + }); +} + +export interface ResumeWithAccountDeps { + db: HostDb; + runAgent: (input: AgentRunInput) => Promise; + eventBus: Pick; + resolveAccount?: typeof resolveLaunchAccount; + validateRouting?: typeof validateAccountAuthRouting; + inspectHistory?: typeof inspectAccountResumeHistory; + assertHistoryCurrent?: typeof assertAccountResumeHistoryCurrent; + assertIdle?: typeof assertAccountResumeTerminalIdle; + assertNoClaudeWriter?: typeof assertNoRecordedClaudeWriter; +} + +export async function resumeTerminalWithAccount( + deps: ResumeWithAccountDeps, + input: ResumeWithAccountInput, +) { + const source = context(deps.db, input); + if (!source || source.revision !== input.expectedRevision) changed(); + if ( + source.reason || + !source.account || + !source.workspace || + !source.config || + !source.binding.agentSessionId + ) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + source.reason ?? + "The saved conversation is unavailable. Nothing was launched.", + }); + const config = source.config; + const workspace = source.workspace; + let release: () => void; + try { + release = claimNativeSession( + source.binding.agentId, + source.binding.agentSessionId, + ); + } catch { + changed(); + } + let claimed = false; + let launchAuthorized = false; + const terminalId = randomUUID(); + const originalReason = originalEndReason(source.binding.endReason) as string; + const preparingReason = `account-resume-preparing:${originalReason}`; + const claimedBinding = { + ...source.binding, + endReason: preparingReason, + resumedIntoTerminalId: terminalId, + }; + try { + if ( + source.binding.endReason?.startsWith("account-resume-preparing:") && + source.binding.resumedIntoTerminalId + ) { + const reserved = deps.db + .select() + .from(terminalAgentBindings) + .where( + eq( + terminalAgentBindings.terminalId, + source.binding.resumedIntoTerminalId, + ), + ) + .get(); + if (reserved) + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The earlier recovery terminal has a saved agent binding. Open that terminal before trying again. Nothing was launched.", + }); + } + const target = await (deps.resolveAccount ?? resolveLaunchAccount)( + config, + input.account, + ); + await (deps.validateRouting ?? validateAccountAuthRouting)( + target, + workspace.path, + ); + const checkIdle = () => + (deps.assertIdle ?? assertAccountResumeTerminalIdle)( + deps.db, + input.terminalId, + input.workspaceId, + ); + const checkWriters = async () => { + if (source.binding.agentId === "claude") + await (deps.assertNoClaudeWriter ?? assertNoRecordedClaudeWriter)({ + sessionId: source.binding.agentSessionId as string, + directories: [ + source.account?.directory as string, + target.directory as string, + ], + }); + }; + await checkIdle(); + await checkWriters(); + const historyInput = { + source: source.account, + target, + sessionId: source.binding.agentSessionId, + cwd: workspace.path, + }; + const history = await (deps.inspectHistory ?? inspectAccountResumeHistory)( + historyInput, + ); + deps.db.transaction((tx) => { + if (context(deps.db, input)?.revision !== input.expectedRevision) + changed(); + assertNoCompetingBinding(deps.db, source.binding); + tx.update(terminalAgentBindings) + .set({ endReason: preparingReason, resumedIntoTerminalId: terminalId }) + .where(eq(terminalAgentBindings.terminalId, input.terminalId)) + .run(); + }); + claimed = true; + const assertClaim = (successorPersisted = false) => { + const current = context(deps.db, input); + if ( + !current || + JSON.stringify(current.binding) !== JSON.stringify(claimedBinding) || + revisionOf(source.binding, current.workspace, current.config) !== + source.revision + ) + changed(); + let authorizedSuccessorTerminalId: string | undefined; + if (successorPersisted) { + const successor = deps.db + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, terminalId)) + .get(); + if (successor) { + if ( + successor.workspaceId !== input.workspaceId || + successor.agentId !== source.binding.agentId || + successor.agentSessionId !== source.binding.agentSessionId || + successor.definitionId !== config.id || + successor.endedAt !== null || + successor.endReason !== null || + successor.resumedIntoTerminalId !== null || + !sameSessionAccountContext( + parsePersistedSessionAccount(successor.accountJson), + target, + ) + ) + changed(); + authorizedSuccessorTerminalId = terminalId; + } + } + assertNoCompetingBinding( + deps.db, + source.binding, + authorizedSuccessorTerminalId, + ); + }; + const result = await deps.runAgent({ + workspaceId: input.workspaceId, + agent: config.id, + prompt: "", + surface: "terminal", + resumeSessionId: source.binding.agentSessionId, + account: target, + terminalLaunch: { + terminalId, + beforeInitialCommand: async () => { + const currentTarget = await ( + deps.resolveAccount ?? resolveLaunchAccount + )(config, input.account); + if (JSON.stringify(currentTarget) !== JSON.stringify(target)) + changed(); + await (deps.validateRouting ?? validateAccountAuthRouting)( + target, + workspace.path, + ); + await checkIdle(); + await checkWriters(); + if ( + !sameAccountResumeHistory( + history, + await (deps.inspectHistory ?? inspectAccountResumeHistory)( + historyInput, + ), + ) + ) + changed(); + assertClaim(); + }, + onInitialCommandReady: () => { + // Called in the same transaction that persists the target binding. + (deps.assertHistoryCurrent ?? assertAccountResumeHistoryCurrent)( + history, + ); + assertClaim(true); + deps.db + .update(terminalAgentBindings) + .set({ endReason: "resumed" }) + .where(eq(terminalAgentBindings.terminalId, input.terminalId)) + .run(); + launchAuthorized = true; + }, + }, + }); + if (!launchAuthorized || result.sessionId !== terminalId) changed(); + deps.eventBus.broadcastTerminalLifecycle({ + workspaceId: input.workspaceId, + terminalId: input.terminalId, + eventType: "resumed", + resumedTerminalId: result.sessionId, + label: result.label, + occurredAt: Date.now(), + }); + return { + resumed: true as const, + terminalId: result.sessionId, + label: result.label, + }; + } catch (error) { + if (claimed && !launchAuthorized) { + deps.db.transaction((tx) => { + const current = tx + .select() + .from(terminalAgentBindings) + .where(eq(terminalAgentBindings.terminalId, input.terminalId)) + .get(); + if (JSON.stringify(current) !== JSON.stringify(claimedBinding)) return; + tx.update(terminalAgentBindings) + .set({ endReason: originalReason, resumedIntoTerminalId: null }) + .where(eq(terminalAgentBindings.terminalId, input.terminalId)) + .run(); + }); + } + throw error; + } finally { + release(); + } +} diff --git a/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.test.ts b/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.test.ts index 7be2a81cec4..d6e0d19ecf1 100644 --- a/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.test.ts +++ b/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.test.ts @@ -1,6 +1,7 @@ import { Database } from "bun:sqlite"; import { describe, expect, it } from "bun:test"; import { resolve } from "node:path"; +import { eq } from "drizzle-orm"; import { drizzle } from "drizzle-orm/bun-sqlite"; import { migrate } from "drizzle-orm/bun-sqlite/migrator"; import type { HostDb } from "../../../db"; @@ -141,6 +142,70 @@ function createDeps( } describe("resumeTerminalAgentSession", () => { + it("refuses malformed persisted account context without consuming recovery", async () => { + const db = createTestDb(); + seedResumableBinding(db); + db.update(terminalAgentBindings) + .set({ accountJson: "broken" }) + .where(eq(terminalAgentBindings.terminalId, "t1")) + .run(); + const { deps, runCalls } = createDeps(db); + await expect( + resumeTerminalAgentSession(deps, { + workspaceId: "ws-1", + terminalId: "t1", + }), + ).rejects.toThrow("saved account information is unreadable"); + expect(runCalls).toEqual([]); + expect(findResumeCandidateBinding(db, "ws-1", "t1")?.accountInvalid).toBe( + true, + ); + }); + it("carries the persisted explicit account through exact-session recovery", async () => { + const db = createTestDb(); + seedResumableBinding(db); + const account = { + agent: "claude", + selection: "/selected/profile", + directory: "/selected/profile", + credentialKind: "subscription", + identity: "a".repeat(64), + email: "fixture@example.test", + pinned: true, + }; + db.update(terminalAgentBindings) + .set({ accountJson: JSON.stringify(account), launchId: "old-launch" }) + .where(eq(terminalAgentBindings.terminalId, "t1")) + .run(); + const { deps, runCalls } = createDeps(db); + await resumeTerminalAgentSession(deps, { + workspaceId: "ws-1", + terminalId: "t1", + }); + expect(runCalls[0]).toMatchObject({ + resumeSessionId: "sess-t1", + account, + surface: "terminal", + }); + }); + + it("leaves the recovery candidate intact when its selected account cannot launch", async () => { + const db = createTestDb(); + seedResumableBinding(db); + const { deps, disposedTerminals } = createDeps(db, { + runAgent: async () => { + throw new Error("saved account changed"); + }, + }); + await expect( + resumeTerminalAgentSession(deps, { + workspaceId: "ws-1", + terminalId: "t1", + }), + ).rejects.toThrow("saved account changed"); + expect(findResumeCandidateBinding(db, "ws-1", "t1")).toBeDefined(); + expect(disposedTerminals).toEqual([]); + }); it("claims, relaunches with the saved session id, and disposes the dead terminal", async () => { const db = createTestDb(); seedResumableBinding(db); @@ -465,6 +530,27 @@ describe("findResumedSuccessorTerminalId", () => { }); describe("listAccountRestartCandidates", () => { + it("does not include explicitly selected accounts in a global default switch", () => { + const db = createTestDb(); + seedAgentConfig(db); + seedLiveBinding(db, { terminalId: "pinned" }); + db.update(terminalAgentBindings) + .set({ + accountJson: JSON.stringify({ + agent: "claude", + selection: "/selected", + directory: "/selected", + credentialKind: "subscription", + identity: "a".repeat(64), + pinned: true, + }), + }) + .where(eq(terminalAgentBindings.terminalId, "pinned")) + .run(); + expect(listAccountRestartCandidates(db, createStore(db), "claude")).toEqual( + [], + ); + }); it("lists live provider sessions with a resumable conversation, nothing else", () => { const db = createTestDb(); seedAgentConfig(db); diff --git a/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.ts b/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.ts index d110656e812..2e6f04b6ec4 100644 --- a/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.ts +++ b/packages/host-service/src/trpc/router/terminal-agents/terminal-agents.ts @@ -35,6 +35,16 @@ import type { HostServiceContext } from "../../../types"; import { protectedProcedure, router } from "../../index"; import { type AgentRunResult, runAgentInWorkspace } from "../agents/agents"; import { toTerminalSessionError } from "../terminal/errors"; +import type { SessionAccount } from "../usage/session-account/session-account"; +import { + backgroundReconnectSource, + reconnectTerminalBackgroundSession, + supportsBackgroundReconnect, +} from "./background-reconnect-adapter"; +import { + accountResumeSource, + resumeTerminalWithAccount, +} from "./resume-account"; type GetOrCreateResult = { binding: TerminalAgentBinding; @@ -60,6 +70,8 @@ export interface ResumeSessionDeps { agent: string; prompt: string; resumeSessionId?: string; + account?: SessionAccount; + surface?: "terminal"; }) => Promise; disposeSession: ( terminalId: string, @@ -112,8 +124,8 @@ function bindingHasHarnessSession( * shows none, the agent is launched fresh instead of `--resume`-ing into "no * conversation found". A store that does hold one (a resumed session idle * since its restore) or cannot be read resumes as usual. Nothing is lost - * either way: the pane comes back as the same agent on the current default - * account. + * either way: the pane comes back as the same agent. Explicitly selected + * accounts remain pinned; legacy sessions follow the current default. */ export async function resumeTerminalAgentSession( deps: ResumeSessionDeps, @@ -131,6 +143,14 @@ export async function resumeTerminalAgentSession( terminalId, ); if (!claimed?.agentSessionId) return { resumed: false }; + if (claimed.accountInvalid) { + unclaimResumeCandidateBinding(deps.db, terminalId); + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The saved account information is unreadable. Nothing was launched.", + }); + } const config = resolveHostAgentConfig( deps.db, @@ -156,6 +176,9 @@ export async function resumeTerminalAgentSession( agent: config.id, prompt: "", ...(resumable ? { resumeSessionId: claimed.agentSessionId } : {}), + ...(claimed.account?.pinned + ? { account: claimed.account, surface: "terminal" as const } + : {}), }); } catch (error) { unclaimResumeCandidateBinding(deps.db, terminalId); @@ -219,7 +242,13 @@ export function listAccountRestartCandidates( ): Array<{ binding: TerminalAgentBinding; agentLabel: string }> { const out: Array<{ binding: TerminalAgentBinding; agentLabel: string }> = []; for (const binding of store.list()) { - if (!binding.agentSessionId || binding.chatSessionId) continue; + if ( + !binding.agentSessionId || + binding.chatSessionId || + binding.account?.pinned || + binding.accountInvalid + ) + continue; const config = resolveHostAgentConfig( db, binding.definitionId ?? binding.agentId, @@ -376,6 +405,75 @@ const GET_OR_CREATE_TIMEOUT_MS = 10_000; const MAX_AGENT_TRANSCRIPT_CHARS = 400_000; export const terminalAgentsRouter = router({ + accountRecoveryCapabilities: protectedProcedure.query(() => ({ + version: 1 as const, + exactAccountResume: true as const, + })), + accountResumeSource: protectedProcedure + .input( + z.object({ workspaceId: z.string(), terminalId: z.string() }).strict(), + ) + .query(({ ctx, input }) => accountResumeSource(ctx.db, input)), + + resumeWithAccount: protectedProcedure + .input( + z + .object({ + workspaceId: z.string(), + terminalId: z.string(), + expectedRevision: z.string().regex(/^[a-f0-9]{64}$/), + account: z + .object({ + selection: z.string().max(4096).nullable(), + identity: z.string().regex(/^[a-f0-9]{64}$/), + }) + .strict(), + }) + .strict(), + ) + .mutation(({ ctx, input }) => + resumeTerminalWithAccount( + { + db: ctx.db, + runAgent: (runInput) => runAgentInWorkspace(ctx, runInput), + eventBus: ctx.eventBus, + }, + input, + ), + ), + + /** Additive capability: older hosts never receive an unguarded new recovery procedure. */ + backgroundRecoveryCapabilities: protectedProcedure.query(async () => ({ + version: 1 as const, + claudeLiveAttach: await supportsBackgroundReconnect(), + })), + backgroundRecoverySource: protectedProcedure + .input( + z.object({ workspaceId: z.string(), terminalId: z.string() }).strict(), + ) + .query(({ ctx, input }) => backgroundReconnectSource(ctx, input)), + reconnectBackground: protectedProcedure + .input( + z + .object({ + workspaceId: z.string(), + terminalId: z.string(), + expectedRevision: z.string().regex(/^[a-f0-9]{64}$/), + }) + .strict(), + ) + .mutation(async ({ ctx, input }) => { + try { + return await reconnectTerminalBackgroundSession(ctx, input); + } catch { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: + "The exact background conversation could not be verified. Nothing was restarted. Retry Continue after checking the original session.", + }); + } + }), + list: protectedProcedure.query(({ ctx }) => { return ctx.terminalAgentStore.list(); }), diff --git a/packages/host-service/src/trpc/router/usage/claude-collection-queue.test.ts b/packages/host-service/src/trpc/router/usage/claude-collection-queue.test.ts new file mode 100644 index 00000000000..2837906480e --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-collection-queue.test.ts @@ -0,0 +1,117 @@ +import { expect, test } from "bun:test"; +import { + createClaudeCollectionQueue, + createRestartableClaudeCollectionQueue, +} from "./claude-collection-queue"; + +test("default automatic collection spaces account starts by one second", async () => { + let at = 0; + const starts: number[] = []; + const queue = createClaudeCollectionQueue({ + now: () => at, + sleep: async (ms) => { + at += ms; + }, + }); + await Promise.all( + Array.from({ length: 4 }, (_, index) => + queue.enqueue(String(index), async () => { + starts.push(at); + }), + ), + ); + expect(starts).toEqual([0, 1_000, 2_000, 3_000]); + await queue.dispose(); +}); + +test("twenty slow accounts enqueue without blocking inventory, serialize, coalesce and prioritize a selected account", async () => { + let at = 0, + running = 0, + maximum = 0; + const starts: string[] = [], + finishes: Array<() => void> = []; + const queue = createClaudeCollectionQueue({ + now: () => at, + sleep: async (ms) => { + at += ms; + }, + staggerMs: 150, + }); + const run = (id: string) => async () => { + starts.push(id); + maximum = Math.max(maximum, ++running); + await new Promise((resolve) => finishes.push(resolve)); + running--; + return id; + }; + const jobs = Array.from({ length: 20 }, (_, i) => + queue.enqueue(String(i), run(String(i))), + ); + expect(starts).toEqual(["0"]); + const selected = queue.enqueue("19", run("19"), true); + expect(selected === jobs[19]).toBe(true); + for (let i = 0; i < 20; i++) { + finishes.shift()?.(); + for (let tick = 0; tick < 8; tick++) await Promise.resolve(); + } + expect(await Promise.all(jobs)).toHaveLength(20); + expect(starts.slice(0, 2)).toEqual(["0", "19"]); + expect(maximum).toBe(1); + expect(at).toBe(19 * 150); + await queue.dispose(); +}); + +test("disposing cancels only owned queued and active HTTP jobs", async () => { + const queue = createClaudeCollectionQueue({ staggerMs: 0 }); + let ranSibling = false; + const active = queue.enqueue("active", async (signal) => { + await new Promise((resolve) => + signal.addEventListener("abort", () => resolve(), { once: true }), + ); + throw new Error("owned abort"); + }); + const waiting = queue.enqueue("waiting", async () => { + ranSibling = true; + }); + const activeCheck = active.catch((error: Error) => error.message); + const waitingCheck = waiting.catch((error: Error) => error.message); + await queue.dispose(); + expect(await activeCheck).toBe("owned abort"); + expect(await waitingCheck).toBe("Usage collection cancelled."); + expect(ranSibling).toBe(false); +}); + +test("a collector can restart after disposal settles while listeners remain safely owned", async () => { + const owner = createRestartableClaudeCollectionQueue({ staggerMs: 0 }); + let release!: () => void; + let notifications = 0; + let premature = false; + const unsubscribe = owner.subscribe(() => { + notifications++; + }); + const first = owner.enqueue("old", async (signal) => { + await new Promise((resolve) => { + release = resolve; + }); + expect(signal.aborted).toBe(true); + return 1; + }); + const disposing = owner.dispose(); + const refused = await owner + .enqueue("premature", async () => { + premature = true; + }) + .catch((error: Error) => error.message); + expect(refused).toBe("Usage collector is closing."); + expect(premature).toBe(false); + expect(owner.dispose()).toBe(disposing); + release(); + await disposing; + expect(await first).toBe(1); + expect(await owner.enqueue("new", async () => 2)).toBe(2); + expect(notifications).toBe(1); + unsubscribe(); + await owner.enqueue("unsubscribed", async () => 3); + expect(notifications).toBe(1); + await owner.dispose(); +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-collection-queue.ts b/packages/host-service/src/trpc/router/usage/claude-collection-queue.ts new file mode 100644 index 00000000000..1baa4e3d5d9 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-collection-queue.ts @@ -0,0 +1,165 @@ +export function createClaudeCollectionQueue({ + now = Date.now, + sleep = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)), + staggerMs = 1_000, + capacity = 1024, +}: { + now?: () => number; + sleep?: (ms: number) => Promise; + staggerMs?: number; + capacity?: number; +} = {}) { + type Job = { + key: string; + priority: boolean; + run(signal: AbortSignal): Promise; + resolve(value: unknown): void; + reject(error: unknown): void; + promise: Promise; + controller: AbortController; + }; + const jobs = new Map(); + const listeners = new Set<() => void>(); + let running = false; + let disposed = false; + let lastStart = Number.NEGATIVE_INFINITY; + let active: Job | undefined; + let draining: Promise | undefined; + async function drain() { + if (running || disposed) return; + running = true; + try { + while (jobs.size && !disposed) { + const job = + [...jobs.values()].find((entry) => entry.priority) ?? + jobs.values().next().value; + if (!job) break; + const wait = staggerMs - (now() - lastStart); + if (wait > 0) await sleep(wait); + if (disposed) break; + lastStart = now(); + active = job; + try { + job.resolve(await job.run(job.controller.signal)); + } catch (error) { + job.reject(error); + } finally { + active = undefined; + jobs.delete(job.key); + for (const listener of listeners) { + try { + listener(); + } catch {} + } + } + } + } finally { + running = false; + } + } + return { + enqueue( + key: string, + run: (signal: AbortSignal) => Promise, + priority = false, + ): Promise { + if (disposed) + return Promise.reject(new Error("Usage collector is closed.")); + const existing = jobs.get(key); + if (existing) { + existing.priority ||= priority; + return existing.promise as Promise; + } + if (jobs.size >= capacity) + return Promise.reject(new Error("Usage collector is busy.")); + let resolve!: (value: unknown) => void; + let reject!: (value: unknown) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + jobs.set(key, { + key, + priority, + run, + resolve, + reject, + promise, + controller: new AbortController(), + }); + if (!running) draining = drain(); + return promise as Promise; + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + async dispose() { + disposed = true; + active?.controller.abort(); + for (const [key, job] of jobs) { + if (job === active) continue; + job.controller.abort(); + job.reject(new Error("Usage collection cancelled.")); + jobs.delete(key); + } + listeners.clear(); + await draining?.catch(() => {}); + }, + }; +} + +export function createRestartableClaudeCollectionQueue( + options: Parameters[0] = {}, +) { + let current: ReturnType | undefined; + let closing: Promise | undefined; + const listeners = new Set<() => void>(); + function queue() { + if (closing) throw new Error("Usage collector is closing."); + if (!current) { + current = createClaudeCollectionQueue(options); + current.subscribe(() => { + for (const listener of listeners) { + try { + listener(); + } catch {} + } + }); + } + return current; + } + return { + enqueue( + key: string, + run: (signal: AbortSignal) => Promise, + priority = false, + ): Promise { + try { + return queue().enqueue(key, run, priority); + } catch (error) { + return Promise.reject(error); + } + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + dispose(): Promise { + if (closing) return closing; + const previous = current; + if (!previous) return Promise.resolve(); + const operation = previous.dispose().finally(() => { + if (current === previous) current = undefined; + if (closing === operation) closing = undefined; + }); + closing = operation; + return operation; + }, + }; +} diff --git a/packages/host-service/src/trpc/router/usage/claude-last-known.test.ts b/packages/host-service/src/trpc/router/usage/claude-last-known.test.ts new file mode 100644 index 00000000000..ea8e2407682 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-last-known.test.ts @@ -0,0 +1,166 @@ +import { expect, test } from "bun:test"; +import { + chmod, + link, + mkdtemp, + readFile, + rm, + stat, + symlink, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createClaudeLastKnownStore } from "./claude-last-known"; +import type { UsageQuotaWindow } from "./types"; + +const profile = { + account: { uuid: "11111111-1111-4111-8111-111111111111" }, + organization: { uuid: "22222222-2222-4222-8222-222222222222" }, +}; +const at = Date.parse("2026-10-25T20:00:00Z"); +const windows = (): Array< + UsageQuotaWindow & { source: "provider"; observedAt: Date } +> => [ + { + id: "five_hour", + label: "Session (5h)", + usedPercent: 24, + resetsAt: new Date(at + 3600_000), + observedAt: new Date(at - 1000), + source: "provider", + }, + { + id: "seven_day", + label: "Weekly", + usedPercent: 52, + resetsAt: null, + observedAt: new Date(at), + source: "provider", + }, +]; + +test("restart retains only exact-token authenticated owner history with original per-window dates", async () => { + const root = await mkdtemp(join(tmpdir(), "claude-history-")); + try { + const path = join(root, "history.json"); + const store = createClaudeLastKnownStore(path, () => at); + await store.remember("private-fixture-token", profile, { + fetchedAt: new Date(at), + windows: windows(), + }); + const content = await readFile(path, "utf8"); + expect(content).not.toContain("private-fixture-token"); + expect(content).not.toContain(profile.account.uuid); + expect(content).not.toContain(profile.organization.uuid); + expect((await stat(path)).mode & 0o777).toBe(0o600); + const restarted = createClaudeLastKnownStore(path, () => at + 600_000); + expect(await restarted.get("private-fixture-token", profile)).toEqual({ + fetchedAt: new Date(at), + windows: windows(), + }); + expect(await restarted.get("rotated-token", profile)).toBeUndefined(); + expect( + await restarted.get("private-fixture-token", { + account: profile.account, + organization: { uuid: "33333333-3333-4333-8333-333333333333" }, + }), + ).toBeUndefined(); + expect( + await restarted.get("private-fixture-token", { + email: "display-only@example.test", + }), + ).toBeUndefined(); + await restarted.forget("private-fixture-token", profile); + expect( + await createClaudeLastKnownStore(path, () => at + 600_000).get( + "private-fixture-token", + profile, + ), + ).toBeUndefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("native observations cannot promote old provider history or add wallet/reset fields", async () => { + const store = createClaudeLastKnownStore(undefined, () => at + 5000); + await store.remember("fixture-token", profile, { + fetchedAt: new Date(at + 5000), + windows: [ + ...windows(), + { + id: "native", + label: "native", + usedPercent: 2, + resetsAt: null, + source: "claude_sdk", + observedAt: new Date(at + 5000), + }, + ], + }); + const result = await store.get("fixture-token", profile); + expect(result?.fetchedAt).toEqual(new Date(at)); + expect(result?.windows).toEqual(windows()); + expect(Object.keys(result ?? {}).sort()).toEqual(["fetchedAt", "windows"]); +}); + +test("future, expired and unverified history stays absent", async () => { + const store = createClaudeLastKnownStore(undefined, () => at); + await store.remember( + "fixture-token", + {}, + { fetchedAt: new Date(at), windows: windows() }, + ); + expect(await store.get("fixture-token", profile)).toBeUndefined(); + await store.remember("future", profile, { + fetchedAt: new Date(at + 1), + windows: windows().map((w) => ({ ...w, observedAt: new Date(at + 1) })), + }); + expect(await store.get("future", profile)).toBeUndefined(); + await store.remember("expired", profile, { + fetchedAt: new Date(at - 15 * 86400_000), + windows: windows().map((w) => ({ + ...w, + observedAt: new Date(at - 15 * 86400_000), + })), + }); + expect(await store.get("expired", profile)).toBeUndefined(); +}); + +test("unsafe history aliases and public-mode files cannot provide display authority", async () => { + const root = await mkdtemp(join(tmpdir(), "claude-history-safety-")); + try { + const path = join(root, "history.json"); + await createClaudeLastKnownStore(path, () => at).remember( + "fixture-token", + profile, + { fetchedAt: new Date(at), windows: windows() }, + ); + const alias = join(root, "alias.json"); + await symlink(path, alias); + expect( + await createClaudeLastKnownStore(alias, () => at).get( + "fixture-token", + profile, + ), + ).toBeUndefined(); + await rm(alias); + await link(path, alias); + expect( + await createClaudeLastKnownStore(path, () => at).get( + "fixture-token", + profile, + ), + ).toBeUndefined(); + await rm(alias); + await chmod(path, 0o644); + expect( + await createClaudeLastKnownStore(path, () => at).get( + "fixture-token", + profile, + ), + ).toBeUndefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-last-known.ts b/packages/host-service/src/trpc/router/usage/claude-last-known.ts new file mode 100644 index 00000000000..2b836dc3f71 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-last-known.ts @@ -0,0 +1,280 @@ +import { randomUUID } from "node:crypto"; +import { constants } from "node:fs"; +import { + lstat, + mkdir, + open, + rename, + unlink, + writeFile, +} from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { hashQuotaScope } from "./quota-cooldown-store"; +import { claudeProfileIdentity } from "./quota-identity"; +import type { UsageAccount, UsageQuotaWindow } from "./types"; + +const MAX_BYTES = 512 * 1024; +const MAX_RECORDS = 128; +const MAX_AGE_MS = 14 * 24 * 60 * 60_000; +type SavedWindow = Omit< + UsageQuotaWindow, + "resetsAt" | "observedAt" | "source" +> & { + resetsAt: number | null; + observedAt: number; + source: "provider"; +}; +type Saved = { key: string; fetchedAt: number; windows: SavedWindow[] }; + +function record(value: unknown): Record | null { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +function scope(accessToken: string, profile: unknown): string | null { + const identity = claudeProfileIdentity(profile); + return identity && accessToken.trim() + ? hashQuotaScope([ + "claude-last-known-v1", + accessToken, + hashQuotaScope([identity.principal, identity.organization]), + ]) + : null; +} + +function parseSaved(value: unknown, now: number): Saved | null { + const row = record(value); + if ( + !row || + typeof row.key !== "string" || + !/^[a-f0-9]{64}$/.test(row.key) || + typeof row.fetchedAt !== "number" || + !Number.isFinite(row.fetchedAt) || + row.fetchedAt < now - MAX_AGE_MS || + row.fetchedAt > now || + !Array.isArray(row.windows) || + row.windows.length < 1 || + row.windows.length > 32 + ) + return null; + const windows: SavedWindow[] = []; + for (const value of row.windows) { + const window = record(value); + if ( + !window || + typeof window.id !== "string" || + window.id.length > 128 || + typeof window.label !== "string" || + window.label.length > 256 || + typeof window.usedPercent !== "number" || + !Number.isFinite(window.usedPercent) || + window.usedPercent < 0 || + window.usedPercent > 100 || + window.source !== "provider" || + typeof window.observedAt !== "number" || + !Number.isFinite(window.observedAt) || + window.observedAt > row.fetchedAt || + window.observedAt < now - MAX_AGE_MS || + (window.resetsAt !== null && + (typeof window.resetsAt !== "number" || + !Number.isFinite(window.resetsAt) || + window.resetsAt < 0)) + ) + return null; + windows.push({ + id: window.id, + label: window.label, + usedPercent: window.usedPercent, + resetsAt: window.resetsAt as number | null, + observedAt: window.observedAt, + source: "provider", + }); + } + if (new Set(windows.map((window) => window.id)).size !== windows.length) + return null; + return { key: row.key, fetchedAt: row.fetchedAt, windows }; +} + +/** Display history only. A path, display email or replacement token grants no access. */ +export function createClaudeLastKnownStore( + path?: string, + now = () => Date.now(), +) { + const entries = new Map(); + let loaded: Promise | undefined; + let previous: Promise = Promise.resolve(); + async function load() { + if (!path) return; + try { + const file = await open( + path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const info = await file.stat(); + if ( + !info.isFile() || + info.nlink !== 1 || + info.size > MAX_BYTES || + (process.platform !== "win32" && + (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)) + ) + return; + const text = await file.readFile("utf8"); + if (Buffer.byteLength(text) > MAX_BYTES) return; + const state = record(JSON.parse(text)); + if ( + state?.version !== 1 || + !Array.isArray(state.entries) || + state.entries.length > MAX_RECORDS + ) + return; + for (const value of state.entries) { + const row = parseSaved(value, now()); + if (row) entries.set(row.key, row); + } + } finally { + await file.close(); + } + } catch { + // History is optional and never changes live quota or authentication. + } + } + async function persist() { + if (!path) return; + let temporary: string | undefined; + try { + const directory = dirname(path); + await mkdir(directory, { recursive: true, mode: 0o700 }); + const info = await lstat(directory); + if ( + !info.isDirectory() || + info.isSymbolicLink() || + (process.platform !== "win32" && + (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) + ) + return; + let rows = [...entries.values()] + .filter((entry) => parseSaved(entry, now()) !== null) + .sort((a, b) => b.fetchedAt - a.fetchedAt) + .slice(0, MAX_RECORDS); + let text = JSON.stringify({ version: 1, entries: rows }); + while (Buffer.byteLength(text) > MAX_BYTES) { + rows = rows.slice(0, -1); + text = JSON.stringify({ version: 1, entries: rows }); + } + temporary = `${path}.${randomUUID()}.tmp`; + await writeFile(temporary, text, { flag: "wx", mode: 0o600 }); + await rename(temporary, path); + } catch { + // Keep the dated in-memory observation if private storage is unavailable. + } finally { + if (temporary) await unlink(temporary).catch(() => {}); + } + } + function mutate(operation: () => Promise) { + const next = previous.then(async () => { + if (!loaded) loaded = load(); + await loaded; + await operation(); + }); + previous = next.catch(() => {}); + return next; + } + const display = (key: string | null) => { + const row = key ? entries.get(key) : undefined; + if (!row || !parseSaved(row, now())) return undefined; + return { + fetchedAt: new Date(row.fetchedAt), + windows: row.windows.map((window) => ({ + ...window, + resetsAt: window.resetsAt === null ? null : new Date(window.resetsAt), + observedAt: new Date(window.observedAt), + })), + }; + }; + return { + async getVerifiedOwner(accessToken: string, ownerHash: string) { + await previous; + if (!loaded) loaded = load(); + await loaded; + if (!accessToken.trim() || !/^[a-f0-9]{64}$/.test(ownerHash)) + return undefined; + return display( + hashQuotaScope(["claude-last-known-v1", accessToken, ownerHash]), + ); + }, + async get(accessToken: string, profile: unknown) { + await previous; + if (!loaded) loaded = load(); + await loaded; + return display(scope(accessToken, profile)); + }, + remember( + accessToken: string, + profile: unknown, + quota: Pick, + ) { + return mutate(async () => { + const key = scope(accessToken, profile); + if (!key) return; + const providerWindows = quota.windows.filter( + (window) => window.source === "provider" && window.observedAt, + ); + const acquiredAt = Math.max( + ...providerWindows.map( + (window) => window.observedAt?.getTime() ?? Number.NaN, + ), + ); + const row = parseSaved( + { + key, + fetchedAt: acquiredAt, + windows: providerWindows.map((window) => ({ + ...window, + resetsAt: window.resetsAt?.getTime() ?? null, + observedAt: + window.observedAt?.getTime() ?? quota.fetchedAt.getTime(), + source: "provider", + })), + }, + now(), + ); + if (!row) return; + if ((entries.get(key)?.fetchedAt ?? -1) > row.fetchedAt) return; + entries.delete(key); + entries.set(key, row); + while (entries.size > MAX_RECORDS) + entries.delete(entries.keys().next().value ?? ""); + await persist(); + }); + }, + forgetVerifiedOwner(accessToken: string, ownerHash: string) { + return mutate(async () => { + if (!accessToken.trim() || !/^[a-f0-9]{64}$/.test(ownerHash)) return; + const key = hashQuotaScope([ + "claude-last-known-v1", + accessToken, + ownerHash, + ]); + if (entries.delete(key)) await persist(); + }); + }, + forget(accessToken: string, profile: unknown) { + return mutate(async () => { + const key = scope(accessToken, profile); + if (key && entries.delete(key)) await persist(); + }); + }, + }; +} + +export const claudeLastKnown = createClaudeLastKnownStore( + join( + process.env.SUPERSET_HOME_DIR?.trim() || join(homedir(), ".superset"), + "state", + "claude-last-known.json", + ), +); diff --git a/packages/host-service/src/trpc/router/usage/claude-native.integration.test.ts b/packages/host-service/src/trpc/router/usage/claude-native.integration.test.ts new file mode 100644 index 00000000000..66f56f2da0f --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-native.integration.test.ts @@ -0,0 +1,174 @@ +import { afterAll, expect, mock, setSystemTime, spyOn, test } from "bun:test"; +import { createHash } from "node:crypto"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const profiles = await import("./profiles"); +const keychainServices = spyOn( + profiles, + "keychainServicesForConfigDir", +).mockReturnValue([]); +const directory = mkdtempSync(join(tmpdir(), "native-quota-integration-")); +const profile = join(directory, "profile"); +mkdirSync(profile, { mode: 0o700 }); +const originalHome = process.env.HOME; +const originalSuperset = process.env.SUPERSET_HOME_DIR; +const originalFlag = process.env.SUPERSET_NATIVE_CLAUDE_USAGE; +const originalFetch = globalThis.fetch; +const initial = Date.now(); +const principal = "11111111-1111-4111-8111-111111111111"; +const organization = "22222222-2222-4222-8222-222222222222"; +const email = "fixture@example.test"; +const token = "disposable-fixture-only"; +process.env.HOME = directory; +process.env.SUPERSET_HOME_DIR = join(directory, "superset"); +process.env.SUPERSET_NATIVE_CLAUDE_USAGE = "1"; +writeFileSync( + join(profile, ".credentials.json"), + JSON.stringify({ + claudeAiOauth: { + accessToken: token, + expiresAt: initial + 8 * 60 * 60_000, + subscriptionType: "max", + }, + }), + { mode: 0o600 }, +); +writeFileSync( + join(profile, ".claude.json"), + JSON.stringify({ + oauthAccount: { accountUuid: principal, emailAddress: email }, + }), + { mode: 0o600 }, +); +let usageRequests = 0; +const reset = Math.floor((initial + 5 * 60 * 60_000) / 1000); +const weekly = Math.floor((initial + 7 * 24 * 60 * 60_000) / 1000); +globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = input instanceof Request ? input.url : String(input); + const endpoint = new URL(url); + if ( + endpoint.origin === "https://api.anthropic.com" && + endpoint.pathname === "/api/oauth/usage" + ) { + usageRequests++; + return Response.json({ + five_hour: { + utilization: 10, + resets_at: new Date(reset * 1000).toISOString(), + }, + seven_day: { + utilization: 15, + resets_at: new Date(weekly * 1000).toISOString(), + }, + }); + } + if (url === "https://api.anthropic.com/api/oauth/profile") + return Response.json({ + account: { uuid: principal, email }, + organization: { uuid: organization }, + }); + return new Response(null, { status: 503 }); +}) as unknown as typeof fetch; +setSystemTime(initial); +afterAll(() => { + keychainServices.mockRestore(); + globalThis.fetch = originalFetch; + setSystemTime(); + if (originalHome === undefined) delete process.env.HOME; + else process.env.HOME = originalHome; + if (originalSuperset === undefined) delete process.env.SUPERSET_HOME_DIR; + else process.env.SUPERSET_HOME_DIR = originalSuperset; + if (originalFlag === undefined) + delete process.env.SUPERSET_NATIVE_CLAUDE_USAGE; + else process.env.SUPERSET_NATIVE_CLAUDE_USAGE = originalFlag; + rmSync(directory, { recursive: true, force: true }); +}); +const { + getCredentialQuota, + captureNativeClaudeUsageGeneration, + resolveNativeClaudeUsageScope, + disposeClaudeQuotaCollection, +} = await import("./claude"); +const { nativeClaudeUsage } = await import("./native-claude-usage"); +test("actual credential reader uses fresh bound native windows without another usage request", async () => { + const credential = { + accessToken: token, + expiresAt: initial + 8 * 60 * 60_000, + refreshTokenExpiresAt: null, + hasRefreshToken: false, + subscriptionType: "max", + accountKey: profile, + sourceLabel: "fixture", + selection: profile, + email, + }; + try { + const http = await getCredentialQuota(credential, true, "blocking"); + expect(http.status).toBe("ok"); + expect(usageRequests).toBe(1); + const identity = createHash("sha256") + .update(JSON.stringify([principal, undefined, email])) + .digest("hex"); + const generation = await captureNativeClaudeUsageGeneration( + profile, + profile, + identity, + ); + expect(generation).not.toBeNull(); + if (!generation) throw new Error("missing generation"); + const scope = await resolveNativeClaudeUsageScope( + profile, + profile, + identity, + generation, + ); + expect(scope).not.toBeNull(); + if (!scope) throw new Error("missing authenticated scope"); + const launch = { + launchId: "owned-integration-launch", + sessionId: "owned-integration-session", + generation, + }; + nativeClaudeUsage.captureLaunch(launch); + nativeClaudeUsage.promoteLaunch({ ...launch, scope }); + nativeClaudeUsage.ingest({ + receivedAt: Date.now(), + ...launch, + scope, + source: "claude_statusline", + payload: { cost: { total_api_duration_ms: 0 } }, + }); + setSystemTime(initial + 16 * 60_000); + nativeClaudeUsage.ingest({ + receivedAt: Date.now(), + ...launch, + scope, + source: "claude_statusline", + payload: { + cost: { total_api_duration_ms: 1 }, + rate_limits: { + five_hour: { used_percentage: 25, resets_at: reset }, + seven_day: { used_percentage: 30, resets_at: weekly }, + }, + }, + }); + const native = await getCredentialQuota(credential, false, "background"); + expect(native.windows.map((window) => window.usedPercent)).toEqual([ + 25, 30, + ]); + expect( + native.windows.every((window) => window.source === "claude_statusline"), + ).toBe(true); + expect(native.fetchedAt).toEqual(http.fetchedAt); + expect(usageRequests).toBe(1); + const forced = await getCredentialQuota(credential, true, "blocking"); + expect(forced.windows.map((window) => window.usedPercent)).toEqual([ + 10, 15, + ]); + expect(usageRequests).toBe(2); + } finally { + await disposeClaudeQuotaCollection(); + } +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-prepaid.test.ts b/packages/host-service/src/trpc/router/usage/claude-prepaid.test.ts new file mode 100644 index 00000000000..ccae9bf46fb --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-prepaid.test.ts @@ -0,0 +1,185 @@ +import { expect, test } from "bun:test"; +import { + createClaudePrepaidReader, + parseClaudePrepaidBalance, +} from "./claude-prepaid"; +import { createClaudeRequestClient } from "./claude-request"; +import { createQuotaCooldownStore } from "./quota-cooldown-store"; + +const checkedAt = new Date("2026-10-23T19:00:00Z"); +const profile = { + account: { uuid: "11111111-1111-4111-8111-111111111111" }, + organization: { uuid: "22222222-2222-4222-8222-222222222222" }, +}; + +test.each([ + [{ amount: 8871, currency: "USD" }, 88.71, "USD"], + [{ amount: 0, currency: "USD" }, 0, "USD"], + [{ amount: 0, currency: null, balance: null }, 0, null], + [ + { + amount: 5597, + currency: "EUR", + balance: { + money: { amount_minor: 5597, currency: "EUR", exponent: 2 }, + credits: null, + }, + promo_tranches: [{ money: null }], + }, + 55.97, + "EUR", + ], + [ + { + amount: 500, + balance: { money: { amount_minor: 500, currency: "JPY", exponent: 0 } }, + }, + 500, + "JPY", + ], + [ + { + currency: " usd ", + balance: { credits: { amount_minor: 8871, exponent: 2 } }, + }, + 88.71, + "USD", + ], +])("normalizes observed prepaid schemas without confusing spend caps: %j", (body, amount, currency) => { + expect(parseClaudePrepaidBalance(body, checkedAt)).toEqual({ + amount, + currency, + checkedAt, + }); +}); + +test.each([ + null, + [[]], + {}, + { monthly_limit: 10000, used_credits: 100 }, + { amount: "5597", currency: "USD" }, + { amount: true, currency: "USD" }, + { amount: -1, currency: "USD" }, + { amount: Infinity, currency: "USD" }, + { amount: Number.NaN, currency: "USD" }, + { amount: 100 }, + { amount: 100, currency: "" }, + { amount: 100, currency: "dollars" }, + { amount: 100, currency: "XYZ" }, + { amount: 100, currency: "JPY" }, + { amount: 100, currency: "BHD" }, + { amount: 100, currency: 123 }, + { amount: 100, currency: "USD", balance: [] }, + { amount: 100, currency: "USD", balance: { money: false } }, + { amount: 100, currency: "USD", balance: { credits: "100" } }, + { amount: 100, currency: "USD", balance: { money: { exponent: -1 } } }, + { amount: 100, currency: "USD", balance: { money: { exponent: 0.5 } } }, + { amount: 100, currency: "USD", balance: { money: { exponent: 100 } } }, + { amount: 100, currency: "USD", balance: { money: { exponent: "2" } } }, + { amount: 100, currency: "USD", balance: { money: { currency: "EUR" } } }, + { amount: 100, currency: "USD", balance: { money: { amount_minor: 200 } } }, +])("malformed or contradictory wallet data stays unavailable: %j", (body) => { + expect(parseClaudePrepaidBalance(body, checkedAt)).toBeUndefined(); +}); + +test("wallet 429 retains its exact owner balance and original date without pausing usage", async () => { + let at = checkedAt.getTime(), + calls = 0; + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(undefined, () => at), + now: () => at, + random: () => 0, + fetcher: async () => { + calls++; + return calls === 1 + ? Response.json({ amount: 8871, currency: "USD" }) + : new Response(null, { + status: 429, + headers: { "Retry-After": "600" }, + }); + }, + }); + const wallet = createClaudePrepaidReader({ + request: requests.request, + now: () => at, + }); + const signal = new AbortController().signal; + const first = await wallet.fetch("wallet-fixture", profile, signal); + expect(first).toEqual({ amount: 88.71, currency: "USD", checkedAt }); + at += 30 * 60_000; + expect(await wallet.fetch("wallet-fixture", profile, signal)).toEqual(first); + expect(calls).toBe(2); + at += 30_000; + expect(await wallet.fetch("wallet-fixture", profile, signal)).toEqual(first); + expect(calls).toBe(2); + expect(wallet.peek("other-token", profile)).toBeUndefined(); + expect( + wallet.peek("wallet-fixture", { account: profile.account }), + ).toBeUndefined(); + at += 31_000; + expect(wallet.peek("wallet-fixture", profile)).toBeUndefined(); +}); + +test("wallet denial and explicit currencyless zero remain distinct", async () => { + for (const status of [200, 403]) { + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(), + fetcher: async () => + status === 200 + ? Response.json({ amount: 0, currency: null, balance: null }) + : new Response(null, { status }), + }); + const wallet = createClaudePrepaidReader({ request: requests.request }); + const result = await wallet.fetch( + `wallet-zero-${status}`, + profile, + new AbortController().signal, + ); + if (status === 200) + expect(result).toMatchObject({ amount: 0, currency: null }); + else expect(result).toBeUndefined(); + } +}); + +test("cancelled optional refresh retains the exact dated wallet without accepting its late body or renewing its age", async () => { + let at = Date.parse("2026-10-25T20:00:00Z"); + const measuredAt = new Date(at); + const controller = new AbortController(); + let calls = 0; + const profile = { + account: { uuid: "11111111-1111-4111-8111-111111111111" }, + organization: { uuid: "22222222-2222-4222-8222-222222222222" }, + }; + const reader = createClaudePrepaidReader({ + now: () => at, + request: async () => { + calls++; + if (calls === 2) controller.abort(); + return Response.json({ amount: calls === 1 ? 8871 : 0, currency: "USD" }); + }, + }); + const original = await reader.fetch( + "fixture-aborted-wallet", + profile, + new AbortController().signal, + ); + at += 30 * 60_000; + const cancelled = await reader.fetch( + "fixture-aborted-wallet", + profile, + controller.signal, + ); + expect(cancelled).toEqual(original); + expect(cancelled?.amount).toBe(88.71); + expect(cancelled?.checkedAt).toEqual(measuredAt); + at += 1; + expect( + await reader.fetch( + "fixture-aborted-wallet", + profile, + new AbortController().signal, + ), + ).toEqual(original); + expect(calls).toBe(2); +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-prepaid.ts b/packages/host-service/src/trpc/router/usage/claude-prepaid.ts new file mode 100644 index 00000000000..7e7004c8043 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-prepaid.ts @@ -0,0 +1,178 @@ +import { createHash } from "node:crypto"; +import { + claudeRequests, + type createClaudeRequestClient, +} from "./claude-request"; +import { createCredentialQuotaCache } from "./credential-quota-cache"; +import { recordQuotaRetry } from "./quota-backoff"; +import { claudeProfileIdentity } from "./quota-identity"; +import type { UsageAccount } from "./types"; + +const supportedCurrencies = new Set(Intl.supportedValuesOf("currency")); + +function record(value: unknown): Record | null { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +export function parseClaudePrepaidBalance( + value: unknown, + checkedAt = new Date(), +): UsageAccount["prepaidBalance"] { + const root = record(value); + if (!root) return undefined; + const balance = record(root.balance); + const money = record(balance?.money); + const credits = record(balance?.credits); + if ( + (root.balance != null && !balance) || + (balance?.money != null && !money) || + (balance?.credits != null && !credits) + ) + return undefined; + const amount = root.amount ?? money?.amount_minor ?? credits?.amount_minor; + if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) + return undefined; + const currencies = [money?.currency, root.currency] + .filter((currency) => currency != null) + .map((currency) => + typeof currency === "string" ? currency.trim().toUpperCase() : "", + ); + const currency = currencies[0] ?? null; + if ( + (currency === null ? amount !== 0 : !supportedCurrencies.has(currency)) || + currencies.some((value) => value !== currency) + ) + return undefined; + const currencyExponent = currency + ? new Intl.NumberFormat(undefined, { + style: "currency", + currency, + }).resolvedOptions().maximumFractionDigits + : null; + // The legacy response omits its exponent for two-decimal currencies. + const exponent = + money?.exponent ?? + credits?.exponent ?? + (currencyExponent === 2 || amount === 0 ? 2 : undefined); + if ( + typeof exponent !== "number" || + !Number.isInteger(exponent) || + exponent < 0 || + exponent > 6 || + ![root.amount, money?.amount_minor, credits?.amount_minor] + .filter((value) => value != null) + .every((value) => value === amount) || + !Number.isFinite(checkedAt.getTime()) + ) + return undefined; + return { amount: amount / 10 ** exponent, currency, checkedAt }; +} + +function walletKey( + accessToken: string, + identity: NonNullable>, +) { + return createHash("sha256") + .update( + JSON.stringify([accessToken, identity.principal, identity.organization]), + ) + .digest("hex"); +} + +export function createClaudePrepaidReader({ + request = claudeRequests.request, + now = () => Date.now(), +}: { + request?: ReturnType["request"]; + now?: () => number; +} = {}) { + const wallets = createCredentialQuotaCache<{ + balance?: UsageAccount["prepaidBalance"]; + }>(30 * 60_000, now); + function peek(accessToken: string, profile: unknown) { + const identity = claudeProfileIdentity(profile); + if (!identity || !accessToken.trim()) return undefined; + const balance = wallets.peek(walletKey(accessToken, identity))?.value + .balance; + const measuredAt = balance?.checkedAt.getTime(); + return balance && + measuredAt !== undefined && + Number.isFinite(measuredAt) && + measuredAt <= now() && + now() - measuredAt <= 31 * 60_000 + ? { ...balance, checkedAt: new Date(balance.checkedAt) } + : undefined; + } + return { + peek, + async fetch( + accessToken: string, + profile: unknown, + signal: AbortSignal, + canonicalProfile?: string | null, + ) { + const identity = claudeProfileIdentity(profile); + if (!identity || !accessToken.trim() || signal.aborted) return undefined; + try { + const key = walletKey(accessToken, identity); + await wallets.get( + key, + async () => { + const previous = peek(accessToken, profile); + const response = await request( + "wallet", + accessToken, + `https://api.anthropic.com/api/oauth/organizations/${identity.organization}/prepaid/credits`, + { + method: "GET", + cache: "no-store", + redirect: "error", + headers: { + Authorization: `Bearer ${accessToken}`, + "anthropic-beta": "oauth-2025-04-20", + }, + signal, + }, + canonicalProfile, + ); + if (response.ok && signal.aborted) + return recordQuotaRetry( + { balance: previous }, + new Response(null, { status: 503 }), + ); + if (!response.ok) + return recordQuotaRetry( + { + balance: [408, 429, 500, 502, 503, 504, 529].includes( + response.status, + ) + ? previous + : undefined, + }, + response, + ); + const body: unknown = await response.json(); + if (signal.aborted) + return recordQuotaRetry( + { balance: previous }, + new Response(null, { status: 503 }), + ); + return { + balance: parseClaudePrepaidBalance(body, new Date(now())), + }; + }, + false, + ); + return peek(accessToken, profile); + } catch { + return peek(accessToken, profile); + } + }, + }; +} + +const prepaidReader = createClaudePrepaidReader(); +export const fetchClaudePrepaidBalance = prepaidReader.fetch; +export const peekClaudePrepaidBalance = prepaidReader.peek; diff --git a/packages/host-service/src/trpc/router/usage/claude-proof-store.test.ts b/packages/host-service/src/trpc/router/usage/claude-proof-store.test.ts new file mode 100644 index 00000000000..f6bcdacfad4 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-proof-store.test.ts @@ -0,0 +1,130 @@ +import { expect, test } from "bun:test"; +import { + chmodSync, + linkSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createClaudeProofStore } from "./claude-proof-store"; +import { + restoreClaudeQuotaIdentity, + verifiedClaudeQuotaOwner, + verifiedNativeClaudeQuotaScope, +} from "./quota-identity"; + +const profile = { + account: { + uuid: "11111111-1111-4111-8111-111111111111", + email: "fixture@example.test", + }, + organization: { uuid: "22222222-2222-4222-8222-222222222222" }, +}; +const at = 1_000_000; + +test("restart preserves only exact-token/path dated owner provenance and never native authorization", () => { + const root = mkdtempSync(join(tmpdir(), "claude-proof-")); + try { + const path = join(root, "proof.json"); + createClaudeProofStore(path, () => at).remember( + "private-fixture-token", + "/fixture/profile", + profile, + at - 1000, + ); + const serialized = readFileSync(path, "utf8"); + for (const secret of [ + "private-fixture-token", + "/fixture/profile", + profile.account.uuid, + profile.account.email, + profile.organization.uuid, + ]) + expect(serialized).not.toContain(secret); + expect(statSync(path).mode & 0o777).toBe(0o600); + const store = createClaudeProofStore(path, () => at + 1000); + const proof = store.get("private-fixture-token", "/fixture/profile"); + if (!proof) throw new Error("Fixture proof missing."); + expect(proof.verifiedAt).toBe(at - 1000); + expect(store.get("new-token", "/fixture/profile")).toBeNull(); + expect(store.get("private-fixture-token", "/other/profile")).toBeNull(); + expect(store.get("private-fixture-token", null)).toBeNull(); + const value = restoreClaudeQuotaIdentity({}, proof, at); + expect(verifiedClaudeQuotaOwner(value, at)?.verifiedAt).toEqual( + new Date(at - 1000), + ); + expect( + verifiedNativeClaudeQuotaScope( + value, + "private-fixture-token", + "/fixture/profile", + proof.registrationHash ?? "", + at, + ), + ).toBeNull(); + store.forget("private-fixture-token"); + expect( + createClaudeProofStore(path, () => at).get( + "private-fixture-token", + "/fixture/profile", + ), + ).toBeNull(); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("future/expired proof and unsafe aliases or permissions fail closed", () => { + const root = mkdtempSync(join(tmpdir(), "claude-proof-")); + try { + const path = join(root, "proof.json"); + const store = createClaudeProofStore(path, () => at); + store.remember("fixture-token", "/fixture/profile", profile, at + 1); + expect(store.get("fixture-token", "/fixture/profile")).toBeNull(); + store.remember("fixture-token", "/fixture/profile", profile, at); + expect( + createClaudeProofStore(path, () => at + 6 * 60 * 60_000 + 1).get( + "fixture-token", + "/fixture/profile", + ), + ).toBeNull(); + expect( + createClaudeProofStore(path, () => at - 1).get( + "fixture-token", + "/fixture/profile", + ), + ).toBeNull(); + const alias = join(root, "alias.json"); + symlinkSync(path, alias); + expect( + createClaudeProofStore(alias, () => at).get( + "fixture-token", + "/fixture/profile", + ), + ).toBeNull(); + rmSync(alias); + linkSync(path, alias); + expect( + createClaudeProofStore(path, () => at).get( + "fixture-token", + "/fixture/profile", + ), + ).toBeNull(); + rmSync(alias); + if (process.platform !== "win32") { + chmodSync(path, 0o644); + expect( + createClaudeProofStore(path, () => at).get( + "fixture-token", + "/fixture/profile", + ), + ).toBeNull(); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-proof-store.ts b/packages/host-service/src/trpc/router/usage/claude-proof-store.ts new file mode 100644 index 00000000000..e0f4c239b92 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-proof-store.ts @@ -0,0 +1,200 @@ +import { randomUUID } from "node:crypto"; +import { + closeSync, + constants, + fstatSync, + lstatSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { hashQuotaScope } from "./quota-cooldown-store"; +import { + type ClaudeQuotaProof, + claudeQuotaProof, + validClaudeQuotaProof, +} from "./quota-identity"; + +const MAX_RECORDS = 128; +const MAX_BYTES = 128 * 1024; +type Saved = ClaudeQuotaProof & { key: string; profileHash: string }; +const digest = (value: unknown): value is string => + typeof value === "string" && /^[a-f0-9]{64}$/.test(value); +function valid(value: unknown, now: number): value is Saved { + if (!value || typeof value !== "object") return false; + const row = value as Saved; + return ( + digest(row.key) && + digest(row.profileHash) && + validClaudeQuotaProof(row, now) + ); +} +const key = (token: string, canonicalProfile: string) => + hashQuotaScope(["claude-display-proof-v1", token, canonicalProfile]); + +/** Optional provenance, never credentials or launch authorization. All persisted identity is hashed. */ +export function createClaudeProofStore(path?: string, now = () => Date.now()) { + const entries = new Map(); + let loaded = false; + function load() { + if (loaded) return; + loaded = true; + if (!path) return; + try { + const parent = lstatSync(dirname(path)); + if ( + !parent.isDirectory() || + parent.isSymbolicLink() || + (process.platform !== "win32" && + (parent.uid !== process.getuid?.() || (parent.mode & 0o022) !== 0)) + ) + return; + const fd = openSync( + path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + let text: string; + try { + const info = fstatSync(fd); + if ( + !info.isFile() || + info.nlink !== 1 || + info.size > MAX_BYTES || + (process.platform !== "win32" && + ((info.mode & 0o077) !== 0 || info.uid !== process.getuid?.())) + ) + return; + text = readFileSync(fd, "utf8"); + if (Buffer.byteLength(text) > MAX_BYTES) return; + } finally { + closeSync(fd); + } + const state = JSON.parse(text); + if ( + state?.version !== 1 || + !Array.isArray(state.entries) || + state.entries.length > MAX_RECORDS + ) + return; + for (const row of state.entries) + if (valid(row, now())) + entries.set(row.key, { + key: row.key, + profileHash: row.profileHash, + tokenHash: row.tokenHash, + ownerHash: row.ownerHash, + registrationHash: row.registrationHash, + verifiedAt: row.verifiedAt, + }); + } catch { + /* An unsafe or unavailable cache grants no provenance. */ + } + } + function persist() { + if (!path) return; + let temporary: string | undefined; + try { + const directory = dirname(path); + mkdirSync(directory, { recursive: true, mode: 0o700 }); + const info = lstatSync(directory); + if ( + !info.isDirectory() || + info.isSymbolicLink() || + (process.platform !== "win32" && + (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) + ) + return; + const rows = [...entries.values()] + .filter((row) => valid(row, now())) + .sort((a, b) => b.verifiedAt - a.verifiedAt) + .slice(0, MAX_RECORDS); + const text = JSON.stringify({ version: 1, entries: rows }); + if (Buffer.byteLength(text) > MAX_BYTES) return; + temporary = `${path}.${randomUUID()}.tmp`; + writeFileSync(temporary, text, { flag: "wx", mode: 0o600 }); + renameSync(temporary, path); + } catch { + /* Keep the original in-memory proof if storage is unavailable. */ + } finally { + if (temporary) { + try { + unlinkSync(temporary); + } catch {} + } + } + } + function invalidateReplaced(token: string, canonicalProfile: string) { + const tokenHash = hashQuotaScope(token); + const profileHash = hashQuotaScope(canonicalProfile); + let changed = false; + for (const [identityKey, row] of entries) + if (row.profileHash === profileHash && row.tokenHash !== tokenHash) { + entries.delete(identityKey); + changed = true; + } + if (changed) persist(); + } + return { + get(token: string, canonicalProfile: string | null) { + load(); + if (!token.trim() || !canonicalProfile) return null; + invalidateReplaced(token, canonicalProfile); + const row = entries.get(key(token, canonicalProfile)); + if (!row || !valid(row, now()) || row.tokenHash !== hashQuotaScope(token)) + return null; + return { + tokenHash: row.tokenHash, + ownerHash: row.ownerHash, + registrationHash: row.registrationHash, + verifiedAt: row.verifiedAt, + }; + }, + remember( + token: string, + canonicalProfile: string | null, + profile: unknown, + verifiedAt: number, + ) { + load(); + if (!canonicalProfile) return; + const proof = claudeQuotaProof(token, profile, verifiedAt); + if (!proof || !validClaudeQuotaProof(proof, now())) return; + invalidateReplaced(token, canonicalProfile); + const identityKey = key(token, canonicalProfile); + const previous = entries.get(identityKey); + if (previous && previous.verifiedAt > verifiedAt) return; + entries.delete(identityKey); + entries.set(identityKey, { + key: identityKey, + profileHash: hashQuotaScope(canonicalProfile), + ...proof, + }); + while (entries.size > MAX_RECORDS) + entries.delete(entries.keys().next().value ?? ""); + persist(); + }, + forget(token: string) { + load(); + const tokenHash = hashQuotaScope(token); + let changed = false; + for (const [identityKey, proof] of entries) + if (proof.tokenHash === tokenHash) { + entries.delete(identityKey); + changed = true; + } + if (changed) persist(); + }, + }; +} +export const claudeProofStore = createClaudeProofStore( + join( + process.env.SUPERSET_HOME_DIR?.trim() || join(homedir(), ".superset"), + "state", + "claude-display-proofs.json", + ), +); diff --git a/packages/host-service/src/trpc/router/usage/claude-quota-polling.test.ts b/packages/host-service/src/trpc/router/usage/claude-quota-polling.test.ts new file mode 100644 index 00000000000..36cda5f3203 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-quota-polling.test.ts @@ -0,0 +1,86 @@ +import { expect, test } from "bun:test"; +import { + CLAUDE_ACTIVE_QUOTA_POLL_MS, + CLAUDE_IDLE_QUOTA_POLL_MS, + createClaudeQuotaPolling, +} from "./claude-quota-polling"; + +function binding(at: number) { + return { + agentId: "claude", + agentSessionId: "chat", + confirmedSessionId: "chat", + lastEventAt: at, + account: { + agent: "claude", + credentialKind: "subscription", + selection: "/profiles/active", + identity: "verified", + }, + }; +} + +test("recent exact account activity speeds only that profile and naturally returns to idle", () => { + let now = 1_000_000; + const polling = createClaudeQuotaPolling(() => now); + polling.register(() => [binding(1_000_000)]); + expect(polling.interval("/profiles/active")).toBe( + CLAUDE_ACTIVE_QUOTA_POLL_MS, + ); + expect(polling.interval("/profiles/sibling")).toBe(CLAUDE_IDLE_QUOTA_POLL_MS); + expect(polling.interval(null)).toBe(CLAUDE_IDLE_QUOTA_POLL_MS); + now += 5 * 60_000; + expect(polling.interval("/profiles/active")).toBe(CLAUDE_IDLE_QUOTA_POLL_MS); +}); + +test("recent imported activity can speed scheduling without granting native quota authority", () => { + const polling = createClaudeQuotaPolling(() => 1_000_000); + polling.register(() => [ + { ...binding(1_000_000), confirmedSessionId: undefined }, + ]); + expect(polling.interval("/profiles/active")).toBe( + CLAUDE_ACTIVE_QUOTA_POLL_MS, + ); + expect(polling.interval("/profiles/sibling")).toBe(CLAUDE_IDLE_QUOTA_POLL_MS); +}); + +test("ended, conflicting, foreign, future and nonfinite activity stays idle", () => { + const now = 1_000_000; + for (const change of [ + { confirmedSessionId: "different" }, + { agentSessionId: "" }, + { endedAt: now }, + { failureType: "session_identity_conflict" }, + { agentId: "codex" }, + { accountInvalid: true }, + { account: { ...binding(now).account, conflict: true } }, + { lastEventAt: now + 1 }, + { lastEventAt: Number.NaN }, + { account: { ...binding(now).account, credentialKind: "api-key" } }, + { account: { ...binding(now).account, identity: "" } }, + { account: { ...binding(now).account, agent: "codex" } }, + ]) { + const polling = createClaudeQuotaPolling(() => now); + polling.register(() => [{ ...binding(now), ...change }]); + expect(polling.interval("/profiles/active")).toBe( + CLAUDE_IDLE_QUOTA_POLL_MS, + ); + } +}); + +test("activity owners unregister independently, even when sharing one callback", () => { + const polling = createClaudeQuotaPolling(() => 1_000_000); + const source = () => [binding(1_000_000)]; + const first = polling.register(source); + const second = polling.register(source); + polling.register(() => { + throw new Error("unavailable source"); + }); + first(); + first(); + expect(polling.interval("/profiles/active")).toBe( + CLAUDE_ACTIVE_QUOTA_POLL_MS, + ); + second(); + expect(polling.interval("/profiles/active")).toBe(CLAUDE_IDLE_QUOTA_POLL_MS); +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-quota-polling.ts b/packages/host-service/src/trpc/router/usage/claude-quota-polling.ts new file mode 100644 index 00000000000..f24128b845b --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-quota-polling.ts @@ -0,0 +1,69 @@ +export const CLAUDE_ACTIVE_QUOTA_POLL_MS = 2 * 60_000; +export const CLAUDE_IDLE_QUOTA_POLL_MS = 10 * 60_000; +const RECENT_ACTIVITY_MS = 5 * 60_000; + +interface ClaudeQuotaActivity { + agentId: string; + agentSessionId?: string; + confirmedSessionId?: string; + endedAt?: number; + failureType?: string; + lastEventAt: number; + accountInvalid?: boolean; + account?: { + conflict?: boolean; + agent: string; + credentialKind: string; + selection: string | null; + identity: string; + }; +} + +/** Activity changes scheduling only; it never establishes quota or account authority. */ +export function createClaudeQuotaPolling(now = Date.now) { + const sources = new Map readonly ClaudeQuotaActivity[]>(); + return { + register(source: () => readonly ClaudeQuotaActivity[]) { + if (sources.size >= 32) + throw new Error("Too many usage activity owners."); + const owner = Symbol(); + sources.set(owner, source); + return () => { + sources.delete(owner); + }; + }, + interval(selection: string | null): number { + const at = now(); + for (const source of sources.values()) { + try { + if ( + source().some( + (binding) => + binding.agentId === "claude" && + binding.endedAt === undefined && + !!binding.agentSessionId && + (binding.confirmedSessionId === undefined || + binding.agentSessionId === binding.confirmedSessionId) && + binding.failureType !== "session_identity_conflict" && + !binding.accountInvalid && + !binding.account?.conflict && + binding.account?.agent === "claude" && + binding.account.credentialKind === "subscription" && + !!binding.account.identity && + binding.account.selection === selection && + Number.isFinite(binding.lastEventAt) && + binding.lastEventAt <= at && + at - binding.lastEventAt < RECENT_ACTIVITY_MS, + ) + ) + return CLAUDE_ACTIVE_QUOTA_POLL_MS; + } catch { + // An unavailable activity source cannot change identity or force a request. + } + } + return CLAUDE_IDLE_QUOTA_POLL_MS; + }, + }; +} + +export const claudeQuotaPolling = createClaudeQuotaPolling(); diff --git a/packages/host-service/src/trpc/router/usage/claude-request.test.ts b/packages/host-service/src/trpc/router/usage/claude-request.test.ts new file mode 100644 index 00000000000..d2e83409d54 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-request.test.ts @@ -0,0 +1,161 @@ +import { expect, test } from "bun:test"; +import { + chmod, + mkdtemp, + readFile, + rm, + stat, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createClaudeRequestClient } from "./claude-request"; +import { readQuotaRetryHint, recordQuotaRetry } from "./quota-backoff"; +import { + createQuotaCooldownStore, + hashQuotaScope, +} from "./quota-cooldown-store"; + +test("endpoint pauses survive restart and token rotation without cached replay extending a deadline", async () => { + const root = await mkdtemp(join(tmpdir(), "claude-cooldown-")); + try { + const file = join(root, "cooldowns.json"); + let at = 1000, + calls = 0; + const fetcher = async () => { + calls++; + return new Response(null, { + status: 429, + headers: { "Retry-After": "600" }, + }); + }; + const first = createClaudeRequestClient({ + store: createQuotaCooldownStore(file, () => at), + now: () => at, + random: () => 0, + fetcher, + }); + const response = await first.request( + "usage", + "fixture-token-private", + "https://example.test/usage", + {}, + "/fixture/profile", + ); + expect(readQuotaRetryHint(recordQuotaRetry({}, response))?.retryAt).toBe( + 601000, + ); + at = 600999; + const restarted = createClaudeRequestClient({ + store: createQuotaCooldownStore(file, () => at), + now: () => at, + random: () => 0, + fetcher, + }); + const replay = await restarted.request( + "usage", + "new-unknown-owner-token", + "https://example.test/usage", + {}, + "/fixture/profile", + ); + expect(readQuotaRetryHint(recordQuotaRetry({}, replay))?.retryAt).toBe( + 601000, + ); + expect(calls).toBe(1); + expect((await stat(file)).mode & 0o777).toBe(0o600); + const content = await readFile(file, "utf8"); + expect(content).not.toContain("fixture-token-private"); + expect(content).not.toContain("/fixture/profile"); + at++; + await restarted.request( + "usage", + "new-unknown-owner-token", + "https://example.test/usage", + {}, + "/fixture/profile", + ); + expect(calls).toBe(2); + const states = JSON.parse(await readFile(file, "utf8")).entries; + expect( + states.find( + (value: { key: string }) => + value.key === + hashQuotaScope([ + "claude-profile-pause-v1", + "usage", + "/fixture/profile", + ]), + ), + ).toMatchObject({ failures: 2, retryAt: 1201000 }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("profile and wallet pauses are independent, diagnostics bounded, and auth rejection never renews", async () => { + let at = 0, + calls = 0; + const client = createClaudeRequestClient({ + store: createQuotaCooldownStore(undefined, () => at), + now: () => at, + random: () => 0, + fetcher: (async (_url, init) => { + calls++; + return new Response(null, { + status: + new Headers(init?.headers).get("test-status") === "401" ? 401 : 503, + }); + }) as typeof fetch, + }); + await client.request("profile", "a", "https://example.test", {}); + await client.request("profile", "a", "https://example.test", {}); + await client.request("wallet", "a", "https://example.test", {}); + expect(calls).toBe(2); + for (let i = 0; i < 110; i++) { + at++; + await client.request("usage", "auth-fixture", "https://example.test", { + headers: { "test-status": "401" }, + }); + } + expect(client.diagnostics()).toHaveLength(96); + expect( + client + .diagnostics() + .every( + (value) => + value.status === 401 && + value.retryAt === 0 && + /^[a-f0-9]{64}$/.test(value.scope), + ), + ).toBe(true); +}); + +test("cooldown reader rejects aliased and publicly readable metadata", async () => { + const root = await mkdtemp(join(tmpdir(), "cooldown-private-")); + try { + const file = join(root, "state.json"), + other = join(root, "other.json"), + key = hashQuotaScope("fixture"); + const value = { + key, + kind: "rate_limit" as const, + status: 429, + failures: 1, + retryAt: 600000, + updatedAt: 0, + }; + createQuotaCooldownStore(file, () => 0).set(value); + await chmod(file, 0o644); + expect(createQuotaCooldownStore(file, () => 0).get(key)).toBeUndefined(); + await rm(file); + await writeFile(other, JSON.stringify({ version: 1, entries: [value] }), { + mode: 0o600, + }); + await symlink(other, file); + expect(createQuotaCooldownStore(file, () => 0).get(key)).toBeUndefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-request.ts b/packages/host-service/src/trpc/router/usage/claude-request.ts new file mode 100644 index 00000000000..7fa3c5a2cf7 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-request.ts @@ -0,0 +1,139 @@ +import { quotaRetryDelay, setQuotaResponseRetry } from "./quota-backoff"; +import { + type createQuotaCooldownStore, + hashQuotaScope, + type QuotaEndpoint, + quotaCooldownStore, +} from "./quota-cooldown-store"; + +type Store = ReturnType; +type Diagnostic = { + endpoint: QuotaEndpoint; + scope: string; + status: number; + retryAt: number; + at: number; + cached: boolean; +}; + +export function createClaudeRequestClient({ + store = quotaCooldownStore, + now = () => Date.now(), + random = Math.random, + fetcher = (...args: Parameters) => fetch(...args), +}: { + store?: Store; + now?: () => number; + random?: () => number; + fetcher?: ( + input: string | URL | Request, + init?: RequestInit, + ) => Promise; +} = {}) { + const diagnostics: Diagnostic[] = []; + function note(value: Diagnostic) { + diagnostics.push(value); + if (diagnostics.length > 96) diagnostics.shift(); + } + return { + diagnostics: () => diagnostics.map((value) => ({ ...value })), + async request( + endpoint: QuotaEndpoint, + accessToken: string, + url: string, + init: RequestInit, + canonicalProfile?: string | null, + ): Promise { + const keys = [hashQuotaScope(["claude-http-v1", endpoint, accessToken])]; + if (canonicalProfile) + keys.push( + hashQuotaScope([ + "claude-profile-pause-v1", + endpoint, + canonicalProfile, + ]), + ); + const pause = keys + .map((key) => store.get(key)) + .filter((entry) => entry !== undefined) + .sort((a, b) => b.retryAt - a.retryAt)[0]; + const scope = keys[0] as string; + if (pause && pause.retryAt > now()) { + note({ + endpoint, + scope, + status: pause.status, + retryAt: pause.retryAt, + at: now(), + cached: true, + }); + return setQuotaResponseRetry( + new Response(null, { + status: pause.status, + headers: { + "Retry-After": String(Math.ceil((pause.retryAt - now()) / 1000)), + }, + }), + pause.retryAt, + ); + } + if (init.signal?.aborted) throw new Error("Usage request cancelled."); + let response: Response; + try { + response = await fetcher(url, init); + } catch (error) { + if (init.signal?.aborted) throw error; + response = new Response(null, { status: 503 }); + } + if ([408, 429, 500, 502, 503, 504, 529].includes(response.status)) { + const failures = Math.min((pause?.failures ?? 0) + 1, 8); + const base = response.status === 429 ? 5 * 60_000 : 30_000; + const exponential = Math.min(30 * 60_000, base * 2 ** (failures - 1)); + const delay = Math.max( + quotaRetryDelay(response.headers.get("retry-after"), now()), + Math.min( + 30 * 60_000, + exponential + + (failures > 1 + ? Math.floor( + exponential * 0.2 * Math.max(0, Math.min(1, random())), + ) + : 0), + ), + ); + const retryAt = now() + delay; + for (const key of keys) + store.set({ + key, + kind: response.status === 429 ? "rate_limit" : "transient", + status: response.status, + failures, + retryAt, + updatedAt: now(), + }); + setQuotaResponseRetry(response, retryAt); + note({ + endpoint, + scope, + status: response.status, + retryAt, + at: now(), + cached: false, + }); + } else { + for (const key of keys) store.clear(key); + note({ + endpoint, + scope, + status: response.status, + retryAt: 0, + at: now(), + cached: false, + }); + } + return response; + }, + }; +} + +export const claudeRequests = createClaudeRequestClient(); diff --git a/packages/host-service/src/trpc/router/usage/claude-subscription.test.ts b/packages/host-service/src/trpc/router/usage/claude-subscription.test.ts new file mode 100644 index 00000000000..6987469e82a --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-subscription.test.ts @@ -0,0 +1,766 @@ +import { expect, test } from "bun:test"; +import { createClaudeLastKnownStore } from "./claude-last-known"; +import { createClaudeProofStore } from "./claude-proof-store"; +import { createClaudeRequestClient } from "./claude-request"; +import { createClaudeSubscriptionReader } from "./claude-subscription"; +import { createQuotaCooldownStore } from "./quota-cooldown-store"; +import { copyQuotaIdentity, verifiedClaudeQuotaOwner } from "./quota-identity"; +import { createQuotaRequestBudget } from "./quota-request"; + +const profile = { + account: { + uuid: "11111111-1111-4111-8111-111111111111", + email: "fixture@example.test", + }, + organization: { uuid: "22222222-2222-4222-8222-222222222222" }, +}; +const initialAt = Date.parse("2026-10-25T20:00:00Z"); +const usage = () => ({ + five_hour: { utilization: 24, resets_at: "2026-10-26T01:00:00Z" }, + seven_day: { utilization: 52, resets_at: null }, +}); + +test("usage outages retain dated exact-owner history, wallet and identity without retry bursts", async () => { + let at = initialAt; + let status = 200; + const calls = { usage: 0, profile: 0, wallet: 0 }; + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(undefined, () => at), + now: () => at, + random: () => 0, + fetcher: async (url, init) => { + expect(new URL(String(url)).origin).toBe("https://api.anthropic.com"); + expect(init?.redirect).toBe("error"); + if (String(url).endsWith("/profile")) { + calls.profile++; + return Response.json(profile); + } + if (String(url).endsWith("/prepaid/credits")) { + calls.wallet++; + return Response.json({ amount: 8871, currency: "USD" }); + } + calls.usage++; + return status === 200 + ? Response.json(usage()) + : new Response(null, { + status, + headers: { "Retry-After": "600" }, + }); + }, + }); + const reader = createClaudeSubscriptionReader({ + request: requests.request, + now: () => at, + history: createClaudeLastKnownStore(undefined, () => at), + }); + const first = await reader.read("fixture-success-then-outage"); + expect(first.status).toBe("ok"); + expect(first.prepaidBalance).toEqual({ + amount: 88.71, + currency: "USD", + checkedAt: new Date(initialAt), + }); + const owner = verifiedClaudeQuotaOwner(first, at); + expect(owner?.verifiedAt).toEqual(new Date(initialAt)); + expect(JSON.stringify(first)).not.toContain(owner?.identity ?? "impossible"); + at += 16 * 60_000; + status = 429; + const limited = await reader.read("fixture-success-then-outage"); + expect(limited.status).toBe("unavailable"); + expect(limited.windows).toEqual([]); + expect(limited.lastKnownUsage?.fetchedAt).toEqual(new Date(initialAt)); + expect(limited.lastKnownUsage?.windows).toEqual(first.windows); + expect(limited.prepaidBalance?.checkedAt).toEqual(new Date(initialAt)); + expect(verifiedClaudeQuotaOwner(limited, at)).toEqual(owner); + expect( + verifiedClaudeQuotaOwner(copyQuotaIdentity(limited, { ...limited }), at), + ).toEqual(owner); + const deadline = limited.retryAt; + at += 30_000; + const repeated = await reader.read("fixture-success-then-outage"); + expect(repeated.retryAt).toEqual(deadline); + expect(repeated.prepaidBalance?.checkedAt).toEqual(new Date(initialAt)); + expect(calls).toEqual({ usage: 2, profile: 1, wallet: 1 }); +}); + +test("unauthorized usage removes history and cached owner proof before a later transient result", async () => { + let at = initialAt; + let usageStatus = 200; + let profileStatus = 200; + let profileCalls = 0; + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(undefined, () => at), + now: () => at, + fetcher: async (url) => { + if (String(url).endsWith("/profile")) { + profileCalls++; + return profileStatus === 200 + ? Response.json(profile) + : new Response(null, { status: profileStatus }); + } + if (String(url).endsWith("/prepaid/credits")) + return new Response(null, { status: 403 }); + return usageStatus === 200 + ? Response.json(usage()) + : new Response(null, { status: usageStatus }); + }, + }); + const reader = createClaudeSubscriptionReader({ + request: requests.request, + now: () => at, + history: createClaudeLastKnownStore(undefined, () => at), + }); + await reader.read("fixture-auth-revocation"); + usageStatus = 401; + const revoked = await reader.read("fixture-auth-revocation"); + expect(revoked.lastKnownUsage).toBeUndefined(); + expect(revoked.prepaidBalance).toBeUndefined(); + expect(verifiedClaudeQuotaOwner(revoked, at)).toBeNull(); + usageStatus = 503; + profileStatus = 403; + at += 1000; + const unavailable = await reader.read("fixture-auth-revocation"); + expect(profileCalls).toBe(2); + expect(unavailable.lastKnownUsage).toBeUndefined(); + expect(verifiedClaudeQuotaOwner(unavailable, at)).toBeNull(); +}); + +test("missing authenticated principal or organization never enables wallet or owner history", async () => { + for (const body of [ + { email: "display@example.test" }, + { account: profile.account }, + { ...profile, account_uuid: "33333333-3333-4333-8333-333333333333" }, + ]) { + let walletCalls = 0; + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(), + fetcher: async (url) => { + if (String(url).endsWith("/profile")) return Response.json(body); + if (String(url).endsWith("/prepaid/credits")) { + walletCalls++; + return Response.json({ amount: 100, currency: "USD" }); + } + return Response.json(usage()); + }, + }); + const reader = createClaudeSubscriptionReader({ + request: requests.request, + history: createClaudeLastKnownStore(), + }); + const result = await reader.read("fixture-unverified-owner"); + expect(result.status).toBe("ok"); + expect(result.prepaidBalance).toBeUndefined(); + expect(verifiedClaudeQuotaOwner(result)).toBeNull(); + expect(walletCalls).toBe(0); + } +}); + +test("identity changes preserve valid quota while refusing another owner's history and balance", async () => { + let at = initialAt; + let activeProfile = profile; + let usageStatus = 200; + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(undefined, () => at), + now: () => at, + fetcher: async (url) => { + if (String(url).endsWith("/profile")) return Response.json(activeProfile); + if (String(url).endsWith("/prepaid/credits")) + return Response.json({ amount: 400, currency: "USD" }); + return usageStatus === 200 + ? Response.json(usage()) + : new Response(null, { status: usageStatus }); + }, + }); + const reader = createClaudeSubscriptionReader({ + request: requests.request, + now: () => at, + history: createClaudeLastKnownStore(undefined, () => at), + }); + const first = await reader.read("fixture-first-owner"); + at += 1000; + activeProfile = { + ...profile, + organization: { uuid: "33333333-3333-4333-8333-333333333333" }, + }; + usageStatus = 503; + const changed = await reader.read("fixture-replacement-token"); + expect(changed.lastKnownUsage).toBeUndefined(); + expect(changed.prepaidBalance).toBeUndefined(); + expect(verifiedClaudeQuotaOwner(changed, at)?.identity).not.toBe( + verifiedClaudeQuotaOwner(first, at)?.identity, + ); +}); + +test("malformed optional quota windows cannot erase valid basic windows or invent reset dates", async () => { + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(), + fetcher: async (url) => { + if (String(url).endsWith("/profile")) + return new Response(null, { status: 403 }); + return Response.json({ + five_hour: { utilization: 135, resets_at: "not-a-date" }, + seven_day: { utilization: "bad" }, + limits: { invalid: true }, + }); + }, + }); + const reader = createClaudeSubscriptionReader({ + request: requests.request, + history: createClaudeLastKnownStore(), + }); + const result = await reader.read("fixture-malformed-optional"); + expect(result.windows).toHaveLength(1); + expect(result.windows[0]).toMatchObject({ + id: "five_hour", + usedPercent: 100, + resetsAt: null, + source: "provider", + }); + expect(result.prepaidBalance).toBeUndefined(); +}); + +test("a freshly authenticated replacement token retains the same opaque owner without inheriting funds", async () => { + let status = 200; + const requests = createClaudeRequestClient({ + store: createQuotaCooldownStore(), + fetcher: async (url) => { + if (String(url).endsWith("/profile")) return Response.json(profile); + if (String(url).endsWith("/prepaid/credits")) + return Response.json({ amount: 100, currency: "USD" }); + return status === 200 + ? Response.json(usage()) + : new Response(null, { status }); + }, + }); + const reader = createClaudeSubscriptionReader({ + request: requests.request, + history: createClaudeLastKnownStore(), + }); + const original = await reader.read("fixture-before-rotation"); + status = 503; + const rotated = await reader.read("fixture-after-rotation"); + expect(verifiedClaudeQuotaOwner(rotated)?.identity).toBe( + verifiedClaudeQuotaOwner(original)?.identity, + ); + expect(rotated.lastKnownUsage).toBeUndefined(); + expect(rotated.prepaidBalance).toBeUndefined(); +}); + +test("a restart during provider outage retains exact dated display provenance and history, never a native proof", async () => { + const { mkdtemp, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { createClaudeProofStore } = await import("./claude-proof-store"); + const { verifiedNativeClaudeQuotaScope, claudeProfileRegistration } = + await import("./quota-identity"); + const root = await mkdtemp(join(tmpdir(), "claude-restart-")); + let at = initialAt; + let outage = false; + let unauthorized = false; + const fetcher = async (url: string | URL | Request) => { + if (String(url).endsWith("/profile")) + return outage + ? new Response(null, { status: 503 }) + : Response.json(profile); + if (String(url).endsWith("/prepaid/credits")) + return new Response(null, { status: 403 }); + return unauthorized + ? new Response(null, { status: 401 }) + : outage + ? new Response(null, { status: 429, headers: { "Retry-After": "600" } }) + : Response.json(usage()); + }; + const reader = () => + createClaudeSubscriptionReader({ + request: createClaudeRequestClient({ + fetcher, + store: createQuotaCooldownStore(), + now: () => at, + }).request, + now: () => at, + proofs: createClaudeProofStore(join(root, "proof.json"), () => at), + history: createClaudeLastKnownStore(join(root, "history.json"), () => at), + }); + try { + const context = { canonicalProfile: "/fixture/profile" }; + const first = await reader().read( + "fixture-restart-proof", + undefined, + context, + ); + const owner = verifiedClaudeQuotaOwner(first, at); + at += 16 * 60_000; + outage = true; + const restarted = await reader().read( + "fixture-restart-proof", + undefined, + context, + ); + expect(restarted.status).toBe("unavailable"); + expect(restarted.windows).toEqual([]); + expect(verifiedClaudeQuotaOwner(restarted, at)).toEqual(owner); + expect(restarted.lastKnownUsage?.fetchedAt).toEqual(new Date(initialAt)); + expect(restarted.lastKnownUsage?.windows).toEqual(first.windows); + expect( + verifiedNativeClaudeQuotaScope( + restarted, + "fixture-restart-proof", + "/fixture/profile", + claudeProfileRegistration(profile) ?? "", + at, + ), + ).toBeNull(); + const rotated = await reader().read( + "fixture-rotated-proof", + undefined, + context, + ); + expect(verifiedClaudeQuotaOwner(rotated, at)).toBeNull(); + expect(rotated.lastKnownUsage).toBeUndefined(); + unauthorized = true; + await reader().read("fixture-restart-proof", undefined, context); + unauthorized = false; + const afterRevocation = await reader().read( + "fixture-restart-proof", + undefined, + context, + ); + expect(verifiedClaudeQuotaOwner(afterRevocation, at)).toBeNull(); + expect(afterRevocation.lastKnownUsage).toBeUndefined(); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +function deadlineClock() { + let at = initialAt; + let nextId = 0; + const pending = new Map void }>(); + const now = () => at; + return { + now, + advance(milliseconds: number) { + at += milliseconds; + for (const [id, timer] of [...pending]) { + if (timer.at > at) continue; + pending.delete(id); + timer.callback(); + } + }, + createBudget: (milliseconds: number) => + createQuotaRequestBudget(milliseconds, now, { + set(callback, delay) { + const id = ++nextId; + pending.set(id, { at: at + delay, callback }); + return id as unknown as ReturnType; + }, + clear(timer) { + pending.delete(timer as unknown as number); + }, + }), + pending: () => pending.size, + }; +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +test("an optional profile timeout at the original deadline keeps admitted quota without inventing an owner", async () => { + const clock = deadlineClock(); + const started = deferred(); + const profileResponse = deferred(); + let optionalSignal: AbortSignal | null | undefined; + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: createClaudeLastKnownStore(undefined, clock.now), + request: async (endpoint, _token, _url, init) => { + if (endpoint === "usage") { + clock.advance(6_000); + return Response.json(usage()); + } + expect(endpoint).toBe("profile"); + optionalSignal = init.signal; + started.resolve(); + return profileResponse.promise; + }, + }); + const result = reader.read("fixture-optional-profile-timeout"); + await started.promise; + clock.advance(2_000); + const quota = await result; + expect(quota.status).toBe("ok"); + expect(quota.windows.map((window) => window.usedPercent)).toEqual([24, 52]); + expect(quota.fetchedAt).toEqual(new Date(initialAt + 6_000)); + expect( + quota.windows.every( + (window) => window.observedAt?.getTime() === initialAt + 6_000, + ), + ).toBe(true); + expect(quota.prepaidBalance).toBeUndefined(); + expect(verifiedClaudeQuotaOwner(quota, clock.now())).toBeNull(); + expect(optionalSignal?.aborted).toBe(true); + expect(clock.pending()).toBe(0); + profileResponse.resolve(Response.json(profile)); +}); + +test("a timed-out optional wallet keeps its dated balance and current quota as separate observations", async () => { + const clock = deadlineClock(); + const started = deferred(); + const walletResponse = deferred(); + let stallWallet = false; + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: createClaudeLastKnownStore(undefined, clock.now), + request: async (endpoint) => { + if (endpoint === "usage") { + if (stallWallet) clock.advance(6_000); + return Response.json(usage()); + } + if (endpoint === "profile") return Response.json(profile); + if (stallWallet) { + started.resolve(); + return walletResponse.promise; + } + return Response.json({ amount: 8871, currency: "USD" }); + }, + }); + const original = await reader.read("fixture-optional-wallet-timeout"); + clock.advance(30 * 60_000); + stallWallet = true; + const result = reader.read("fixture-optional-wallet-timeout"); + await started.promise; + clock.advance(2_000); + const quota = await result; + expect(quota.status).toBe("ok"); + expect(quota.windows.map((window) => window.usedPercent)).toEqual([24, 52]); + expect(quota.prepaidBalance).toEqual(original.prepaidBalance); + expect(quota.prepaidBalance?.checkedAt).toEqual(new Date(initialAt)); + expect(quota.fetchedAt).toEqual(new Date(initialAt + 30 * 60_000 + 6_000)); + expect(clock.pending()).toBe(0); + walletResponse.resolve(new Response(null, { status: 503 })); +}); + +test("the primary deadline still rejects a response that has not arrived", async () => { + const clock = deadlineClock(); + const started = deferred(); + const response = deferred(); + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: createClaudeLastKnownStore(undefined, clock.now), + request: async () => { + started.resolve(); + return response.promise; + }, + }); + const result = reader.read("fixture-primary-deadline"); + await started.promise; + clock.advance(8_000); + const quota = await result; + expect(quota.status).toBe("unavailable"); + expect(quota.windows).toEqual([]); + expect(quota.prepaidBalance).toBeUndefined(); + expect(clock.pending()).toBe(0); + response.resolve(Response.json(usage())); +}); + +test.each([ + 401, 403, +])("a late explicit profile denial %i revokes cached proof after the optional deadline", async (status) => { + const clock = deadlineClock(); + const started = deferred(); + const response = deferred(); + const forgotten = deferred(); + const token = `fixture-late-profile-denial-${status}`; + const canonical = "/fixture/late-profile-denial"; + const store = createClaudeProofStore(undefined, clock.now); + store.remember(token, canonical, profile, clock.now()); + expect(store.get(token, canonical)).not.toBeNull(); + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: createClaudeLastKnownStore(undefined, clock.now), + proofs: { + ...store, + forget(value) { + store.forget(value); + forgotten.resolve(); + }, + }, + request: async (endpoint) => { + if (endpoint === "usage") { + clock.advance(6_000); + return Response.json(usage()); + } + expect(endpoint).toBe("profile"); + started.resolve(); + return response.promise; + }, + }); + const result = reader.read(token, undefined, { canonicalProfile: canonical }); + await started.promise; + clock.advance(2_000); + expect((await result).status).toBe("ok"); + response.resolve(new Response(null, { status })); + await forgotten.promise; + expect(store.get(token, canonical)).toBeNull(); + expect(clock.pending()).toBe(0); +}); + +test.each([ + 401, 403, +])("a primary denial %i arriving after cancellation still revokes exact-token provenance", async (status) => { + const clock = deadlineClock(); + const started = deferred(); + const deniedResponse = deferred(); + const forgotten = deferred(); + const token = `fixture-late-primary-denial-${status}`; + const canonical = "/fixture/late-primary-denial"; + const store = createClaudeProofStore(undefined, clock.now); + let mode: "ok" | "delayed" | "unavailable" = "ok"; + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: createClaudeLastKnownStore(undefined, clock.now), + proofs: { + ...store, + forget(value) { + store.forget(value); + forgotten.resolve(); + }, + }, + request: async (endpoint) => { + if (endpoint === "profile") + return mode === "ok" + ? Response.json(profile) + : new Response(null, { status: 503 }); + if (endpoint === "wallet") return new Response(null, { status: 403 }); + if (mode === "delayed") { + started.resolve(); + return deniedResponse.promise; + } + return mode === "ok" + ? Response.json(usage()) + : new Response(null, { status: 503 }); + }, + }); + await reader.read(token, undefined, { canonicalProfile: canonical }); + expect(store.get(token, canonical)).not.toBeNull(); + mode = "delayed"; + const result = reader.read(token, undefined, { canonicalProfile: canonical }); + await started.promise; + clock.advance(8_000); + expect((await result).status).toBe("unavailable"); + deniedResponse.resolve(new Response(null, { status })); + await forgotten.promise; + expect(store.get(token, canonical)).toBeNull(); + mode = "unavailable"; + const after = await reader.read(token, undefined, { + canonicalProfile: canonical, + }); + expect(after.lastKnownUsage).toBeUndefined(); + expect(verifiedClaudeQuotaOwner(after, clock.now())).toBeNull(); + expect(clock.pending()).toBe(0); +}); + +test("a stalled history write is bounded without discarding admitted quota or queueing later writes", async () => { + const clock = deadlineClock(); + const started = deferred(); + const saved = deferred(); + let writes = 0; + const history = createClaudeLastKnownStore(undefined, clock.now); + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: { + ...history, + remember: async () => { + writes++; + started.resolve(); + return saved.promise; + }, + }, + request: async (endpoint) => + endpoint === "usage" + ? Response.json(usage()) + : endpoint === "profile" + ? Response.json(profile) + : new Response(null, { status: 403 }), + }); + const first = reader.read("fixture-stalled-history-write"); + await started.promise; + clock.advance(8_000); + const quota = await first; + expect(quota.status).toBe("ok"); + expect(quota.windows.map((window) => window.usedPercent)).toEqual([24, 52]); + expect(quota.fetchedAt).toEqual(new Date(initialAt)); + expect( + quota.windows.every((window) => window.observedAt?.getTime() === initialAt), + ).toBe(true); + expect((await reader.read("fixture-stalled-history-write")).status).toBe( + "ok", + ); + expect(writes).toBe(1); + expect(clock.pending()).toBe(0); + saved.resolve(); +}); + +test("a stalled history read cannot delay an outage result or refresh the wallet's date", async () => { + const clock = deadlineClock(); + const started = deferred(); + const historyResult = deferred(); + let outage = false; + let reads = 0; + const history = createClaudeLastKnownStore(undefined, clock.now); + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: { + ...history, + get: async () => { + reads++; + started.resolve(); + return historyResult.promise; + }, + }, + request: async (endpoint) => + endpoint === "usage" + ? outage + ? new Response(null, { status: 503 }) + : Response.json(usage()) + : endpoint === "profile" + ? Response.json(profile) + : Response.json({ amount: 8871, currency: "USD" }), + }); + const original = await reader.read("fixture-stalled-history-read"); + outage = true; + const pending = reader.read("fixture-stalled-history-read"); + await started.promise; + clock.advance(8_000); + const quota = await pending; + expect(quota.status).toBe("unavailable"); + expect(quota.lastKnownUsage).toBeUndefined(); + expect(quota.prepaidBalance).toEqual(original.prepaidBalance); + expect(quota.prepaidBalance?.checkedAt).toEqual(new Date(initialAt)); + expect( + (await reader.read("fixture-stalled-history-read")).lastKnownUsage, + ).toBeUndefined(); + expect(reads).toBe(1); + expect(clock.pending()).toBe(0); + historyResult.resolve(undefined); +}); + +test("denial quarantines provenance before a stalled history deletion and never queues a second deletion", async () => { + const clock = deadlineClock(); + const started = deferred(); + const deleted = deferred(); + const token = "fixture-stalled-history-denial"; + const canonical = "/fixture/stalled-history-denial"; + const proofs = createClaudeProofStore(undefined, clock.now); + let usageStatus = 200; + let deletes = 0; + let ownerDeletes = 0; + const history = createClaudeLastKnownStore(undefined, clock.now); + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + proofs, + history: { + ...history, + forget: async () => { + deletes++; + started.resolve(); + return deleted.promise; + }, + forgetVerifiedOwner: async () => { + ownerDeletes++; + }, + }, + request: async (endpoint) => + endpoint === "usage" + ? usageStatus === 200 + ? Response.json(usage()) + : new Response(null, { status: usageStatus }) + : endpoint === "profile" + ? Response.json(profile) + : new Response(null, { status: 403 }), + }); + await reader.read(token, undefined, { canonicalProfile: canonical }); + expect(proofs.get(token, canonical)).not.toBeNull(); + usageStatus = 401; + const result = reader.read(token, undefined, { canonicalProfile: canonical }); + await started.promise; + expect(proofs.get(token, canonical)).toBeNull(); + clock.advance(8_000); + const denied = await result; + expect(denied.status).toBe("token_expired"); + expect(verifiedClaudeQuotaOwner(denied, clock.now())).toBeNull(); + usageStatus = 503; + const unavailable = await reader.read(token, undefined, { + canonicalProfile: canonical, + }); + expect(unavailable.lastKnownUsage).toBeUndefined(); + expect(verifiedClaudeQuotaOwner(unavailable, clock.now())).toBeNull(); + expect(deletes).toBe(1); + expect(ownerDeletes).toBe(0); + expect(clock.pending()).toBe(0); + deleted.resolve(); +}); + +test("one stalled account's history write cannot starve another account or queue duplicate writes", async () => { + const clock = deadlineClock(); + const started = deferred(); + const saved = deferred(); + const finished = deferred(); + const firstToken = "fixture-history-scope-stalled"; + const secondToken = "fixture-history-scope-healthy"; + const writes: string[] = []; + const history = createClaudeLastKnownStore(undefined, clock.now); + const reader = createClaudeSubscriptionReader({ + now: clock.now, + createBudget: clock.createBudget, + history: { + ...history, + remember: async (token, account, quota) => { + writes.push(token); + if (token === firstToken) { + started.resolve(); + await saved.promise; + } + await history.remember(token, account, quota); + if (token === firstToken) finished.resolve(); + }, + }, + request: async (endpoint) => + endpoint === "usage" + ? Response.json(usage()) + : endpoint === "profile" + ? Response.json(profile) + : new Response(null, { status: 403 }), + }); + const first = reader.read(firstToken); + await started.promise; + const healthy = await reader.read(secondToken); + expect(healthy.status).toBe("ok"); + expect(writes).toEqual([firstToken, secondToken]); + const persisted = await history.get(secondToken, profile); + if (!persisted) throw new Error("Healthy account history was not saved"); + expect(persisted.fetchedAt).toEqual(new Date(initialAt)); + expect(healthy.windows).toEqual(persisted.windows); + clock.advance(8_000); + const stalled = await first; + expect(stalled.status).toBe("ok"); + expect(stalled.fetchedAt).toEqual(new Date(initialAt)); + expect((await reader.read(firstToken)).status).toBe("ok"); + expect(writes).toEqual([firstToken, secondToken]); + expect(clock.pending()).toBe(0); + saved.resolve(); + await finished.promise; +}); diff --git a/packages/host-service/src/trpc/router/usage/claude-subscription.ts b/packages/host-service/src/trpc/router/usage/claude-subscription.ts new file mode 100644 index 00000000000..cef44c079d4 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/claude-subscription.ts @@ -0,0 +1,548 @@ +import { + claudeLastKnown, + type createClaudeLastKnownStore, +} from "./claude-last-known"; +import { createClaudePrepaidReader } from "./claude-prepaid"; +import { claudeProofStore, createClaudeProofStore } from "./claude-proof-store"; +import { + claudeRequests, + type createClaudeRequestClient, +} from "./claude-request"; +import { createCredentialQuotaCache } from "./credential-quota-cache"; +import { readQuotaRetryHint, recordQuotaRetry } from "./quota-backoff"; +import { hashQuotaScope } from "./quota-cooldown-store"; +import { + bindClaudeQuotaIdentity, + claudeProfileIdentity, + restoreClaudeQuotaIdentity, +} from "./quota-identity"; +import { + createQuotaRequestBudget, + OPTIONAL_QUOTA_BUDGET_MS, +} from "./quota-request"; +import type { + UsageAccount, + UsageAccountStatus, + UsageQuotaWindow, +} from "./types"; + +const USAGE_URL = "https://api.anthropic.com/api/oauth/usage"; +const PROFILE_URL = "https://api.anthropic.com/api/oauth/profile"; +const BETA = "oauth-2025-04-20"; +const TRANSIENT = new Set([408, 429, 500, 502, 503, 504, 529]); +const PROFILE_MAX_AGE_MS = 6 * 60 * 60_000; + +function validDate(value: unknown): Date | null { + if (typeof value !== "string") return null; + const date = new Date(value); + return Number.isFinite(date.getTime()) ? date : null; +} + +interface ClaudeUsageWindow { + utilization?: number; + resets_at?: string; +} + +interface ClaudeUsageResponse { + five_hour?: ClaudeUsageWindow; + seven_day?: ClaudeUsageWindow; + seven_day_sonnet?: ClaudeUsageWindow; + limits?: Array<{ + kind?: string; + percent?: number; + resets_at?: string; + scope?: { model?: { display_name?: string } }; + }>; + extra_usage?: { monthly_limit?: number; used_credits?: number }; +} + +interface ClaudeProfileResponse { + account?: { + uuid?: string; + email?: string; + email_address?: string; + emailAddress?: string; + }; + organization?: { uuid?: string }; + accountUuid?: string; + account_uuid?: string; + organizationUuid?: string; + organization_uuid?: string; + email?: string; +} + +function toWindow( + id: string, + label: string, + window: ClaudeUsageWindow | undefined, +): UsageQuotaWindow | null { + if ( + !window || + typeof window.utilization !== "number" || + !Number.isFinite(window.utilization) + ) + return null; + return { + id, + label, + usedPercent: Math.max(0, Math.min(100, Math.round(window.utilization))), + resetsAt: validDate(window.resets_at), + }; +} + +function mapWindows(usage: ClaudeUsageResponse): UsageQuotaWindow[] { + const windows: UsageQuotaWindow[] = []; + const session = toWindow("five_hour", "Session (5h)", usage.five_hour); + if (session) windows.push(session); + const weekly = toWindow("seven_day", "Weekly", usage.seven_day); + if (weekly) windows.push(weekly); + const sonnet = toWindow( + "seven_day_sonnet", + "Weekly · Sonnet", + usage.seven_day_sonnet, + ); + if (sonnet) windows.push(sonnet); + + for (const limit of Array.isArray(usage.limits) ? usage.limits : []) { + if (!limit || typeof limit !== "object") continue; + if ( + limit.kind !== "weekly_scoped" || + typeof limit.percent !== "number" || + !Number.isFinite(limit.percent) + ) { + continue; + } + const modelName = limit.scope?.model?.display_name; + if ( + typeof modelName !== "string" || + !modelName.trim() || + modelName.length > 200 + ) + continue; + const label = `Weekly · ${modelName}`; + if (windows.some((existing) => existing.label === label)) continue; + windows.push({ + id: `weekly_scoped:${modelName}`, + label, + usedPercent: Math.max(0, Math.min(100, Math.round(limit.percent))), + resetsAt: validDate(limit.resets_at), + }); + } + return windows; +} + +export interface ClaudeSubscriptionQuota { + email: string | null; + status: UsageAccountStatus; + statusDetail: string | null; + windows: UsageQuotaWindow[]; + extraUsage: UsageAccount["extraUsage"]; + fetchedAt?: Date; + retryAt?: Date; + lastKnownUsage?: UsageAccount["lastKnownUsage"]; + prepaidBalance?: UsageAccount["prepaidBalance"]; +} + +type Budgets = { primaryMs: number; profileMs: number }; +type Context = { canonicalProfile?: string | null; signal?: AbortSignal }; +type Request = ReturnType["request"]; + +export function createClaudeSubscriptionReader({ + request = claudeRequests.request, + now = () => Date.now(), + history = claudeLastKnown, + proofs = createClaudeProofStore(undefined, now), + createBudget = createQuotaRequestBudget, +}: { + request?: Request; + now?: () => number; + history?: ReturnType; + proofs?: ReturnType; + createBudget?: ( + budgetMs: number, + now: () => number, + ) => ReturnType; +} = {}) { + const profiles = createCredentialQuotaCache<{ + profile: ClaudeProfileResponse | null; + checkedAt: number; + }>( + (value) => + claudeProfileIdentity(value.profile) ? PROFILE_MAX_AGE_MS : 15 * 60_000, + now, + ); + const wallets = createClaudePrepaidReader({ request, now }); + const pending = new Map>(); + const revocations = new Map(); + let quarantineOverflow = false; + const historyInFlight = new Map>(); + function deny(token: string, canonical: string | null) { + const key = profileKey(token); + const previousProfile = cachedProfile(token); + const previousOwner = proofs.get(token, canonical); + if (revocations.has(key) || revocations.size < 1024) + revocations.set(key, { denied: true }); + else quarantineOverflow = true; + proofs.forget(token); + profiles.invalidate(key); + return { profile: previousProfile, ownerHash: previousOwner?.ownerHash }; + } + function historyQuarantined(token: string) { + return quarantineOverflow || revocations.has(profileKey(token)); + } + + function profileKey(token: string) { + return hashQuotaScope(["claude-profile-cache-v1", token]); + } + function cachedProfile(token: string) { + const value = profiles.peek(profileKey(token))?.value; + return value && + value.checkedAt <= now() && + now() - value.checkedAt <= PROFILE_MAX_AGE_MS + ? value.profile + : null; + } + async function fetchProfile( + token: string, + signal: AbortSignal, + canonical?: string | null, + ) { + signal.throwIfAborted(); + const key = profileKey(token); + await profiles.get(key, async () => { + const previous = profiles.peek(key)?.value; + const response = await request( + "profile", + token, + PROFILE_URL, + { + cache: "no-store", + redirect: "error", + signal, + headers: { Authorization: `Bearer ${token}`, "anthropic-beta": BETA }, + }, + canonical, + ); + if (!response.ok) { + if (response.status === 401 || response.status === 403) + deny(token, canonical ?? null); + else if (!TRANSIENT.has(response.status)) proofs.forget(token); + return recordQuotaRetry( + { + profile: TRANSIENT.has(response.status) + ? cachedProfile(token) + : null, + checkedAt: previous?.checkedAt ?? 0, + }, + response, + ); + } + signal.throwIfAborted(); + const body: unknown = await response.json(); + signal.throwIfAborted(); + const profile = + body && typeof body === "object" && !Array.isArray(body) + ? (body as ClaudeProfileResponse) + : null; + const checkedAt = now(); + if (claudeProfileIdentity(profile)) + proofs.remember(token, canonical ?? null, profile, checkedAt); + else proofs.forget(token); + return { profile, checkedAt }; + }); + signal.throwIfAborted(); + return cachedProfile(token); + } + async function acquire( + token: string, + budgets: Budgets, + context: Context, + ): Promise { + let profile = cachedProfile(token); + const budget = createBudget(budgets.primaryMs, now); + let deniedHistory: ReturnType | undefined; + async function optionalHistory( + load: (signal: AbortSignal) => Promise, + ): Promise { + const key = profileKey(token); + if (historyInFlight.has(key) || historyInFlight.size >= 1024) + return undefined; + try { + return await budget.run(async (signal) => { + signal.throwIfAborted(); + context.signal?.throwIfAborted(); + if (historyInFlight.has(key) || historyInFlight.size >= 1024) + return undefined; + const operation = Promise.resolve().then(() => { + signal.throwIfAborted(); + context.signal?.throwIfAborted(); + return load(signal); + }); + historyInFlight.set(key, operation); + const clear = () => { + if (historyInFlight.get(key) === operation) + historyInFlight.delete(key); + }; + void operation.then(clear, clear); + return operation; + }); + } catch { + return undefined; + } + } + const result = async ( + quota: ClaudeSubscriptionQuota, + response?: Response, + ) => { + const measuredAt = quota.fetchedAt ?? new Date(now()); + const bind = (value: T): T => { + if ( + quarantineOverflow || + revocations.get(profileKey(token))?.denied || + quota.status === "token_expired" + ) + return { + ...value, + lastKnownUsage: undefined, + prepaidBalance: undefined, + }; + const owner = profiles.peek(profileKey(token))?.value; + const persisted = proofs.get(token, context.canonicalProfile ?? null); + if (owner?.profile === profile && claudeProfileIdentity(profile)) + return bindClaudeQuotaIdentity( + value, + token, + profile, + owner.checkedAt, + ); + return persisted + ? restoreClaudeQuotaIdentity(value, persisted, now()) + : value; + }; + const value = { ...quota, fetchedAt: measuredAt }; + if (response && TRANSIENT.has(response.status)) { + const persisted = proofs.get(token, context.canonicalProfile ?? null); + const historical = !historyQuarantined(token) + ? await optionalHistory(() => + profile + ? history.get(token, profile) + : persisted + ? history.getVerifiedOwner(token, persisted.ownerHash) + : Promise.resolve(undefined), + ) + : undefined; + const lastKnownUsage = !historyQuarantined(token) + ? historical + : undefined; + const prepaidBalance = wallets.peek(token, profile); + const withHistory = { + ...value, + ...(lastKnownUsage ? { lastKnownUsage } : {}), + ...(prepaidBalance ? { prepaidBalance } : {}), + }; + recordQuotaRetry(withHistory, response); + const retryAt = readQuotaRetryHint(withHistory)?.retryAt; + if (retryAt) withHistory.retryAt = new Date(retryAt); + return bind(withHistory); + } + return bind(value); + }; + try { + const { response, usage, observedAt } = await budget.run( + async (budgetSignal) => { + const signal = context.signal + ? AbortSignal.any([budgetSignal, context.signal]) + : budgetSignal; + const primary = { + response: await request( + "usage", + token, + USAGE_URL, + { + cache: "no-store", + redirect: "error", + signal, + headers: { + Authorization: `Bearer ${token}`, + "anthropic-beta": BETA, + }, + }, + context.canonicalProfile, + ), + }; + if ( + primary.response.status === 401 || + primary.response.status === 403 + ) { + deniedHistory = deny(token, context.canonicalProfile ?? null); + profile = null; + return { ...primary, usage: null, observedAt: new Date(now()) }; + } + const usage = primary.response.ok + ? ((await primary.response.json()) as ClaudeUsageResponse) + : null; + signal.throwIfAborted(); + return { ...primary, usage, observedAt: new Date(now()) }; + }, + ); + if (response.status === 401 || response.status === 403) { + const previous = + deniedHistory ?? deny(token, context.canonicalProfile ?? null); + profile = null; + await optionalHistory(async (signal) => { + await history.forget(token, previous.profile); + signal.throwIfAborted(); + context.signal?.throwIfAborted(); + if (previous.ownerHash) + await history.forgetVerifiedOwner(token, previous.ownerHash); + }); + return result({ + email: null, + status: "token_expired", + statusDetail: "Sign-in expired — run /login in Claude Code.", + windows: [], + extraUsage: null, + }); + } + let windows: UsageQuotaWindow[] = []; + let extraUsage: UsageAccount["extraUsage"] = null; + if (usage) { + windows = mapWindows(usage).map((window) => ({ + ...window, + observedAt, + source: "provider" as const, + })); + const used = usage.extra_usage?.used_credits, + limit = usage.extra_usage?.monthly_limit; + if ( + typeof used === "number" && + Number.isFinite(used) && + used >= 0 && + typeof limit === "number" && + Number.isFinite(limit) && + limit >= 0 + ) + extraUsage = { usedCents: used, limitCents: limit }; + } + let prepaidBalance: UsageAccount["prepaidBalance"]; + try { + await budget.run(async (optionalSignal) => { + const combined = context.signal + ? AbortSignal.any([context.signal, optionalSignal]) + : optionalSignal; + profile = await fetchProfile( + token, + combined, + context.canonicalProfile, + ); + if (response.ok) + prepaidBalance = await wallets.fetch( + token, + profile, + combined, + context.canonicalProfile, + ); + }, budgets.profileMs); + } catch { + /* Optional reads use only the original deadline's remaining time. */ + } + prepaidBalance ??= wallets.peek(token, profile); + const email = + [ + profile?.account?.email, + profile?.account?.email_address, + profile?.account?.emailAddress, + profile?.email, + ].find((value) => typeof value === "string" && value.trim()) ?? null; + if (!response.ok) + return result( + { + email, + status: "unavailable", + statusDetail: `Usage endpoint returned ${response.status}.`, + windows: [], + extraUsage: null, + }, + response, + ); + const key = profileKey(token); + const revocation = revocations.get(key); + if ( + profiles.peek(key)?.value.profile === profile && + claudeProfileIdentity(profile) && + revocation + ) + revocation.denied = false; + if (windows.length) { + const saved = await optionalHistory(async () => { + await history.remember(token, profile, { + windows, + fetchedAt: observedAt, + }); + return true; + }); + if (saved && revocations.get(key) === revocation && !revocation?.denied) + revocations.delete(key); + } else await optionalHistory(() => history.forget(token, profile)); + return result({ + email, + status: windows.length || prepaidBalance ? "ok" : "unavailable", + statusDetail: + windows.length || prepaidBalance + ? null + : "No quota data returned (org-managed and education plans do not expose limits).", + windows, + extraUsage, + fetchedAt: observedAt, + ...(prepaidBalance ? { prepaidBalance } : {}), + }); + } catch { + return result( + { + email: null, + status: "unavailable", + statusDetail: "Usage request failed or timed out. Try again shortly.", + windows: [], + extraUsage: null, + }, + new Response(null, { status: 503 }), + ); + } + } + return { + read( + token: string, + budgets: Budgets = { + primaryMs: 8_000, + profileMs: OPTIONAL_QUOTA_BUDGET_MS, + }, + context: Context = {}, + ) { + const key = hashQuotaScope([ + "claude-acquire-v1", + token, + context.canonicalProfile ?? null, + ]); + const current = pending.get(key); + if (current) return current; + if (pending.size >= 1024) + return Promise.resolve({ + email: null, + status: "unavailable", + statusDetail: "Usage collector is busy. Try again shortly.", + windows: [], + extraUsage: null, + }); + const operation = acquire(token, budgets, context).finally(() => { + if (pending.get(key) === operation) pending.delete(key); + }); + pending.set(key, operation); + return operation; + }, + }; +} + +const subscriptionReader = createClaudeSubscriptionReader({ + proofs: claudeProofStore, +}); +export const fetchClaudeSubscriptionQuota = subscriptionReader.read; diff --git a/packages/host-service/src/trpc/router/usage/claude.ts b/packages/host-service/src/trpc/router/usage/claude.ts index 64d8d42debe..635bf55f8e8 100644 --- a/packages/host-service/src/trpc/router/usage/claude.ts +++ b/packages/host-service/src/trpc/router/usage/claude.ts @@ -14,27 +14,53 @@ import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; +import { createRestartableClaudeCollectionQueue } from "./claude-collection-queue"; +import { + CLAUDE_IDLE_QUOTA_POLL_MS, + claudeQuotaPolling, +} from "./claude-quota-polling"; +import { + type ClaudeSubscriptionQuota, + fetchClaudeSubscriptionQuota, +} from "./claude-subscription"; +import { createCredentialQuotaCache } from "./credential-quota-cache"; +import { + canDeferClaudeHttpQuota, + createNativeClaudeQuotaOverlay, +} from "./native-claude-overlay"; +import { + createNativeClaudeScopeResolver, + nativeClaudeCredentialGeneration, +} from "./native-claude-scope"; +import { nativeClaudeUsage } from "./native-claude-usage"; import { discoverClaudeProfiles, keychainServicesForConfigDir, readKeychainSecrets, } from "./profiles"; -import type { - UsageAccount, - UsageAccountStatus, - UsageQuotaWindow, -} from "./types"; +import { copyQuotaRetry } from "./quota-backoff"; +import type { QuotaSnapshot } from "./quota-cache"; +import { + parseQuotaCredentialJson, + QuotaCredentialReadError, + readQuotaCredentialFile, + type UnavailableQuotaSlot, + unavailableQuotaAccount, +} from "./quota-credentials"; +import { canonicalQuotaProfile, copyQuotaIdentity } from "./quota-identity"; +import { + createQuotaRequestBudget, + QUOTA_CAPTURE_BUDGET_MS, +} from "./quota-request"; +import type { UsageAccount } from "./types"; const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials"; -const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"; -const CLAUDE_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile"; -const CLAUDE_OAUTH_BETA_HEADER = "oauth-2025-04-20"; -const FETCH_TIMEOUT_MS = 10_000; export interface ClaudeOauthCredential { accessToken: string; expiresAt: number | null; refreshTokenExpiresAt: number | null; + hasRefreshToken?: boolean; subscriptionType: string | null; accountKey: string; sourceLabel: string; @@ -60,17 +86,32 @@ function parseCredential( accountKey: string, sourceLabel: string, selection: string | null, + strict = false, ): ClaudeOauthCredential | null { try { - const parsed: ClaudeCredentialFile = JSON.parse(raw); + const parsed: ClaudeCredentialFile = strict + ? parseQuotaCredentialJson(raw) + : JSON.parse(raw); const oauth = parsed.claudeAiOauth; + if ( + strict && + oauth !== undefined && + (typeof oauth !== "object" || + oauth === null || + typeof oauth.accessToken !== "string" || + !oauth.accessToken.trim()) + ) + throw new QuotaCredentialReadError(); if (!oauth?.accessToken) return null; return { accessToken: oauth.accessToken, expiresAt: typeof oauth.expiresAt === "number" ? oauth.expiresAt : null, + hasRefreshToken: + typeof oauth.refreshToken === "string" && + oauth.refreshToken.trim().length > 0, refreshTokenExpiresAt: typeof oauth.refreshToken === "string" && - oauth.refreshToken.length > 0 && + oauth.refreshToken.trim().length > 0 && typeof oauth.refreshTokenExpiresAt === "number" ? oauth.refreshTokenExpiresAt : null, @@ -83,6 +124,7 @@ function parseCredential( selection, }; } catch { + if (strict) throw new QuotaCredentialReadError(); return null; } } @@ -91,19 +133,26 @@ async function readCredentialFile( path: string, sourceLabel: string, selection: string | null, + strict = false, ): Promise { try { - const raw = await readFile(path, "utf-8"); - return parseCredential(raw, path, sourceLabel, selection); + const raw = strict + ? await readQuotaCredentialFile(path) + : await readFile(path, "utf-8"); + if (raw === null) return null; + return parseCredential(raw, path, sourceLabel, selection, strict); } catch { + if (strict) throw new QuotaCredentialReadError(); return null; } } /** The default login's Keychain item: the freshest of the items sharing its * service, since a sibling without a Claude login can sit beside it. */ -async function readKeychainCredential(): Promise { - const secrets = await readKeychainSecrets(CLAUDE_KEYCHAIN_SERVICE); +async function readKeychainCredential( + strict = false, +): Promise { + const secrets = await readKeychainSecrets(CLAUDE_KEYCHAIN_SERVICE, strict); return pickFreshest( secrets.map((secret) => parseCredential( @@ -111,6 +160,7 @@ async function readKeychainCredential(): Promise { `keychain:${CLAUDE_KEYCHAIN_SERVICE}`, "Keychain", null, + strict, ), ), ); @@ -129,7 +179,7 @@ export const EXPIRED_TOKEN_DETAIL = export function classifyLapsedToken( credential: Pick< ClaudeOauthCredential, - "expiresAt" | "refreshTokenExpiresAt" + "expiresAt" | "refreshTokenExpiresAt" | "hasRefreshToken" >, now = Date.now(), ): "live" | "token_stale" | "token_expired" { @@ -137,8 +187,9 @@ export function classifyLapsedToken( return "live"; } if ( - credential.refreshTokenExpiresAt !== null && - credential.refreshTokenExpiresAt > now + credential.refreshTokenExpiresAt === null + ? credential.hasRefreshToken === true + : credential.refreshTokenExpiresAt > now ) { return "token_stale"; } @@ -174,34 +225,52 @@ export function pickFreshest( } /** Identity of the default login, readable even when its token is expired. */ -export async function readDefaultLoginEmail(): Promise { +export async function readDefaultLoginEmail( + strict = false, +): Promise { try { - const parsed = JSON.parse( - await readFile(join(homedir(), ".claude.json"), "utf-8"), + const raw = strict + ? await readQuotaCredentialFile( + join(homedir(), ".claude.json"), + 50 * 1024 * 1024, + ) + : await readFile(join(homedir(), ".claude.json"), "utf-8"); + if (raw === null) return null; + const parsed = ( + strict ? parseQuotaCredentialJson(raw) : JSON.parse(raw) ) as { oauthAccount?: { emailAddress?: string } }; return parsed.oauthAccount?.emailAddress ?? null; } catch { + if (strict) throw new QuotaCredentialReadError(); return null; } } export async function readProfileCredential( profile: Awaited>[number], + strict = false, ): Promise { const fromFile = await readCredentialFile( profile.credentialsPath, profile.sourceLabel, profile.configDir, + strict, ); const candidates: Array = [fromFile]; - for (const service of profile.keychainServices) { - for (const secret of await readKeychainSecrets(service)) { + const serviceSecrets = await Promise.all( + profile.keychainServices.map((service) => + readKeychainSecrets(service, strict), + ), + ); + for (const secrets of serviceSecrets) { + for (const secret of secrets) { candidates.push( parseCredential( secret, profile.configDir, profile.sourceLabel, profile.configDir, + strict, ), ); } @@ -256,11 +325,82 @@ export async function readClaudeLoginFingerprint( * only the freshest of the three surfaces (a stale sibling would otherwise * render as a phantom expired account). */ -async function discoverClaudeCredentials(): Promise<{ +interface ClaudeQuotaInputs { credentials: ClaudeOauthCredential[]; signedOutProfiles: Awaited>; apiProfiles: Awaited>; -}> { + unavailableSlots?: UnavailableQuotaSlot[]; +} + +interface ClaudeCredentialSlot { + source: UnavailableQuotaSlot; + read: () => Promise; + profile?: Awaited>[number]; +} + +/** Keep unreadable slots separate from signed-out profiles and healthy logins. */ +export async function captureClaudeCredentialSlots( + slots: ClaudeCredentialSlot[], + apiProfiles: ClaudeQuotaInputs["apiProfiles"], +): Promise { + const apiSelections = new Set( + apiProfiles.map((profile) => profile.configDir), + ); + const results = await Promise.all( + slots + .filter((slot) => !apiSelections.has(slot.source.selection ?? "")) + .map(async (slot) => { + try { + return { slot, credential: await slot.read(), unavailable: false }; + } catch { + return { slot, credential: null, unavailable: true }; + } + }), + ); + const credentials = new Map(); + const unavailableSlots = new Map(); + const signedOutProfiles: ClaudeQuotaInputs["signedOutProfiles"] = []; + for (const { slot, unavailable } of results) { + if (unavailable) unavailableSlots.set(slot.source.selection, slot.source); + } + for (const { slot, credential, unavailable } of results) { + if (unavailable || unavailableSlots.has(slot.source.selection)) continue; + if (credential) { + credentials.set( + credential.selection, + pickFreshest([ + credentials.get(credential.selection) ?? null, + credential, + ]) ?? credential, + ); + } else if (!credential && slot.profile) + signedOutProfiles.push(slot.profile); + } + return { + credentials: [...credentials.values()], + signedOutProfiles, + apiProfiles, + unavailableSlots: [...unavailableSlots.values()], + }; +} + +export async function readDefaultQuotaCredential( + readCredentials: () => Promise>, + readEmail = readDefaultLoginEmail, +): Promise { + const [email, credentials] = await Promise.all([ + readEmail(true).catch(() => null), + readCredentials(), + ]); + const credential = pickFreshest(credentials); + return credential + ? { ...credential, email: credential.email ?? email } + : null; +} + +async function discoverClaudeCredentials( + strict = false, +): Promise { const home = homedir(); const defaultCandidates: Array<{ path: string; sourceLabel: string }> = [ { @@ -296,21 +436,69 @@ async function discoverClaudeCredentials(): Promise<{ const apiProfiles = allProfiles.filter( (profile) => profile.credentialKind === "api_key", ); + if (strict) { + return captureClaudeCredentialSlots( + [ + { + source: { + agent: "claude", + accountKey: `keychain:${CLAUDE_KEYCHAIN_SERVICE}`, + sourceLabel: "Default Claude login", + selection: null, + }, + read: () => + readDefaultQuotaCredential(async () => { + const [keychain, files] = await Promise.all([ + readKeychainCredential(true), + Promise.all( + defaultCandidates.map(({ path, sourceLabel }) => + readCredentialFile(path, sourceLabel, null, true), + ), + ), + ]); + return [keychain, ...files]; + }), + }, + ...explicitCandidates.map(({ path, sourceLabel, configDir }) => ({ + source: { + agent: "claude" as const, + accountKey: path, + sourceLabel, + selection: configDir, + }, + read: () => readCredentialFile(path, sourceLabel, configDir, true), + })), + ...profiles.map((profile) => ({ + source: { + agent: "claude" as const, + accountKey: profile.configDir, + sourceLabel: profile.sourceLabel, + selection: profile.configDir, + }, + read: () => readProfileCredential(profile, true), + profile, + })), + ], + apiProfiles, + ); + } const [defaultEmail, keychainCredential, defaultFiles, explicit, profiled] = await Promise.all([ - readDefaultLoginEmail(), - readKeychainCredential(), + readDefaultLoginEmail(strict), + readKeychainCredential(strict), Promise.all( defaultCandidates.map(({ path, sourceLabel }) => - readCredentialFile(path, sourceLabel, null), + readCredentialFile(path, sourceLabel, null, strict), ), ), Promise.all( explicitCandidates.map(({ path, sourceLabel, configDir }) => - readCredentialFile(path, sourceLabel, configDir), + readCredentialFile(path, sourceLabel, configDir, strict), ), ), - Promise.all(profiles.map(readProfileCredential)), + Promise.all( + profiles.map((profile) => readProfileCredential(profile, strict)), + ), ]); const defaultCredential = pickFreshest([keychainCredential, ...defaultFiles]); @@ -318,204 +506,229 @@ async function discoverClaudeCredentials(): Promise<{ defaultCredential.email = defaultEmail; } - const byToken = new Map(); + const byProfile = new Map(); for (const credential of [defaultCredential, ...explicit, ...profiled]) { - if (credential && !byToken.has(credential.accessToken)) { - byToken.set(credential.accessToken, credential); - } + if (credential) + byProfile.set( + credential.selection, + pickFreshest([ + byProfile.get(credential.selection) ?? null, + credential, + ]) ?? credential, + ); } + // Profiles with an identity but no readable credential (logged out, or a // login that died half-way) still surface so the UI can offer re-sign-in // and removal — otherwise the dir exists but nothing shows it. const signedOutProfiles = profiles.filter( (_profile, index) => profiled[index] === null, ); - return { credentials: [...byToken.values()], signedOutProfiles, apiProfiles }; -} - -interface ClaudeUsageWindow { - utilization?: number; - resets_at?: string; -} - -interface ClaudeUsageResponse { - five_hour?: ClaudeUsageWindow; - seven_day?: ClaudeUsageWindow; - seven_day_sonnet?: ClaudeUsageWindow; - limits?: Array<{ - kind?: string; - percent?: number; - resets_at?: string; - scope?: { model?: { display_name?: string } }; - }>; - extra_usage?: { monthly_limit?: number; used_credits?: number }; -} - -interface ClaudeProfileResponse { - account?: { email?: string; email_address?: string }; - email?: string; -} - -function toWindow( - id: string, - label: string, - window: ClaudeUsageWindow | undefined, -): UsageQuotaWindow | null { - if (!window || typeof window.utilization !== "number") return null; return { - id, - label, - usedPercent: Math.max(0, Math.round(window.utilization)), - resetsAt: window.resets_at ? new Date(window.resets_at) : null, + credentials: [...byProfile.values()], + signedOutProfiles, + apiProfiles, }; } -function mapWindows(usage: ClaudeUsageResponse): UsageQuotaWindow[] { - const windows: UsageQuotaWindow[] = []; - const session = toWindow("five_hour", "Session (5h)", usage.five_hour); - if (session) windows.push(session); - const weekly = toWindow("seven_day", "Weekly", usage.seven_day); - if (weekly) windows.push(weekly); - const sonnet = toWindow( - "seven_day_sonnet", - "Weekly · Sonnet", - usage.seven_day_sonnet, +export type { ClaudeSubscriptionQuota } from "./claude-subscription"; +export { fetchClaudeSubscriptionQuota } from "./claude-subscription"; + +export const CLAUDE_QUOTA_POLL_MS = 60_000; +const accountQuotaCache = createCredentialQuotaCache< + ClaudeSubscriptionQuota & { fetchedAt: Date } +>(CLAUDE_IDLE_QUOTA_POLL_MS); +const collectionQueue = createRestartableClaudeCollectionQueue(); +export const onClaudeQuotaUpdate = collectionQueue.subscribe; +export const disposeClaudeQuotaCollection = collectionQueue.dispose; +type CollectionMode = "blocking" | "background" | "skip"; +async function readNativeClaudeCredential(selection: string | null) { + const directory = selection ?? join(homedir(), ".claude"); + const canonical = await canonicalQuotaProfile(directory); + if (!canonical) return null; + const credential = + selection === null + ? await readDefaultQuotaCredential(() => + Promise.all([ + readKeychainCredential(true), + readCredentialFile( + join(homedir(), ".claude", ".credentials.json"), + "~/.claude", + null, + true, + ), + readCredentialFile( + join(homedir(), ".config", "claude", "credentials.json"), + "~/.config/claude", + null, + true, + ), + ]), + ) + : await readProfileCredential( + { + configDir: selection, + credentialsPath: join(selection, ".credentials.json"), + sourceLabel: selection, + email: null, + credentialKind: "subscription", + loginFingerprint: null, + keychainServices: keychainServicesForConfigDir(selection), + }, + true, + ); + if (!credential || classifyLapsedToken(credential) !== "live") return null; + const defaultDirectory = await canonicalQuotaProfile( + join(homedir(), ".claude"), ); - if (sonnet) windows.push(sonnet); - - for (const limit of usage.limits ?? []) { - if (limit.kind !== "weekly_scoped" || typeof limit.percent !== "number") { - continue; - } - const modelName = limit.scope?.model?.display_name; - if (!modelName) continue; - const label = `Weekly · ${modelName}`; - if (windows.some((existing) => existing.label === label)) continue; - windows.push({ - id: `weekly_scoped:${modelName}`, - label, - usedPercent: Math.max(0, Math.round(limit.percent)), - resetsAt: limit.resets_at ? new Date(limit.resets_at) : null, - }); - } - return windows; + const file = + canonical === defaultDirectory + ? join(homedir(), ".claude.json") + : join(directory, ".claude.json"); + const raw = await readQuotaCredentialFile(file, 50 * 1024 * 1024); + if (raw === null) return null; + const data = parseQuotaCredentialJson(raw); + const account = data.oauthAccount as + | { accountUuid?: unknown; emailAddress?: unknown } + | undefined; + if ( + typeof account?.accountUuid !== "string" || + !account.accountUuid || + typeof account.emailAddress !== "string" || + !account.emailAddress + ) + return null; + // Keep this tuple byte-for-byte aligned with session-account/readAccountIdentity. + const registrationHash = createHash("sha256") + .update( + JSON.stringify([account.accountUuid, undefined, account.emailAddress]), + ) + .digest("hex"); + return { + accessToken: credential.accessToken, + canonicalProfile: canonical, + registrationHash, + }; } - -async function fetchClaudeProfileEmail( - accessToken: string, -): Promise { - try { - const response = await fetch(CLAUDE_PROFILE_URL, { - headers: { - Authorization: `Bearer ${accessToken}`, - "anthropic-beta": CLAUDE_OAUTH_BETA_HEADER, +const nativeClaudeScope = createNativeClaudeScopeResolver({ + readCurrent: readNativeClaudeCredential, + canonicalize: canonicalQuotaProfile, + peekQuota: (accessToken) => + accountQuotaCache.peek( + createHash("sha256") + .update(JSON.stringify(["claude", accessToken])) + .digest("hex"), + )?.value, +}); +export const captureNativeClaudeUsageGeneration = + nativeClaudeScope.captureGeneration; +export const resolveNativeClaudeUsageScope = nativeClaudeScope.resolve; +const nativeQuotaOverlay = createNativeClaudeQuotaOverlay({ + enabled: () => process.env.SUPERSET_NATIVE_CLAUDE_USAGE === "1", + generation: nativeClaudeCredentialGeneration, + readCurrent: readNativeClaudeCredential, + resolveScope: nativeClaudeScope.resolve, + isCurrent: (accessToken, quota) => + accountQuotaCache.peek( + createHash("sha256") + .update(JSON.stringify(["claude", accessToken])) + .digest("hex"), + )?.value === quota, + snapshot: (scope) => nativeClaudeUsage.snapshot(scope), +}); + +export async function getCredentialQuota( + credential: ClaudeOauthCredential, + forceRefresh = false, + mode: CollectionMode = "blocking", +) { + const accessToken = credential.accessToken; + const key = createHash("sha256") + .update(JSON.stringify([credential.selection, accessToken])) + .digest("hex"); + const transport = createHash("sha256") + .update(JSON.stringify(["claude", accessToken])) + .digest("hex"); + const pollingMs = claudeQuotaPolling.interval(credential.selection ?? null); + const cached = accountQuotaCache.peek(transport)?.value; + const projectNative = async ( + quota: ClaudeSubscriptionQuota & { fetchedAt: Date }, + ) => { + const projected = await nativeQuotaOverlay(credential, quota); + return projected + ? copyQuotaRetry(quota, copyQuotaIdentity(quota, projected)) + : null; + }; + const passive = cached ? await projectNative(cached) : null; + if ( + !forceRefresh && + passive && + cached && + canDeferClaudeHttpQuota(cached, passive) + ) + return passive; + const load = async (signal?: AbortSignal) => + accountQuotaCache.get( + key, + async () => { + const profilePath = credential.selection ?? join(homedir(), ".claude"); + const canonical = await canonicalQuotaProfile(profilePath); + const expected = createHash("sha256").update(accessToken).digest("hex"); + if ( + mode !== "blocking" && + (await readClaudeLoginFingerprint(credential.selection)) !== expected + ) + throw new Error("Usage credentials changed before collection."); + const quota = await fetchClaudeSubscriptionQuota( + accessToken, + undefined, + { canonicalProfile: canonical, signal }, + ); + if ( + mode !== "blocking" && + ((await readClaudeLoginFingerprint(credential.selection)) !== + expected || + (await canonicalQuotaProfile(profilePath)) !== canonical) + ) + throw new Error("Usage credentials changed during collection."); + return copyQuotaRetry( + quota, + copyQuotaIdentity(quota, { + ...quota, + fetchedAt: quota.fetchedAt ?? new Date(), + }), + ); }, - signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), - }); - if (!response.ok) return null; - const profile = (await response.json()) as ClaudeProfileResponse; - return ( - profile.account?.email ?? - profile.account?.email_address ?? - profile.email ?? - null + forceRefresh, + transport, + pollingMs, ); - } catch { - return null; + if (mode === "blocking") { + const loaded = await load(); + return (await projectNative(loaded)) ?? loaded; } -} - -/** What the usage endpoint says about one live access token. */ -export interface ClaudeSubscriptionQuota { - email: string | null; - status: UsageAccountStatus; - statusDetail: string | null; - windows: UsageQuotaWindow[]; - extraUsage: UsageAccount["extraUsage"]; -} - -/** - * Reads the subscription quota behind a live Claude OAuth access token. The - * OpenCode reader shares this: its Anthropic login is the same OAuth client, - * so the same endpoint answers. - */ -export async function fetchClaudeSubscriptionQuota( - accessToken: string, -): Promise { - try { - const [usageResponse, apiEmail] = await Promise.all([ - fetch(CLAUDE_USAGE_URL, { - headers: { - Authorization: `Bearer ${accessToken}`, - "anthropic-beta": CLAUDE_OAUTH_BETA_HEADER, - }, - signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), - }), - fetchClaudeProfileEmail(accessToken), - ]); - - if (usageResponse.status === 401 || usageResponse.status === 403) { - return { - email: apiEmail, - status: "token_expired", - statusDetail: EXPIRED_TOKEN_DETAIL, - windows: [], - extraUsage: null, - }; - } - if (!usageResponse.ok) { - return { - email: apiEmail, - status: "unavailable", - statusDetail: `Usage endpoint returned ${usageResponse.status}.`, - windows: [], - extraUsage: null, - }; - } - - const usage = (await usageResponse.json()) as ClaudeUsageResponse; - const windows = mapWindows(usage); - const extraUsage = - typeof usage.extra_usage?.used_credits === "number" && - typeof usage.extra_usage?.monthly_limit === "number" - ? { - usedCents: usage.extra_usage.used_credits, - limitCents: usage.extra_usage.monthly_limit, - } - : null; - - if (windows.length === 0) { - return { - email: apiEmail, - status: "unavailable", - statusDetail: - "No quota data returned (org-managed and education plans do not expose limits).", - windows: [], - extraUsage, - }; - } - - return { - email: apiEmail, - status: "ok", - statusDetail: null, - windows, - extraUsage, - }; - } catch (error) { - return { - email: null, - status: "unavailable", - statusDetail: - error instanceof Error ? error.message : "Failed to fetch usage.", + if ( + mode !== "skip" && + (forceRefresh || !accountQuotaCache.fresh(transport, pollingMs)) + ) + void collectionQueue.enqueue(transport, load, forceRefresh).catch(() => {}); + return ( + passive ?? + cached ?? { + email: credential.email ?? null, + status: "unavailable" as const, + statusDetail: "Usage is refreshing.", windows: [], extraUsage: null, - }; - } + fetchedAt: new Date(0), + } + ); } -async function fetchClaudeAccount( +export async function fetchClaudeAccount( credential: ClaudeOauthCredential, + forceRefresh = false, + mode: CollectionMode = "blocking", ): Promise { const base = { agent: "claude" as const, @@ -543,14 +756,95 @@ async function fetchClaudeAccount( }; } - const quota = await fetchClaudeSubscriptionQuota(credential.accessToken); - return { ...base, ...quota, email: quota.email ?? credential.email ?? null }; + const quota = await getCredentialQuota(credential, forceRefresh, mode); + return copyQuotaRetry( + quota, + copyQuotaIdentity(quota, { + ...base, + ...quota, + email: quota.email ?? credential.email ?? null, + }), + ); } export async function fetchClaudeAccounts(): Promise { - const { credentials, signedOutProfiles, apiProfiles } = - await discoverClaudeCredentials(); - const accounts = await Promise.all(credentials.map(fetchClaudeAccount)); + return fetchClaudeSnapshot(await discoverClaudeCredentials()); +} + +export async function captureClaudeQuotaSnapshot( + capture = () => discoverClaudeCredentials(true), + fetchAccount = fetchClaudeAccount, +): Promise> { + let snapshot: ClaudeQuotaInputs; + try { + snapshot = structuredClone( + await createQuotaRequestBudget(QUOTA_CAPTURE_BUDGET_MS).run(() => + capture(), + ), + ); + } catch { + snapshot = { + credentials: [], + signedOutProfiles: [], + apiProfiles: [], + unavailableSlots: [ + { + agent: "claude", + accountKey: "claude:discovery", + sourceLabel: "Claude accounts", + selection: null, + }, + ], + }; + } + const revision = createHash("sha256") + .update( + JSON.stringify([ + { + ...snapshot, + credentials: snapshot.credentials.map( + ({ email: _email, ...credential }) => credential, + ), + }, + snapshot.credentials.map((credential) => + classifyLapsedToken(credential), + ), + ]), + ) + .digest("hex"); + return { + revision, + load: (forceRefresh = false) => + fetchClaudeSnapshot(snapshot, (credential) => + fetchAccount(credential, forceRefresh, "background"), + ), + }; +} + +async function fetchClaudeSnapshot( + { + credentials, + signedOutProfiles, + apiProfiles, + unavailableSlots = [], + }: Awaited>, + fetchAccount = fetchClaudeAccount, +): Promise { + const accounts = [ + ...(await Promise.all( + credentials.map((credential) => + fetchAccount(credential, false, "background").catch(() => + unavailableQuotaAccount({ + agent: "claude", + accountKey: credential.accountKey, + sourceLabel: credential.sourceLabel, + selection: credential.selection, + }), + ), + ), + )), + ...unavailableSlots.map(unavailableQuotaAccount), + ]; for (const profile of apiProfiles) { accounts.push({ agent: "claude", diff --git a/packages/host-service/src/trpc/router/usage/codex-quota-config.node-test.ts b/packages/host-service/src/trpc/router/usage/codex-quota-config.node-test.ts new file mode 100644 index 00000000000..df7d93053cd --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/codex-quota-config.node-test.ts @@ -0,0 +1,184 @@ +// Run with Node/tsx or Electron-as-Node. Bun must be absent: a Bun-only parser +// passed the ordinary test suite but failed inside the packaged host runtime. +import { strict as assert } from "node:assert"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { captureCodexQuotaSnapshot } from "./codex.ts"; +import { discoverCodexHomes } from "./profiles.ts"; + +const quota = { + email: "synthetic@example.test", + plan: "test", + status: "ok" as const, + statusDetail: null, + windows: [ + { id: "primary", label: "Session", usedPercent: 25, resetsAt: null }, + ], + creditsBalance: null, +}; + +test("Node captured Codex auth accepts valid file-store TOML without a Bun global", async () => { + assert.equal(typeof (globalThis as { Bun?: unknown }).Bun, "undefined"); + for (const [index, config] of [ + undefined, + "", + 'model = "synthetic"', + "# file store\ncli_auth_credentials_store = 'file'", + '"cli_auth_credentials_store" = "file"\n[profiles.synthetic]\nmodel="synthetic"', + ].entries()) { + const home = await mkdtemp(join(tmpdir(), "codex-quota-config-node-")); + try { + if (config !== undefined) + await writeFile(join(home, "config.toml"), config); + await writeFile( + join(home, "auth.json"), + JSON.stringify({ + auth_mode: "chatgpt", + tokens: { + access_token: `synthetic-node-valid-${index}`, + account_id: "synthetic-account", + }, + }), + ); + let requests = 0; + const snapshot = await captureCodexQuotaSnapshot( + async () => [ + { + home, + sourceLabel: "synthetic", + credentialKind: "subscription", + loginFingerprint: null, + }, + ], + async (token, accountId) => { + assert.equal(token, `synthetic-node-valid-${index}`); + assert.equal(accountId, "synthetic-account"); + requests++; + return quota; + }, + ); + const [account] = await snapshot.load(true); + assert.equal(account?.status, "ok"); + assert.equal(requests, 1); + } finally { + await rm(home, { recursive: true, force: true }); + } + } +}); + +test("Node discovery distinguishes missing auth with valid TOML from unsupported stores", async () => { + assert.equal(typeof (globalThis as { Bun?: unknown }).Bun, "undefined"); + for (const config of [ + 'cli_auth_credentials_store="file"', + 'cli_auth_credentials_store="keyring"', + 'cli_auth_credentials_store="auto"', + 'cli_auth_credentials_store="ephemeral"', + "cli_auth_credentials_store=42", + "broken = [", + 'cli_auth_credentials_store="file"\ncli_auth_credentials_store="keyring"', + ]) { + const home = await mkdtemp(join(tmpdir(), "codex-quota-discovery-node-")); + try { + await writeFile(join(home, "config.toml"), config); + const [account] = await discoverCodexHomes({ + defaultHome: home, + candidates: [], + includeUnavailable: true, + }); + assert.equal( + account?.quotaUnavailable, + config === 'cli_auth_credentials_store="file"' ? undefined : true, + ); + } finally { + await rm(home, { recursive: true, force: true }); + } + } +}); + +test("Node malformed/unsupported configs refuse captured auth before any quota request", async () => { + for (const [index, config] of [ + 'cli_auth_credentials_store="keyring"', + 'cli_auth_credentials_store="auto"', + 'cli_auth_credentials_store="ephemeral"', + "cli_auth_credentials_store=false", + "broken = [", + 'cli_auth_credentials_store="file"\ncli_auth_credentials_store="auto"', + ].entries()) { + const home = await mkdtemp(join(tmpdir(), "codex-quota-refusal-node-")); + try { + await writeFile(join(home, "config.toml"), config); + await writeFile( + join(home, "auth.json"), + JSON.stringify({ + auth_mode: "chatgpt", + tokens: { + access_token: `synthetic-node-refusal-${index}`, + account_id: "synthetic-account", + }, + }), + ); + let requests = 0; + const snapshot = await captureCodexQuotaSnapshot( + async () => [ + { + home, + sourceLabel: "synthetic", + credentialKind: "subscription", + loginFingerprint: null, + }, + ], + async () => { + requests++; + return quota; + }, + ); + const [account] = await snapshot.load(true); + assert.equal(account?.status, "unavailable"); + assert.equal(requests, 0); + } finally { + await rm(home, { recursive: true, force: true }); + } + } +}); + +test("Node file-store auth validation still refuses malformed or non-ChatGPT identities", async () => { + for (const [index, auth] of [ + "not-json", + JSON.stringify({ auth_mode: "api", tokens: { access_token: "synthetic" } }), + JSON.stringify({ tokens: 42 }), + JSON.stringify({ + tokens: { access_token: "synthetic", account_id: { wrong: true } }, + }), + ].entries()) { + const home = await mkdtemp(join(tmpdir(), "codex-quota-identity-node-")); + try { + await writeFile( + join(home, "config.toml"), + 'cli_auth_credentials_store = "file"', + ); + await writeFile(join(home, "auth.json"), auth); + let requests = 0; + const snapshot = await captureCodexQuotaSnapshot( + async () => [ + { + home, + sourceLabel: `synthetic-${index}`, + credentialKind: "subscription", + loginFingerprint: null, + }, + ], + async () => { + requests++; + return quota; + }, + ); + const [account] = await snapshot.load(true); + assert.equal(account?.status, "unavailable"); + assert.equal(requests, 0); + } finally { + await rm(home, { recursive: true, force: true }); + } + } +}); diff --git a/packages/host-service/src/trpc/router/usage/codex-quota-config.ts b/packages/host-service/src/trpc/router/usage/codex-quota-config.ts new file mode 100644 index 00000000000..ab9aa07dd07 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/codex-quota-config.ts @@ -0,0 +1,23 @@ +import { join } from "node:path"; +import { parse as parseToml } from "smol-toml"; +import { + QuotaCredentialReadError, + readQuotaCredentialFile, +} from "./quota-credentials"; + +export async function assertCodexFileCredentialStore( + home: string, +): Promise { + const config = await readQuotaCredentialFile(join(home, "config.toml")); + if (config === null) return; + try { + const parsed = parseToml(config); + if ( + parsed.cli_auth_credentials_store !== undefined && + parsed.cli_auth_credentials_store !== "file" + ) + throw new QuotaCredentialReadError(); + } catch { + throw new QuotaCredentialReadError(); + } +} diff --git a/packages/host-service/src/trpc/router/usage/codex.ts b/packages/host-service/src/trpc/router/usage/codex.ts index d4bfee2b462..020e01c936b 100644 --- a/packages/host-service/src/trpc/router/usage/codex.ts +++ b/packages/host-service/src/trpc/router/usage/codex.ts @@ -4,10 +4,25 @@ * Read-only: we never refresh the token (see claude.ts for why). */ +import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; +import { assertCodexFileCredentialStore } from "./codex-quota-config"; +import { createCredentialQuotaCache } from "./credential-quota-cache"; import { type CodexHome, discoverCodexHomes } from "./profiles"; +import { copyQuotaRetry, recordQuotaRetry } from "./quota-backoff"; +import type { QuotaSnapshot } from "./quota-cache"; +import { + parseQuotaCredentialJson, + QuotaCredentialReadError, + readQuotaCredentialFile, + unavailableQuotaAccount, +} from "./quota-credentials"; +import { + createQuotaRequestBudget, + QUOTA_REQUEST_BUDGET_MS, +} from "./quota-request"; import type { UsageAccount, UsageAccountStatus, @@ -15,7 +30,6 @@ import type { } from "./types"; const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage"; -const FETCH_TIMEOUT_MS = 10_000; interface CodexAuthFile { tokens?: { @@ -112,15 +126,107 @@ export async function fetchCodexAccounts(): Promise { fetchCodexAccountForHome(home, home.home === defaultHome), ), ); - // Dedupe by account email — one login used from several homes is one - // account; keep the first (default home wins). - const seen = new Set(); - return accounts.flat().filter((account) => { - const key = account.email ?? account.accountKey; - if (seen.has(key)) return false; - seen.add(key); - return true; - }); + // Keep profile identities separate; transport requests are deduplicated below. + return accounts.flat(); +} + +export async function captureCodexQuotaSnapshot( + captureHomes = () => discoverCodexHomes({ includeUnavailable: true }), + fetchQuota = fetchCodexSubscriptionQuota, +): Promise> { + let homes: CodexHome[]; + try { + homes = structuredClone(await captureHomes()); + } catch { + return { + revision: "codex:discovery-unavailable", + load: async () => [ + unavailableQuotaAccount({ + agent: "codex", + accountKey: "codex:discovery", + sourceLabel: "Codex accounts", + selection: null, + }), + ], + }; + } + const inputs = await Promise.all( + homes.map(async (home, index) => { + const source = { + agent: "codex" as const, + accountKey: join(home.home, "auth.json"), + sourceLabel: home.sourceLabel, + selection: index === 0 ? null : home.home, + }; + try { + if (home.quotaUnavailable) + return { state: "unavailable" as const, source }; + return { + state: "available" as const, + home, + isDefaultHome: index === 0, + source, + auth: + home.credentialKind === "api_key" + ? null + : await readCodexQuotaAuth(home.home), + }; + } catch { + return { state: "unavailable" as const, source }; + } + }), + ); + const revision = createHash("sha256") + .update(JSON.stringify(inputs)) + .digest("hex"); + return { + revision, + load: async (forceRefresh = false) => + ( + await Promise.all( + inputs.map(async (input) => { + if (input.state === "unavailable") + return [unavailableQuotaAccount(input.source)]; + try { + return await fetchCodexAccountForHome( + input.home, + input.isDefaultHome, + input.auth, + fetchQuota, + forceRefresh, + ); + } catch { + return [unavailableQuotaAccount(input.source)]; + } + }), + ) + ).flat(), + }; +} + +async function readCodexQuotaAuth(home: string): Promise { + await assertCodexFileCredentialStore(home); + const raw = await readQuotaCredentialFile(join(home, "auth.json")); + if (raw === null) return null; + const parsed = parseQuotaCredentialJson(raw); + if (parsed.auth_mode !== undefined && parsed.auth_mode !== "chatgpt") + throw new QuotaCredentialReadError(); + if (parsed.tokens === undefined || parsed.tokens === null) return null; + if (typeof parsed.tokens !== "object" || Array.isArray(parsed.tokens)) + throw new QuotaCredentialReadError(); + const tokens = parsed.tokens as Record; + if ( + typeof tokens.access_token !== "string" || + !tokens.access_token.trim() || + (tokens.account_id != null && typeof tokens.account_id !== "string") + ) + throw new QuotaCredentialReadError(); + return { + tokens: { + access_token: tokens.access_token, + account_id: (tokens.account_id ?? undefined) as string | undefined, + }, + }; } /** What the ChatGPT usage endpoint says about one access token. */ @@ -143,58 +249,96 @@ export const CODEX_EXPIRED_TOKEN_DETAIL = export async function fetchCodexSubscriptionQuota( accessToken: string, accountId?: string, + budgetMs = QUOTA_REQUEST_BUDGET_MS, ): Promise { const empty = { email: null, plan: null, windows: [], creditsBalance: null }; + const budget = createQuotaRequestBudget(budgetMs); try { - const headers: Record = { - Authorization: `Bearer ${accessToken}`, - }; - if (accountId) headers["chatgpt-account-id"] = accountId; - const response = await fetch(CODEX_USAGE_URL, { - headers, - signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), - }); - - if (response.status === 401 || response.status === 403) { - return { - ...empty, - status: "token_expired", - statusDetail: CODEX_EXPIRED_TOKEN_DETAIL, + return await budget.run(async (signal) => { + const headers: Record = { + Authorization: `Bearer ${accessToken}`, }; - } - if (!response.ok) { + if (accountId) headers["chatgpt-account-id"] = accountId; + const response = await fetch(CODEX_USAGE_URL, { + headers, + cache: "no-store", + redirect: "error", + signal, + }); + + if (response.status === 401 || response.status === 403) { + return { + ...empty, + status: "token_expired", + statusDetail: CODEX_EXPIRED_TOKEN_DETAIL, + }; + } + if (!response.ok) { + return recordQuotaRetry( + { + ...empty, + status: "unavailable", + statusDetail: `Usage endpoint returned ${response.status}.`, + }, + response, + ); + } + + const usage = (await response.json()) as CodexUsageResponse; + const windows = mapWindows(usage); + const balance = Number.parseFloat(usage.credits?.balance ?? ""); return { - ...empty, - status: "unavailable", - statusDetail: `Usage endpoint returned ${response.status}.`, + email: usage.email ?? null, + plan: usage.plan_type ?? null, + status: windows.length > 0 ? "ok" : "unavailable", + statusDetail: + windows.length > 0 ? null : "No quota data returned for this plan.", + windows, + creditsBalance: Number.isFinite(balance) ? balance : null, }; - } - - const usage = (await response.json()) as CodexUsageResponse; - const windows = mapWindows(usage); - const balance = Number.parseFloat(usage.credits?.balance ?? ""); - return { - email: usage.email ?? null, - plan: usage.plan_type ?? null, - status: windows.length > 0 ? "ok" : "unavailable", - statusDetail: - windows.length > 0 ? null : "No quota data returned for this plan.", - windows, - creditsBalance: Number.isFinite(balance) ? balance : null, - }; - } catch (error) { + }); + } catch { return { ...empty, status: "unavailable", - statusDetail: - error instanceof Error ? error.message : "Failed to fetch usage.", + statusDetail: "Usage request failed or timed out. Try again shortly.", }; } } +const credentialQuotaCache = createCredentialQuotaCache< + CodexSubscriptionQuota & { fetchedAt: Date } +>(); +export function getCodexCredentialQuota( + accessToken: string, + accountId: string | undefined, + sourceKey: string, + forceRefresh = false, + fetchQuota = fetchCodexSubscriptionQuota, +) { + const key = createHash("sha256") + .update(JSON.stringify([sourceKey, accessToken, accountId ?? null])) + .digest("hex"); + const transportKey = createHash("sha256") + .update(JSON.stringify(["codex", accessToken, accountId ?? null])) + .digest("hex"); + return credentialQuotaCache.get( + key, + async () => { + const quota = await fetchQuota(accessToken, accountId); + return copyQuotaRetry(quota, { ...quota, fetchedAt: new Date() }); + }, + forceRefresh, + transportKey, + ); +} + async function fetchCodexAccountForHome( home: CodexHome, isDefaultHome: boolean, + capturedAuth?: CodexAuthFile | null, + fetchQuota = fetchCodexSubscriptionQuota, + forceRefresh = false, ): Promise { const codexHome = home.home; const authPath = join(codexHome, "auth.json"); @@ -229,16 +373,22 @@ async function fetchCodexAccountForHome( let auth: CodexAuthFile; try { - auth = JSON.parse(await readFile(authPath, "utf-8")); + auth = + capturedAuth === undefined + ? JSON.parse(await readFile(authPath, "utf-8")) + : (capturedAuth ?? {}); } catch { return []; } const accessToken = auth.tokens?.access_token; if (!accessToken) return []; - const quota = await fetchCodexSubscriptionQuota( + const quota = await getCodexCredentialQuota( accessToken, auth.tokens?.account_id, + codexHome, + forceRefresh, + fetchQuota, ); - return [{ ...base, ...quota }]; + return [copyQuotaRetry(quota, { ...base, ...quota })]; } diff --git a/packages/host-service/src/trpc/router/usage/credential-quota-cache.test.ts b/packages/host-service/src/trpc/router/usage/credential-quota-cache.test.ts new file mode 100644 index 00000000000..2289ac3e3e4 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/credential-quota-cache.test.ts @@ -0,0 +1,311 @@ +import { expect, test } from "bun:test"; +import { createCredentialQuotaCache } from "./credential-quota-cache"; +import { recordQuotaRetry } from "./quota-backoff"; + +test("active cadence refreshes earlier, idle cadence reuses readings, and aliases keep server cooldowns", async () => { + let now = 0, + loads = 0; + const cache = createCredentialQuotaCache<{ observedAt: number }>( + 600_000, + () => now, + ); + const load = async () => ({ observedAt: ++loads }); + const first = await cache.get("idle", load, false, "token", 600_000); + now = 120_000; + expect(await cache.get("idle", load, false, "token", 600_000)).toBe(first); + expect(cache.fresh("token", 120_000)).toBe(false); + expect(await cache.get("active", load, false, "token", 120_000)).toEqual({ + observedAt: 2, + }); + const limited = recordQuotaRetry( + { observedAt: 3 }, + new Response("", { status: 429, headers: { "retry-after": "600" } }), + ); + await cache.get("active", async () => limited, true, "token", 120_000); + now += 599_999; + expect(await cache.get("alias", load, true, "token", 1)).toBe(limited); + expect(loads).toBe(2); + expect(cache.fresh("token", 1)).toBe(true); + now++; + await cache.get("alias", load, false, "token", 120_000); + expect(loads).toBe(3); +}); + +test("profile aliases cannot bypass one transport credential's absolute Retry-After", async () => { + let now = 0, + loads = 0; + const cache = createCredentialQuotaCache<{ + status: string; + windows: number[]; + }>(300_000, () => now); + const limited = recordQuotaRetry( + { status: "unavailable", windows: [] }, + new Response("", { status: 429, headers: { "Retry-After": "600" } }), + ); + const load = async () => { + loads++; + return limited; + }; + await cache.get("profileA-token", load, true, "token"); + now = 30_000; + expect(await cache.get("aliasB-token", load, true, "token")).toBe(limited); + expect(loads).toBe(1); + const unrelated = await cache.get( + "profileC-other", + async () => ({ status: "ok", windows: [25] }), + true, + "other-token", + ); + expect(unrelated.status).toBe("ok"); + now = 600_000; + await cache.get("aliasB-token", load, true, "token"); + expect(loads).toBe(2); +}); +test("a failed loader is released without poisoning the cached credential result", async () => { + const cache = createCredentialQuotaCache<{ status: string }>(); + let loads = 0; + const load = async () => { + loads++; + throw new Error("private-error"); + }; + await expect(cache.get("test", load)).rejects.toThrow("private-error"); + expect(await cache.get("test", async () => ({ status: "ok" }))).toEqual({ + status: "ok", + }); + expect(loads).toBe(1); +}); + +test("concurrent profile aliases share the actual transport request and retain its observed timestamp", async () => { + let loads = 0; + let finish!: (value: { status: string; fetchedAt: Date }) => void; + const response = new Promise<{ status: string; fetchedAt: Date }>( + (resolve) => { + finish = resolve; + }, + ); + const cache = createCredentialQuotaCache<{ + status: string; + fetchedAt: Date; + }>(); + const load = () => { + loads++; + return response; + }; + const a = cache.get("profile-a", load, false, "same-token"); + const b = cache.get("profile-b", load, false, "same-token"); + const value = { status: "ok", fetchedAt: new Date(1234) }; + finish(value); + expect(await a).toBe(value); + expect(await b).toBe(value); + expect(await cache.get("profile-b", load, false, "same-token")).toBe(value); + expect(loads).toBe(1); +}); + +test("repeated rate limits back off once per actual request and never delay healthy siblings", async () => { + let now = 0; + let limitedLoads = 0; + const cache = createCredentialQuotaCache<{ status: string }>( + 300_000, + () => now, + () => 0, + ); + const load = async () => { + limitedLoads++; + return recordQuotaRetry( + { status: "unavailable" }, + new Response("", { status: 429 }), + ); + }; + await Promise.all( + ["a", "b", "c"].map((key) => cache.get(key, load, true, "limited")), + ); + expect(limitedLoads).toBe(1); + now = 299_999; + await cache.get("new-alias", load, true, "limited"); + expect(limitedLoads).toBe(1); + now = 300_000; + await cache.get("a", load, true, "limited"); + expect(limitedLoads).toBe(2); + now = 899_999; + await cache.get("b", load, true, "limited"); + expect(limitedLoads).toBe(2); + expect( + await cache.get("healthy", async () => ({ status: "ok" }), true), + ).toEqual({ status: "ok" }); + now = 900_000; + await cache.get("c", load, true, "limited"); + expect(limitedLoads).toBe(3); +}); + +test("replaying one response through late aliases does not slide its absolute server deadline", async () => { + let now = 0; + let loads = 0; + const cache = createCredentialQuotaCache( + 0, + () => now, + () => 0, + ); + const limited = recordQuotaRetry( + {}, + new Response("", { status: 429, headers: { "retry-after": "600" } }), + ); + const load = async () => { + loads++; + return limited; + }; + await cache.get("a", load, true, "token"); + now = 500_000; + await cache.get("b", load, true, "token"); + expect(loads).toBe(1); + now = 600_000; + await cache.get("b", load, true, "token"); + expect(loads).toBe(2); + now = 600_001; + await cache.get("c", load, true, "token"); + expect(loads).toBe(3); +}); + +test("exponential jitter is bounded and a successful result resets the failure sequence", async () => { + let now = 0; + let loads = 0; + let healthy = false; + const cache = createCredentialQuotaCache<{ status: string }>( + 0, + () => now, + () => 1, + ); + const load = async () => { + loads++; + return healthy + ? { status: "ok" } + : recordQuotaRetry( + { status: "unavailable" }, + new Response("", { status: 503 }), + ); + }; + await cache.get("a", load, true); + now = 30_000; + await cache.get("a", load, true); + now = 101_999; + await cache.get("a", load, true); + expect(loads).toBe(2); + now = 102_000; + healthy = true; + await cache.get("a", load, true); + expect(loads).toBe(3); + healthy = false; + await cache.get("a", load, true); + now += 29_999; + await cache.get("a", load, true); + expect(loads).toBe(4); + now += 1; + await cache.get("a", load, true); + expect(loads).toBe(5); +}); + +test("repeated failures cap automatic retry delay while retaining longer provider instructions", async () => { + let now = 0; + let loads = 0; + const cache = createCredentialQuotaCache( + 0, + () => now, + () => 1, + ); + const load = async () => { + loads++; + return recordQuotaRetry({}, new Response("", { status: 429 })); + }; + for (let attempt = 0; attempt < 9; attempt++) { + await cache.get("limited", load, true); + now += 30 * 60_000; + } + expect(loads).toBe(9); + await cache.get("limited", load, true); + expect(loads).toBe(10); + const longPause = async () => { + loads++; + return recordQuotaRetry( + {}, + new Response("", { status: 503, headers: { "retry-after": "7200" } }), + ); + }; + await cache.get("long", longPause, true); + now += 119 * 60_000; + await cache.get("long", longPause, true); + expect(loads).toBe(11); + now += 60_000; + await cache.get("long", longPause, true); + expect(loads).toBe(12); +}); + +test("renewal can inspect the same transport pause without extending or bypassing it", async () => { + let now = 0; + let loads = 0; + const cache = createCredentialQuotaCache( + 0, + () => now, + () => 0, + ); + const load = async () => { + loads++; + return recordQuotaRetry( + {}, + new Response("", { status: 429, headers: { "retry-after": "600" } }), + ); + }; + expect(cache.retryAt("token")).toBe(0); + await cache.get("profile", load, true, "token"); + expect(cache.retryAt("token")).toBe(600_000); + now = 300_000; + expect(cache.retryAt("token")).toBe(600_000); + await cache.get("alias", load, true, "token"); + expect(loads).toBe(1); + expect(cache.retryAt("token")).toBe(600_000); + now = 600_000; + await cache.get("profile", async () => ({}), true, "token"); + expect(cache.retryAt("token")).toBe(0); +}); + +test("a concurrent alias follower cannot extend the original absolute Retry-After deadline", async () => { + let now = 0; + let release!: () => void; + const gate = new Promise((done) => { + release = done; + }); + let requests = 0; + const cache = createCredentialQuotaCache(300_000, () => now); + const load = async () => { + requests++; + await gate; + return recordQuotaRetry({}, new Response("", { status: 429 })); + }; + const owner = cache.get("owner", load, true, "transport"); + void owner.then(() => { + now = 100_000; + }); + const follower = cache.get("follower", load, true, "transport"); + release(); + await Promise.all([owner, follower]); + now = 300_001; + await cache.get("follower", load, true, "transport"); + expect(requests).toBe(2); +}); + +test("invalidating exact transport authority fences an old result without erasing a replacement", async () => { + const cache = createCredentialQuotaCache<{ status: string }>(); + const old = Promise.withResolvers<{ status: string }>(); + const first = cache.get("old", () => old.promise, false, "token"); + await Promise.resolve(); + cache.invalidate("token"); + expect( + await cache.get( + "new", + async () => ({ status: "new-owner" }), + false, + "token", + ), + ).toEqual({ status: "new-owner" }); + old.resolve({ status: "stale-owner" }); + await expect(first).rejects.toThrow("changed"); + expect(cache.peek("token")?.value).toEqual({ status: "new-owner" }); +}); diff --git a/packages/host-service/src/trpc/router/usage/credential-quota-cache.ts b/packages/host-service/src/trpc/router/usage/credential-quota-cache.ts new file mode 100644 index 00000000000..851ce6eb473 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/credential-quota-cache.ts @@ -0,0 +1,191 @@ +import { readQuotaRetryHint } from "./quota-backoff"; + +const MAX_ENTRIES = 1024; +const MAX_EXPONENTIAL_DELAY_MS = 30 * 60_000; + +// This cache follows one exact token/profile/account header. Inventory changes +// in a sibling account cannot clear its absolute server-requested pause. +export function createCredentialQuotaCache( + ttlMs: number | ((value: T) => number) = 5 * 60_000, + now = () => Date.now(), + random = Math.random, +) { + const freshFor = (value: T, pollingMs?: number) => + readQuotaRetryHint(value) + ? 0 + : pollingMs !== undefined && Number.isFinite(pollingMs) && pollingMs > 0 + ? pollingMs + : typeof ttlMs === "function" + ? ttlMs(value) + : ttlMs; + const entries = new Map< + string, + { value?: T; fetchedAt: number; retryAt: number; pending?: Promise } + >(); + const transports = new Map< + string, + { + value: T; + fetchedAt: number; + retryAt: number; + failures: number; + hint?: object; + } + >(); + const transportPending = new Map>(); + return { + invalidate(transportKey: string) { + transports.delete(transportKey); + transportPending.delete(transportKey); + // Entry aliases contain no authority independent of their transport. + entries.clear(); + }, + peek(transportKey: string) { + return transports.get(transportKey); + }, + fresh(transportKey: string, pollingMs?: number) { + const value = transports.get(transportKey); + return ( + !!value && + (now() < value.retryAt || + now() - value.fetchedAt < freshFor(value.value, pollingMs)) + ); + }, + retryAt(transportKey: string): number { + return transports.get(transportKey)?.retryAt ?? 0; + }, + get( + key: string, + load: () => Promise, + forceRefresh = false, + transportKey = key, + pollingMs?: number, + ): Promise { + const transport = transports.get(transportKey); + if ( + transport && + (now() < transport.retryAt || + (!forceRefresh && + now() - transport.fetchedAt < freshFor(transport.value, pollingMs))) + ) + return Promise.resolve(transport.value); + let entry = entries.get(key); + if (entry?.pending) return entry.pending; + if ( + entry?.value && + (now() < entry.retryAt || + (!forceRefresh && + now() - entry.fetchedAt < freshFor(entry.value, pollingMs))) + ) + return Promise.resolve(entry.value); + if (!entry) { + if (entries.size >= MAX_ENTRIES) { + const disposable = [...entries].find( + ([, candidate]) => !candidate.pending && candidate.retryAt <= now(), + ); + if (!disposable) + return Promise.reject( + new Error("Usage cache is busy. Try again shortly."), + ); + entries.delete(disposable[0]); + } + entry = { fetchedAt: 0, retryAt: 0 }; + entries.set(key, entry); + } + const current = entry; + let credentialRequest = transportPending.get(transportKey); + if (!credentialRequest) { + if (!transports.has(transportKey)) { + const pendingNew = [...transportPending.keys()].filter( + (key) => !transports.has(key), + ).length; + if (transports.size + pendingNew >= MAX_ENTRIES) { + const disposable = [...transports].find( + ([key, candidate]) => + candidate.retryAt <= now() && !transportPending.has(key), + ); + if (!disposable) + return Promise.reject( + new Error("Usage cache is busy. Try again shortly."), + ); + transports.delete(disposable[0]); + } + } + const shared = Promise.resolve() + .then(load) + .then((value) => { + if (transportPending.get(transportKey) !== shared) + throw new Error( + "Usage credential cache changed during the request.", + ); + const previous = transports.get(transportKey); + const hint = readQuotaRetryHint(value); + const failures = hint + ? previous?.hint === hint + ? previous.failures + : Math.min((previous?.failures ?? 0) + 1, 8) + : 0; + let retryAt = 0; + if (hint) { + if (previous?.hint === hint) retryAt = previous.retryAt; + else { + const base = hint.kind === "rate_limit" ? 5 * 60_000 : 30_000; + const exponential = Math.min( + MAX_EXPONENTIAL_DELAY_MS, + base * 2 ** (failures - 1), + ); + const jitter = + failures > 1 + ? Math.floor( + exponential * 0.2 * Math.max(0, Math.min(1, random())), + ) + : 0; + retryAt = + hint.retryAt ?? + now() + + Math.max( + hint.delayMs, + Math.min(MAX_EXPONENTIAL_DELAY_MS, exponential + jitter), + ); + } + } + transports.set(transportKey, { + value, + fetchedAt: now(), + retryAt, + failures, + hint, + }); + return value; + }) + .catch((error: unknown) => { + if (transportPending.get(transportKey) === shared) + transports.delete(transportKey); + throw error; + }) + .finally(() => { + if (transportPending.get(transportKey) === shared) + transportPending.delete(transportKey); + }); + credentialRequest = shared; + transportPending.set(transportKey, shared); + } + const request = credentialRequest + .then((value) => { + current.value = value; + current.fetchedAt = transports.get(transportKey)?.fetchedAt ?? now(); + current.retryAt = transports.get(transportKey)?.retryAt ?? 0; + return value; + }) + .catch((error: unknown) => { + current.value = undefined; + throw error; + }) + .finally(() => { + if (current.pending === request) current.pending = undefined; + }); + current.pending = request; + return request; + }, + }; +} diff --git a/packages/host-service/src/trpc/router/usage/native-claude-binding.test.ts b/packages/host-service/src/trpc/router/usage/native-claude-binding.test.ts new file mode 100644 index 00000000000..457b30c4824 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-binding.test.ts @@ -0,0 +1,244 @@ +import { expect, test } from "bun:test"; +import { + ingestNativeClaudeBinding, + type NativeClaudeAccount, + type NativeClaudeUsageDependencies, +} from "./native-claude-binding"; +import { createNativeClaudeUsageStore } from "./native-claude-usage"; + +function fixture() { + let now = 1_800_000_000_000; + let generation = "a".repeat(64); + let scope: string | null = null; + let valid = true; + const store = createNativeClaudeUsageStore({ + persist: false, + now: () => now, + }); + const account: NativeClaudeAccount = { + agent: "claude", + credentialKind: "subscription", + pinned: true, + selection: "/fixture/profile", + directory: "/fixture/profile", + identity: "e".repeat(64), + }; + const launch = { launchId: "owned-launch", sessionId: "owned-session" }; + const deps: NativeClaudeUsageDependencies = { + store, + validateAccount: async () => valid, + captureGeneration: async () => generation, + resolveScope: async (_selection, _directory, _identity, expected) => + expected === generation ? scope : null, + }; + store.captureLaunch({ ...launch, generation }); + const frame = (counter: number, used = 10) => ({ + cost: { total_api_duration_ms: counter }, + rate_limits: { + five_hour: { + used_percentage: used, + resets_at: (1_800_000_000_000 + 300_000) / 1000, + }, + }, + }); + const ingest = (counter: number, used = 10) => + ingestNativeClaudeBinding( + account, + launch, + { + source: "claude_statusline", + payload: frame(counter, used), + receivedAt: now, + }, + () => true, + deps, + ); + return { + store, + account, + launch, + deps, + frame, + ingest, + advance: (ms = 1000) => { + now += ms; + }, + time: () => now, + warm: () => { + scope = "b".repeat(64); + }, + rotate: () => { + generation = "c".repeat(64); + }, + invalidate: () => { + valid = false; + }, + scope: "b".repeat(64), + }; +} +test("cold launch warms on a later natural replay without promoting measurement age", async () => { + const f = fixture(); + expect(await f.ingest(0)).toBe(false); + f.advance(); + expect(await f.ingest(10, 20)).toBe(false); + const measuredAt = f.time(); + expect(f.store.snapshot(f.scope)).toEqual([]); + f.advance(); + f.warm(); + expect(await f.ingest(10, 20)).toBe(true); + expect(f.store.snapshot(f.scope)).toEqual([ + { + id: "five_hour", + usedPercent: 20, + resetsAt: 1_800_000_300_000, + observedAt: measuredAt, + source: "claude_statusline", + }, + ]); + f.advance(); + await f.ingest(10, 20); + expect(f.store.snapshot(f.scope)[0]?.observedAt).toBe(measuredAt); +}); +test("a first restored frame remains a baseline even when proof warms", async () => { + const f = fixture(); + await f.ingest(100, 45); + f.advance(); + f.warm(); + await f.ingest(100, 45); + expect(f.store.snapshot(f.scope)).toEqual([]); + f.advance(); + await f.ingest(101, 45); + expect(f.store.snapshot(f.scope)[0]?.observedAt).toBe(f.time()); +}); +test("rotation, invalid registration, unpinned accounts and ownership changes cannot acquire authority", async () => { + const f = fixture(); + await f.ingest(0); + f.advance(); + await f.ingest(1); + f.warm(); + f.rotate(); + expect(await f.ingest(2)).toBe(false); + expect(f.store.snapshot(f.scope)).toEqual([]); + const other = fixture(); + other.warm(); + other.invalidate(); + expect(await other.ingest(0)).toBe(false); + expect( + await ingestNativeClaudeBinding( + { ...other.account, pinned: undefined }, + other.launch, + { + source: "claude_statusline", + payload: other.frame(1), + receivedAt: other.time(), + }, + () => true, + other.deps, + ), + ).toBe(false); + expect( + await ingestNativeClaudeBinding( + other.account, + other.launch, + { + source: "claude_statusline", + payload: other.frame(1), + receivedAt: other.time(), + }, + () => false, + other.deps, + ), + ).toBe(false); +}); +test("promotion fences the original credential generation and cannot switch organizations twice", async () => { + const f = fixture(); + expect( + f.store.promoteLaunch({ + ...f.launch, + generation: "9".repeat(64), + scope: f.scope, + }), + ).toBe(false); + await f.ingest(0); + f.warm(); + await f.ingest(1); + expect( + f.store.promoteLaunch({ + ...f.launch, + generation: "a".repeat(64), + scope: "d".repeat(64), + }), + ).toBe(false); +}); + +test("asynchronous principal proof keeps the pre-validation receipt", async () => { + const f = fixture(); + f.warm(); + await f.ingest(0); + f.advance(); + const receivedAt = f.time(); + let release!: () => void; + let entered!: () => void; + const waiting = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const resolveScope = f.deps.resolveScope; + f.deps.resolveScope = async (...args) => { + entered(); + await gate; + return resolveScope(...args); + }; + const delayed = f.ingest(1, 30); + await waiting; + f.advance(45_000); + release(); + expect(await delayed).toBe(true); + expect(f.store.snapshot(f.scope)[0]?.observedAt).toBe(receivedAt); +}); + +test("proof that completes after receipt expiry cannot promote a queued reading", async () => { + const f = fixture(); + await f.ingest(0); + f.advance(); + await f.ingest(1, 30); + let release!: () => void; + let entered!: () => void; + const waiting = new Promise((resolve) => { + entered = resolve; + }); + const gate = new Promise((resolve) => { + release = resolve; + }); + const resolveScope = f.deps.resolveScope; + f.deps.resolveScope = async (...args) => { + entered(); + await gate; + return resolveScope(...args); + }; + f.warm(); + const replay = f.ingest(1, 30); + await waiting; + f.advance(6 * 60_000 + 1); + release(); + expect(await replay).toBe(false); + expect(f.store.snapshot(f.scope)).toEqual([]); +}); + +test("healthy captured frames resolve proof without redundant credential capture", async () => { + const f = fixture(); + f.warm(); + let captures = 0; + const capture = f.deps.captureGeneration; + f.deps.captureGeneration = async (...args) => { + captures++; + return capture(...args); + }; + await f.ingest(0); + f.advance(); + expect(await f.ingest(1, 20)).toBe(true); + expect(captures).toBe(0); + expect(f.store.snapshot(f.scope)[0]?.usedPercent).toBe(20); +}); diff --git a/packages/host-service/src/trpc/router/usage/native-claude-binding.ts b/packages/host-service/src/trpc/router/usage/native-claude-binding.ts new file mode 100644 index 00000000000..8be5d202789 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-binding.ts @@ -0,0 +1,100 @@ +import type { createNativeClaudeUsageStore } from "./native-claude-usage"; + +export interface NativeClaudeAccount { + agent: "claude" | "codex"; + credentialKind: "subscription" | "api_key"; + selection: string | null; + identity: string; + directory?: string; + pinned?: true; + conflict?: true; +} +export interface NativeClaudeLaunch { + launchId: string; + sessionId: string; +} +export interface NativeClaudeUsageDependencies { + captureGeneration( + selection: string | null, + directory: string, + identity: string, + ): Promise; + resolveScope( + selection: string | null, + directory: string, + identity: string, + generation: string, + ): Promise; + validateAccount(account: NativeClaudeAccount): Promise; + store: ReturnType; +} +export function isNativeClaudeAccount( + account: NativeClaudeAccount | undefined, +): account is NativeClaudeAccount & { directory: string } { + return ( + !!account && + account.agent === "claude" && + account.credentialKind === "subscription" && + account.pinned === true && + !account.conflict && + !!account.directory + ); +} +export async function ingestNativeClaudeBinding( + account: NativeClaudeAccount, + launch: NativeClaudeLaunch, + input: { + source: "claude_statusline" | "claude_sdk"; + payload: unknown; + receivedAt: number; + responseCounter?: number; + }, + current: () => boolean, + deps: NativeClaudeUsageDependencies, +): Promise { + if ( + !deps.store.isCurrentReceipt(input.receivedAt) || + !isNativeClaudeAccount(account) || + !current() || + !(await deps.validateAccount(account)) + ) + return false; + const generation = deps.store.capturedGeneration(launch); + if (!generation || !current()) return false; + let bound = deps.store.activeScope({ ...launch, generation }); + if (!bound) return false; + const scope = await deps.resolveScope( + account.selection, + account.directory, + account.identity, + generation, + ); + if (!current() || !deps.store.isCurrentReceipt(input.receivedAt)) + return false; + if (scope) { + if (!deps.store.promoteLaunch({ ...launch, generation, scope })) + return false; + bound = deps.store.activeScope({ ...launch, generation }); + if (!bound || bound.pending || bound.scope !== scope) return false; + } else if (!bound.pending) { + // Previously verified authority has expired or was invalidated; retain its original age. + return false; + } else if ( + (await deps.captureGeneration( + account.selection, + account.directory, + account.identity, + )) !== generation || + !current() || + !deps.store.isCurrentReceipt(input.receivedAt) + ) { + return false; + } + deps.store.ingest({ + ...launch, + ...input, + scope: bound.scope, + quarantined: bound.pending, + }); + return !bound.pending; +} diff --git a/packages/host-service/src/trpc/router/usage/native-claude-overlay.test.ts b/packages/host-service/src/trpc/router/usage/native-claude-overlay.test.ts new file mode 100644 index 00000000000..ef6f6aece2e --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-overlay.test.ts @@ -0,0 +1,287 @@ +import { expect, test } from "bun:test"; +import { + canDeferClaudeHttpQuota, + createNativeClaudeQuotaOverlay, + mergeNativeClaudeQuota, +} from "./native-claude-overlay"; +import type { NativeClaudeUsageWindow } from "./native-claude-usage"; + +const now = 1_800_000_000_000; +const base = () => ({ + status: "unavailable" as const, + statusDetail: "Usage endpoint returned 429.", + email: "fixture@example.test", + windows: [], + fetchedAt: new Date(now - 20 * 60_000), + extraUsage: { usedCents: 20, limitCents: 100 }, + retryAt: new Date(now + 60_000), + prepaidBalance: { + amount: 15, + currency: "USD", + checkedAt: new Date(now - 20 * 60_000), + }, + lastKnownUsage: { fetchedAt: new Date(now - 30 * 60_000), windows: [] }, +}); +const reading = ( + id: "five_hour" | "seven_day", + change: Partial = {}, +): NativeClaudeUsageWindow => ({ + id, + usedPercent: 25, + resetsAt: now + 60_000, + observedAt: now - 1000, + source: "claude_statusline", + ...change, +}); +test("native windows rescue a transient reading without refreshing financial or HTTP dates", () => { + const original = base(); + const merged = mergeNativeClaudeQuota( + original, + [reading("five_hour"), reading("seven_day")], + now, + ); + expect(merged?.status).toBe("ok"); + expect(merged?.fetchedAt).toBe(original.fetchedAt); + expect(merged?.prepaidBalance).toBe(original.prepaidBalance); + expect(merged?.extraUsage).toBe(original.extraUsage); + expect(merged?.retryAt).toBe(original.retryAt); + expect(merged?.lastKnownUsage).toBe(original.lastKnownUsage); + expect(merged?.windows.map((window) => window.source)).toEqual([ + "claude_statusline", + "claude_statusline", + ]); + expect(original.windows).toEqual([]); + expect(merged && canDeferClaudeHttpQuota(original, merged, now)).toBe(true); +}); +test("partial, stale, future, expired and malformed native observations never imply full coverage", () => { + const original = base(); + const partial = mergeNativeClaudeQuota(original, [reading("five_hour")], now); + expect(partial?.windows.map((window) => window.id)).toEqual(["five_hour"]); + expect(partial && canDeferClaudeHttpQuota(original, partial, now)).toBe( + false, + ); + for (const change of [ + { observedAt: now + 1 }, + { observedAt: now - 6 * 60_000 - 1 }, + { resetsAt: now }, + { usedPercent: Number.NaN }, + { usedPercent: 101 }, + ]) + expect( + mergeNativeClaudeQuota(original, [reading("five_hour", change)], now), + ).toBeNull(); + for (const status of ["signed_out", "token_expired", "token_stale"] as const) + expect( + mergeNativeClaudeQuota( + { ...original, status }, + [reading("five_hour")], + now, + ), + ).toBeNull(); +}); +test("provider/model windows and newer reset epochs keep their own original observations", () => { + const scoped = { + id: "seven_day_sonnet", + label: "Weekly · Sonnet", + usedPercent: 40, + resetsAt: new Date(now + 500_000), + observedAt: new Date(now - 20 * 60_000), + source: "provider" as const, + }; + const current = { + id: "five_hour", + label: "Session (5h)", + usedPercent: 55, + resetsAt: new Date(now + 120_000), + observedAt: new Date(now), + source: "provider" as const, + }; + const original = { + ...base(), + status: "ok" as const, + windows: [current, scoped], + }; + const merged = mergeNativeClaudeQuota( + original, + [reading("five_hour"), reading("seven_day")], + now, + ); + expect(merged?.windows.find((window) => window.id === "five_hour")).toBe( + current, + ); + expect( + merged?.windows.find((window) => window.id === "seven_day_sonnet"), + ).toBe(scoped); + expect(merged && canDeferClaudeHttpQuota(original, merged, now)).toBe(false); +}); +test("native quota cannot extend financial reconciliation or wallet age", () => { + const original = base(); + const merged = mergeNativeClaudeQuota( + original, + [reading("five_hour"), reading("seven_day")], + now, + ); + if (!merged) throw new Error("missing native sample"); + expect( + canDeferClaudeHttpQuota( + { ...original, fetchedAt: new Date(now - 30 * 60_000) }, + merged, + now, + ), + ).toBe(false); + expect( + canDeferClaudeHttpQuota( + { + ...original, + prepaidBalance: { + ...original.prepaidBalance, + checkedAt: new Date(now - 30 * 60_000), + }, + }, + merged, + now, + ), + ).toBe(false); + expect( + canDeferClaudeHttpQuota( + { ...original, fetchedAt: new Date(now + 1) }, + merged, + now, + ), + ).toBe(false); +}); +test("cache-only scope lookup fences the captured token, cache object and registration generation", async () => { + const original = base(); + let current = { + accessToken: "fixture-token", + canonicalProfile: "/fixture/profile", + registrationHash: "e".repeat(64), + }; + let cached = original; + let enabled = true; + let proof = true; + let captured: unknown[] = []; + const overlay = createNativeClaudeQuotaOverlay({ + enabled: () => enabled, + readCurrent: async () => current, + generation: (value) => + `generation:${value.accessToken}:${value.registrationHash}`, + resolveScope: async (...args) => { + captured = args; + return proof ? "verified-scope" : null; + }, + isCurrent: (_token, value) => cached === value, + snapshot: () => [reading("five_hour")], + now: () => now, + }); + const credential = { + accessToken: "fixture-token", + selection: "/fixture/profile", + }; + expect((await overlay(credential, original))?.windows).toHaveLength(1); + expect(captured).toEqual([ + "/fixture/profile", + "/fixture/profile", + "e".repeat(64), + `generation:fixture-token:${"e".repeat(64)}`, + ]); + proof = false; + expect(await overlay(credential, original)).toBeNull(); + proof = true; + cached = { ...original }; + expect(await overlay(credential, original)).toBeNull(); + cached = original; + current = { ...current, accessToken: "rotated" }; + expect(await overlay(credential, original)).toBeNull(); + enabled = false; + expect(await overlay(credential, original)).toBeNull(); +}); + +test("native display and HTTP deferral expire together after six minutes", () => { + const original = base(); + const recent = [ + reading("five_hour", { observedAt: now - 6 * 60_000 }), + reading("seven_day", { observedAt: now - 6 * 60_000 }), + ]; + const overlay = mergeNativeClaudeQuota(original, recent, now); + if (!overlay) throw new Error("missing boundary sample"); + expect(canDeferClaudeHttpQuota(original, overlay, now)).toBe(true); + expect(mergeNativeClaudeQuota(original, recent, now + 1)).toBeNull(); + expect(canDeferClaudeHttpQuota(original, overlay, now + 1)).toBe(false); +}); + +const resetPrecisionCases = [ + ["same second with 213ms HTTP precision", 213, 0, 30, true, 213], + ["same second with higher usage", 213, 0, 31, true, 213], + ["same second with lower usage", 0, 213, 29, false, 0], + ["earlier second with higher usage", 0, -1000, 99, false, 0], + ["later second with lower usage", 0, 1000, 1, true, 1000], + ["one millisecond into a later second", 999, 1000, 1, true, 1000], + ["one millisecond into the previous second", 1000, 999, 99, false, 1000], +] as const; + +test.each( + resetPrecisionCases, +)("native overlay compares reset seconds: %s", (_name, previousOffset, nextOffset, usedPercent, accepted, keptOffset) => { + const reset = now + 120_000; + const original = { + ...base(), + status: "ok" as const, + windows: [ + { + id: "five_hour", + label: "Session (5h)", + usedPercent: 30, + resetsAt: new Date(reset + previousOffset), + observedAt: new Date(now - 2000), + source: "provider" as const, + }, + ], + }; + const result = mergeNativeClaudeQuota( + original, + [reading("five_hour", { usedPercent, resetsAt: reset + nextOffset })], + now, + ); + if (!accepted) { + expect(result).toBeNull(); + } else { + expect(result?.windows[0]?.resetsAt?.getTime()).toBe(reset + keptOffset); + expect(result?.windows[0]?.usedPercent).toBe(usedPercent); + expect(result?.windows[0]?.observedAt?.getTime()).toBe(now - 1000); + expect(result?.windows[0]?.source).toBe("claude_statusline"); + expect(result?.fetchedAt).toBe(original.fetchedAt); + } + expect(original.windows[0]?.resetsAt.getTime()).toBe(reset + previousOffset); +}); +test("reset precision does not bypass an older or equal native observation", () => { + const reset = now + 120_000; + const original = { + ...base(), + status: "ok" as const, + windows: [ + { + id: "five_hour", + label: "Session (5h)", + usedPercent: 30, + resetsAt: new Date(reset + 213), + observedAt: new Date(now - 1000), + source: "provider" as const, + }, + ], + }; + for (const observedAt of [now - 1001, now - 1000]) + expect( + mergeNativeClaudeQuota( + original, + [ + reading("five_hour", { + usedPercent: 31, + resetsAt: reset, + observedAt, + }), + ], + now, + ), + ).toBeNull(); +}); diff --git a/packages/host-service/src/trpc/router/usage/native-claude-overlay.ts b/packages/host-service/src/trpc/router/usage/native-claude-overlay.ts new file mode 100644 index 00000000000..1a9b4648f17 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-overlay.ts @@ -0,0 +1,150 @@ +import type { ClaudeSubscriptionQuota } from "./claude-subscription"; +import type { NativeClaudeCredential } from "./native-claude-scope"; +import { + NATIVE_CLAUDE_FRESH_MS, + type NativeClaudeUsageWindow, +} from "./native-claude-usage"; + +export { NATIVE_CLAUDE_FRESH_MS } from "./native-claude-usage"; + +import type { UsageQuotaWindow } from "./types"; + +const HTTP_RECONCILE_MS = 30 * 60_000; +type Quota = ClaudeSubscriptionQuota & { fetchedAt: Date }; +const date = (value: unknown) => + value instanceof Date ? value.getTime() : Number.NaN; +function freshWindow(window: UsageQuotaWindow, now: number): boolean { + const observed = date(window.observedAt); + const reset = date(window.resetsAt); + return ( + Number.isFinite(observed) && + observed <= now && + now - observed <= NATIVE_CLAUDE_FRESH_MS && + Number.isFinite(reset) && + reset > now && + Number.isFinite(window.usedPercent) && + window.usedPercent >= 0 && + window.usedPercent <= 100 + ); +} +export function mergeNativeClaudeQuota( + base: Quota, + native: NativeClaudeUsageWindow[], + now = Date.now(), +): Quota | null { + if (base.status !== "ok" && base.status !== "unavailable") return null; + const windows = [...base.windows]; + let changed = false; + for (const reading of native) { + if (reading.id !== "five_hour" && reading.id !== "seven_day") continue; + const window: UsageQuotaWindow = { + id: reading.id, + label: reading.id === "five_hour" ? "Session (5h)" : "Weekly", + usedPercent: reading.usedPercent, + resetsAt: new Date(reading.resetsAt), + observedAt: new Date(reading.observedAt), + source: reading.source, + }; + if (!freshWindow(window, now)) continue; + const oldIndex = windows.findIndex((value) => value.id === window.id); + const old = windows[oldIndex]; + if (old) { + const oldObservation = + old.observedAt === undefined + ? date(base.fetchedAt) + : date(old.observedAt); + if ( + Number.isFinite(oldObservation) && + oldObservation >= reading.observedAt + ) + continue; + const oldReset = date(old.resetsAt); + const oldEpoch = Math.floor(oldReset / 1000); + const nextEpoch = Math.floor(reading.resetsAt / 1000); + if ( + Number.isFinite(oldReset) && + (oldEpoch > nextEpoch || + (oldEpoch === nextEpoch && old.usedPercent > reading.usedPercent)) + ) + continue; + if (Number.isFinite(oldReset) && oldEpoch === nextEpoch) + window.resetsAt = new Date(Math.max(oldReset, reading.resetsAt)); + windows[oldIndex] = window; + } else windows.push(window); + changed = true; + } + return changed + ? { ...base, status: "ok", statusDetail: null, windows } + : null; +} +export function canDeferClaudeHttpQuota( + base: Quota, + overlay: Quota, + now = Date.now(), +): boolean { + const observed = date(base.fetchedAt); + if ( + !Number.isFinite(observed) || + observed > now || + now - observed >= HTTP_RECONCILE_MS + ) + return false; + if (base.prepaidBalance) { + const checkedAt = date(base.prepaidBalance.checkedAt); + if ( + !Number.isFinite(checkedAt) || + checkedAt > now || + now - checkedAt >= HTTP_RECONCILE_MS + ) + return false; + } + return ["five_hour", "seven_day"].every((id) => + overlay.windows.some( + (window) => + window.id === id && + (window.source === "claude_statusline" || + window.source === "claude_sdk") && + freshWindow(window, now), + ), + ); +} +export function createNativeClaudeQuotaOverlay(deps: { + enabled(): boolean; + generation(credential: NativeClaudeCredential): string; + readCurrent(selection: string | null): Promise; + resolveScope( + selection: string | null, + directory: string, + identity: string, + generation: string, + ): Promise; + isCurrent(token: string, quota: Quota): boolean; + snapshot(scope: string): NativeClaudeUsageWindow[]; + now?: () => number; +}) { + return async ( + credential: { accessToken: string; selection: string | null }, + quota: Quota, + ): Promise => { + if (!deps.enabled()) return null; + try { + const current = await deps.readCurrent(credential.selection); + if (!current || current.accessToken !== credential.accessToken) + return null; + const scope = await deps.resolveScope( + credential.selection, + current.canonicalProfile, + current.registrationHash, + deps.generation(current), + ); + if (!scope || !deps.isCurrent(credential.accessToken, quota)) return null; + return mergeNativeClaudeQuota( + quota, + deps.snapshot(scope), + deps.now?.() ?? Date.now(), + ); + } catch { + return null; + } + }; +} diff --git a/packages/host-service/src/trpc/router/usage/native-claude-scope.test.ts b/packages/host-service/src/trpc/router/usage/native-claude-scope.test.ts new file mode 100644 index 00000000000..00fb21af5a6 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-scope.test.ts @@ -0,0 +1,218 @@ +import { expect, test } from "bun:test"; +import { createNativeClaudeScopeResolver } from "./native-claude-scope"; +import { hashQuotaScope } from "./quota-cooldown-store"; +import { + bindClaudeQuotaIdentity, + claudeProfileRegistration, + claudeQuotaProof, + restoreClaudeQuotaIdentity, +} from "./quota-identity"; + +const profile = { + account: { + uuid: "11111111-1111-4111-8111-111111111111", + email: "fixture@example.test", + }, + organization: { uuid: "22222222-2222-4222-8222-222222222222" }, +}; +const identity = claudeProfileRegistration(profile) ?? ""; +const at = 1_000_000; +const credential = { + accessToken: "native-fixture-token", + canonicalProfile: "/fixture/profile", + registrationHash: identity, +}; + +test("cold launches capture only a generation and recover after authenticated shared proof warms", async () => { + let quota: object | undefined; + let reads = 0; + const resolver = createNativeClaudeScopeResolver({ + readCurrent: async () => { + reads++; + return credential; + }, + canonicalize: async (directory) => directory, + peekQuota: () => quota, + now: () => at, + }); + const generation = await resolver.captureGeneration( + "/fixture/profile", + "/fixture/profile", + identity, + ); + expect(generation).toMatch(/^[a-f0-9]{64}$/); + expect( + await resolver.resolve( + "/fixture/profile", + "/fixture/profile", + identity, + generation ?? "", + ), + ).toBeNull(); + quota = bindClaudeQuotaIdentity( + {}, + credential.accessToken, + profile, + at - 1000, + ); + const scope = await resolver.resolve( + "/fixture/profile", + "/fixture/profile", + identity, + generation ?? "", + ); + expect(scope).toMatch(/^[a-f0-9]{64}$/); + expect(scope).not.toBe(generation); + expect(JSON.stringify({ generation, scope })).not.toContain( + credential.accessToken, + ); + expect(reads).toBe(6); +}); + +test("registration exactly matches the public tuple and fails closed on conflicting aliases", () => { + expect(identity).toBe( + hashQuotaScope([profile.account.uuid, undefined, profile.account.email]), + ); + expect( + claudeProfileRegistration({ ...profile, email: "different@example.test" }), + ).toBeNull(); + expect( + claudeProfileRegistration({ + account: { uuid: profile.account.uuid }, + organization: profile.organization, + }), + ).toBeNull(); +}); + +test("persisted display proof, foreign registration, rotated token, changed directory and expired proof cannot authorize native scope", async () => { + const proof = claudeQuotaProof(credential.accessToken, profile, at); + if (!proof) throw new Error("Fixture proof missing."); + const persisted = restoreClaudeQuotaIdentity({}, proof, at); + let quota: object = persisted; + let current = credential; + let directory: string | null = "/fixture/profile"; + const resolver = createNativeClaudeScopeResolver({ + readCurrent: async () => current, + canonicalize: async () => directory, + peekQuota: () => quota, + now: () => at, + }); + expect(await resolver.resolve(null, "/fixture/profile", identity)).toBeNull(); + quota = bindClaudeQuotaIdentity({}, credential.accessToken, profile, at); + expect( + await resolver.resolve(null, "/fixture/profile", hashQuotaScope("foreign")), + ).toBeNull(); + const generation = await resolver.captureGeneration( + null, + "/fixture/profile", + identity, + ); + current = { ...credential, accessToken: "rotated-fixture-token" }; + expect( + await resolver.resolve( + null, + "/fixture/profile", + identity, + generation ?? "", + ), + ).toBeNull(); + current = credential; + directory = "/other/profile"; + expect(await resolver.resolve(null, "/fixture/profile", identity)).toBeNull(); + directory = "/fixture/profile"; + quota = bindClaudeQuotaIdentity( + {}, + credential.accessToken, + profile, + at - 6 * 60 * 60_000 - 1, + ); + expect(await resolver.resolve(null, "/fixture/profile", identity)).toBeNull(); +}); + +test("credential and canonical-path replacement at either proof boundary is rejected", async () => { + for (const replacedAt of [1, 2]) { + let reads = 0; + const quota = bindClaudeQuotaIdentity( + {}, + credential.accessToken, + profile, + at, + ); + const resolver = createNativeClaudeScopeResolver({ + readCurrent: async () => + ++reads === replacedAt + ? { ...credential, accessToken: "replaced" } + : credential, + canonicalize: async (value) => value, + peekQuota: () => quota, + now: () => at, + }); + expect( + await resolver.resolve(null, "/fixture/profile", identity), + ).toBeNull(); + } + let paths = 0; + const resolver = createNativeClaudeScopeResolver({ + readCurrent: async () => credential, + canonicalize: async () => + ++paths === 2 ? "/other/profile" : "/fixture/profile", + peekQuota: () => + bindClaudeQuotaIdentity({}, credential.accessToken, profile, at), + now: () => at, + }); + expect(await resolver.resolve(null, "/fixture/profile", identity)).toBeNull(); +}); + +test("captured and legacy proof resolution each use exactly two fresh credential reads", async () => { + let reads = 0; + const quota = bindClaudeQuotaIdentity( + {}, + credential.accessToken, + profile, + at, + ); + const resolver = createNativeClaudeScopeResolver({ + readCurrent: async () => { + reads++; + return credential; + }, + canonicalize: async (value) => value, + peekQuota: () => quota, + now: () => at, + }); + const captured = await resolver.captureGeneration( + null, + "/fixture/profile", + identity, + ); + expect(reads).toBe(2); + reads = 0; + expect( + await resolver.resolve(null, "/fixture/profile", identity, captured ?? ""), + ).toMatch(/^[a-f0-9]{64}$/); + expect(reads).toBe(2); + reads = 0; + expect(await resolver.resolve(null, "/fixture/profile", identity)).toMatch( + /^[a-f0-9]{64}$/, + ); + expect(reads).toBe(2); + expect( + await resolver.resolve(null, "/fixture/profile", identity, "wrong"), + ).toBeNull(); +}); + +test("directory retargeting during the final proof read rejects the original credential", async () => { + let directory = "/fixture/profile"; + let reads = 0; + const resolver = createNativeClaudeScopeResolver({ + readCurrent: async () => { + if (++reads === 2) directory = "/other/profile"; + return credential; + }, + canonicalize: async () => directory, + peekQuota: () => + bindClaudeQuotaIdentity({}, credential.accessToken, profile, at), + now: () => at, + }); + expect(await resolver.resolve(null, "/fixture/profile", identity)).toBeNull(); +}); diff --git a/packages/host-service/src/trpc/router/usage/native-claude-scope.ts b/packages/host-service/src/trpc/router/usage/native-claude-scope.ts new file mode 100644 index 00000000000..d1f0a560e16 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-scope.ts @@ -0,0 +1,137 @@ +import { hashQuotaScope } from "./quota-cooldown-store"; +import { verifiedNativeClaudeQuotaScope } from "./quota-identity"; + +export interface NativeClaudeCredential { + accessToken: string; + canonicalProfile: string; + registrationHash: string; +} + +export function nativeClaudeCredentialGeneration( + credential: NativeClaudeCredential, +): string { + return hashQuotaScope([ + "native-claude-generation-v1", + credential.canonicalProfile, + credential.registrationHash, + credential.accessToken, + ]); +} + +/** Cache-only binding. A cold launch may retain quarantined counters, never quota authority. */ +export function createNativeClaudeScopeResolver({ + readCurrent, + canonicalize, + peekQuota, + now = () => Date.now(), +}: { + readCurrent(selection: string | null): Promise; + canonicalize(directory: string): Promise; + peekQuota(token: string): object | undefined; + now?: () => number; +}) { + const generation = nativeClaudeCredentialGeneration; + async function read( + selection: string | null, + expectedDirectory: string, + expectedIdentity: string, + ) { + const directory = await canonicalize(expectedDirectory); + if (!directory) return null; + const current = await readCurrent(selection); + return current && + current.canonicalProfile === directory && + current.registrationHash === expectedIdentity && + (await canonicalize(expectedDirectory)) === directory + ? current + : null; + } + async function capture( + selection: string | null, + expectedDirectory: string, + expectedIdentity: string, + ) { + if (!/^[a-f0-9]{64}$/.test(expectedIdentity)) return null; + try { + const current = await read( + selection, + expectedDirectory, + expectedIdentity, + ); + const next = + current && (await read(selection, expectedDirectory, expectedIdentity)); + if (!current || !next || generation(current) !== generation(next)) + return null; + return { credential: current, generation: generation(current) }; + } catch { + return null; + } + } + return { + async captureGeneration( + selection: string | null, + expectedDirectory: string, + expectedIdentity: string, + ) { + return ( + (await capture(selection, expectedDirectory, expectedIdentity)) + ?.generation ?? null + ); + }, + async resolve( + selection: string | null, + expectedDirectory: string, + expectedIdentity: string, + expectedGeneration?: string, + ) { + if ( + !/^[a-f0-9]{64}$/.test(expectedIdentity) || + (expectedGeneration !== undefined && + !/^[a-f0-9]{64}$/.test(expectedGeneration)) + ) + return null; + let credential: NativeClaudeCredential | null; + try { + credential = await read(selection, expectedDirectory, expectedIdentity); + } catch { + return null; + } + if (!credential) return null; + const capturedGeneration = generation(credential); + if ( + expectedGeneration !== undefined && + capturedGeneration !== expectedGeneration + ) + return null; + const quota = peekQuota(credential.accessToken); + const scope = quota + ? verifiedNativeClaudeQuotaScope( + quota, + credential.accessToken, + credential.canonicalProfile, + expectedIdentity, + now(), + ) + : null; + // The cached proof check is also fenced against a credential replacement during lookup. + try { + const next = await read(selection, expectedDirectory, expectedIdentity); + if ( + !next || + generation(next) !== capturedGeneration || + (await canonicalize(expectedDirectory)) !== + credential.canonicalProfile + ) + return null; + } catch { + return null; + } + if (!scope) return null; + return hashQuotaScope([ + "native-claude-scope-v1", + scope, + capturedGeneration, + ]); + }, + }; +} diff --git a/packages/host-service/src/trpc/router/usage/native-claude-usage.test.ts b/packages/host-service/src/trpc/router/usage/native-claude-usage.test.ts new file mode 100644 index 00000000000..196cd358dc3 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-usage.test.ts @@ -0,0 +1,680 @@ +import { afterEach, expect, test } from "bun:test"; +import { + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + createNativeClaudeUsageStore, + parseNativeClaudeSdkUsage, +} from "./native-claude-usage"; + +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) + rmSync(directory, { recursive: true, force: true }); +}); +function fixture() { + const directory = mkdtempSync(join(tmpdir(), "native-usage-")); + directories.push(directory); + let now = 1_800_000_000_000; + const file = join(directory, "native.json"); + const store = createNativeClaudeUsageStore({ file, now: () => now }); + const identity = { + scope: "a".repeat(64), + launchId: "owned-launch", + sessionId: "owned-session", + }; + store.bindLaunch(identity); + const frame = (counter: number, five = 10, weekly?: number) => ({ + cost: { total_api_duration_ms: counter }, + rate_limits: { + five_hour: { used_percentage: five, resets_at: (now + 60_000) / 1000 }, + ...(weekly === undefined + ? {} + : { + seven_day: { + used_percentage: weekly, + resets_at: (now + 120_000) / 1000, + }, + }), + }, + }); + return { + directory, + file, + store, + identity, + frame, + time: () => now, + advance: (ms = 1000) => { + now += ms; + }, + }; +} +test("first statusline frame is a baseline; API progress updates only supplied windows", () => { + const f = fixture(); + const initial = f.frame(10, 20, 30); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: initial, + }), + ).toBe(false); + expect(f.store.snapshot(f.identity.scope)).toEqual([]); + f.advance(); + const response = f.frame(11, 21, 31); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: response, + }), + ).toBe(true); + const measured = f.store.snapshot(f.identity.scope); + f.advance(); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: response, + }), + ).toBe(false); + expect(f.store.snapshot(f.identity.scope)).toEqual(measured); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: initial, + }), + ).toBe(false); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: response, + }), + ).toBe(false); + expect(f.store.snapshot(f.identity.scope)).toEqual(measured); + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: f.frame(12, 21), + }); + expect( + f.store + .snapshot(f.identity.scope) + .find((window) => window.id === "seven_day")?.observedAt, + ).toBe(measured.find((window) => window.id === "seven_day")?.observedAt); + expect( + f.store + .snapshot(f.identity.scope) + .find((window) => window.id === "five_hour")?.observedAt, + ).toBe(f.time()); +}); +test("startup without quota seeds the first real response and persisted replays keep original age", () => { + const f = fixture(); + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: { cost: { total_api_duration_ms: 0 } }, + }); + const response = f.frame(1); + f.advance(); + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: response, + }); + const before = f.store.snapshot(f.identity.scope); + f.advance(); + const reopened = createNativeClaudeUsageStore({ file: f.file, now: f.time }); + expect( + reopened.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: response, + }), + ).toBe(false); + expect(reopened.snapshot(f.identity.scope)).toEqual(before); + expect(statSync(f.file).mode & 0o777).toBe(0o600); + const serialized = readFileSync(f.file, "utf8"); + expect(serialized).not.toContain("owned-launch"); + expect(serialized).not.toContain("owned-session"); +}); +test("launch identity cannot be retargeted after sign-in changes and unknown generations are rejected", () => { + const f = fixture(); + expect(f.store.bindLaunch({ ...f.identity, scope: "b".repeat(64) })).toBe( + false, + ); + for (const change of [ + { scope: "b".repeat(64) }, + { launchId: "other" }, + { sessionId: "other" }, + ]) { + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + ...change, + source: "claude_statusline", + payload: f.frame(1), + }), + ).toBe(false); + } + expect(f.store.snapshot("b".repeat(64))).toEqual([]); +}); +test("SDK restored state and unchanged UUID replays do not establish a new measurement", () => { + const f = fixture(); + const event = (uuid: string, used = 0.2) => ({ + type: "rate_limit_event", + uuid, + rate_limit_info: { + status: "allowed", + rateLimitType: "five_hour", + utilization: used, + resetsAt: (f.time() + 60_000) / 1000, + }, + }); + const initial = event("cached"); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_sdk", + responseCounter: 0, + payload: initial, + }), + ).toBe(false); + f.advance(); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_sdk", + responseCounter: 0, + payload: event("new-id", 0.3), + }), + ).toBe(false); + f.advance(); + const fresh = event("response", 0.4); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_sdk", + responseCounter: 1, + payload: fresh, + }), + ).toBe(true); + const before = f.store.snapshot(f.identity.scope); + f.advance(); + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_sdk", + responseCounter: 1, + payload: fresh, + }), + ).toBe(false); + expect(f.store.snapshot(f.identity.scope)).toEqual(before); +}); +test("partial SDK fields never turn status or spend limits into subscription percentages", () => { + const f = fixture(); + const parsed = parseNativeClaudeSdkUsage( + { + type: "rate_limit_event", + uuid: "event", + rate_limit_info: { + status: "rejected", + rateLimitType: "overage", + utilization: 1, + resetsAt: (f.time() + 60_000) / 1000, + overageDisabledReason: "out_of_credits", + }, + }, + f.time(), + ); + expect(parsed?.windows).toEqual([]); + expect( + parseNativeClaudeSdkUsage( + { + type: "rate_limit_event", + uuid: "event", + rate_limit_info: { + status: "allowed_warning", + rateLimitType: "five_hour", + }, + }, + f.time(), + )?.windows, + ).toEqual([]); +}); +test("expired windows, missing response markers and backwards clocks are never current quota", () => { + const f = fixture(); + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: f.frame(0), + }); + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: f.frame(1), + }); + f.advance(61_000); + expect(f.store.snapshot(f.identity.scope)).toEqual([]); + const unmarked = { + rate_limits: { + five_hour: { used_percentage: 1, resets_at: (f.time() + 60_000) / 1000 }, + }, + }; + expect( + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: unmarked, + }), + ).toBe(false); +}); +test("private persistence refuses a symlink destination and never follows it", () => { + const f = fixture(); + const target = join(f.directory, "target"); + writeFileSync(target, "sentinel"); + rmSync(f.file); + symlinkSync(target, f.file); + expect(() => + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: f.frame(0), + }), + ).toThrow(); + expect(readFileSync(target, "utf8")).toBe("sentinel"); +}); + +test("pending measurements survive host restart and promotion does not relabel their age", () => { + const f = fixture(); + const launch = { + launchId: "new-owned-launch", + sessionId: "new-owned-session", + generation: "c".repeat(64), + }; + f.store.captureLaunch(launch); + const pending = f.store.activeScope(launch); + expect(pending?.pending).toBe(true); + if (!pending) throw new Error("missing captured generation"); + f.store.ingest({ + receivedAt: f.time(), + ...launch, + scope: pending.scope, + source: "claude_statusline", + payload: f.frame(0), + }); + f.advance(); + f.store.ingest({ + receivedAt: f.time(), + ...launch, + scope: pending.scope, + source: "claude_statusline", + payload: f.frame(1), + }); + const observedAt = f.time(); + f.advance(); + const restarted = createNativeClaudeUsageStore({ file: f.file, now: f.time }); + const scope = "d".repeat(64); + expect(restarted.promoteLaunch({ ...launch, scope })).toBe(true); + expect(restarted.snapshot(scope)[0]?.observedAt).toBe(observedAt); + expect( + restarted.ingest({ + receivedAt: f.time(), + ...launch, + scope, + source: "claude_statusline", + payload: f.frame(1), + }), + ).toBe(false); + expect(restarted.snapshot(scope)[0]?.observedAt).toBe(observedAt); +}); +test("late lower readings in the same reset epoch cannot erase newer utilization", () => { + const f = fixture(); + const initial = f.frame(0, 20); + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: initial, + }); + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: f.frame(1, 30), + }); + const before = f.store.snapshot(f.identity.scope); + f.advance(); + const lower = { ...initial, cost: { total_api_duration_ms: 2 } }; + f.store.ingest({ + receivedAt: f.time(), + ...f.identity, + source: "claude_statusline", + payload: lower, + }); + expect(f.store.snapshot(f.identity.scope)).toEqual(before); +}); + +test("delayed validation retains the trusted receipt instead of the processing clock", () => { + const f = fixture(); + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: f.frame(0), + }); + f.advance(); + const receivedAt = f.time(); + const payload = f.frame(1, 35); + f.advance(45_000); + expect( + f.store.ingest({ + ...f.identity, + receivedAt, + source: "claude_statusline", + payload, + }), + ).toBe(true); + expect(f.store.snapshot(f.identity.scope)[0]?.observedAt).toBe(receivedAt); + expect(f.store.snapshot(f.identity.scope)[0]?.observedAt).not.toBe(f.time()); +}); + +test("missing, invalid, future or expired receipts never alter the response baseline", () => { + const f = fixture(); + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: f.frame(0), + }); + for (const receivedAt of [ + undefined, + Number.NaN, + Number.POSITIVE_INFINITY, + -1, + f.time() + 1, + f.time() - 6 * 60_000 - 1, + ]) { + expect( + f.store.ingest({ + ...f.identity, + receivedAt: receivedAt as number, + source: "claude_statusline", + payload: f.frame(100, 90), + }), + ).toBe(false); + } + expect(f.store.snapshot(f.identity.scope)).toEqual([]); + f.advance(); + expect( + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: f.frame(1, 30), + }), + ).toBe(true); + expect(f.store.snapshot(f.identity.scope)[0]?.usedPercent).toBe(30); +}); + +test("six-minute receipt boundary is inclusive; an older receipt cannot move the baseline", () => { + const f = fixture(); + const first = f.time(); + const payload = { + cost: { total_api_duration_ms: 1 }, + rate_limits: { + five_hour: { + used_percentage: 25, + resets_at: (first + 60 * 60_000) / 1000, + }, + }, + }; + f.store.ingest({ + ...f.identity, + receivedAt: first, + source: "claude_statusline", + payload: { cost: { total_api_duration_ms: 0 } }, + }); + f.advance(6 * 60_000); + expect( + f.store.ingest({ + ...f.identity, + receivedAt: first, + source: "claude_statusline", + payload, + }), + ).toBe(true); + expect(f.store.snapshot(f.identity.scope)[0]?.observedAt).toBe(first); + f.advance(1); + expect( + f.store.ingest({ + ...f.identity, + receivedAt: first, + source: "claude_statusline", + payload: { ...payload, cost: { total_api_duration_ms: 100 } }, + }), + ).toBe(false); + expect( + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: { ...payload, cost: { total_api_duration_ms: 2 } }, + }), + ).toBe(true); + expect(f.store.snapshot(f.identity.scope)[0]?.observedAt).toBe(f.time()); +}); + +test("out-of-order receipt cannot overwrite newer quota or consume a later response counter", () => { + const f = fixture(); + const frame = f.frame(0); + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: frame, + }); + f.advance(2000); + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: { ...frame, cost: { total_api_duration_ms: 2 } }, + }); + const before = f.store.snapshot(f.identity.scope); + expect( + f.store.ingest({ + ...f.identity, + receivedAt: f.time() - 1000, + source: "claude_statusline", + payload: { ...frame, cost: { total_api_duration_ms: 3 } }, + }), + ).toBe(false); + expect(f.store.snapshot(f.identity.scope)).toEqual(before); + f.advance(); + expect( + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: { ...frame, cost: { total_api_duration_ms: 3 } }, + }), + ).toBe(true); +}); + +const resetPrecisionCases = [ + ["same second with 213ms HTTP precision", 213, 0, 30, true, 213], + ["same second with higher usage", 213, 0, 31, true, 213], + ["same second with lower usage", 0, 213, 29, false, 0], + ["earlier second with higher usage", 0, -1000, 99, false, 0], + ["later second with lower usage", 0, 1000, 1, true, 1000], + ["one millisecond into a later second", 999, 1000, 1, true, 1000], + ["one millisecond into the previous second", 1000, 999, 99, false, 1000], +] as const; + +function precisionFrame( + counter: number, + usedPercent: number, + resetsAt: number, +) { + return { + cost: { total_api_duration_ms: counter }, + rate_limits: { + five_hour: { used_percentage: usedPercent, resets_at: resetsAt / 1000 }, + }, + }; +} +test.each( + resetPrecisionCases, +)("live native reset precision: %s", (_name, previousOffset, nextOffset, usedPercent, accepted, keptOffset) => { + const f = fixture(); + const reset = f.time() + 120_000; + const ingest = ( + counter: number, + used: number, + at: number, + receivedAt = f.time(), + ) => + f.store.ingest({ + ...f.identity, + receivedAt, + source: "claude_statusline", + payload: precisionFrame(counter, used, at), + }); + ingest(0, 30, reset + previousOffset); + f.advance(); + expect(ingest(1, 30, reset + previousOffset)).toBe(true); + const previousObservedAt = f.time(); + f.advance(); + expect(ingest(2, usedPercent, reset + nextOffset)).toBe(accepted); + const current = f.store.snapshot(f.identity.scope); + expect(current[0]?.resetsAt).toBe(reset + keptOffset); + expect(current[0]?.usedPercent).toBe(accepted ? usedPercent : 30); + expect(current[0]?.observedAt).toBe(accepted ? f.time() : previousObservedAt); + f.advance(); + expect(ingest(2, usedPercent, reset + nextOffset)).toBe(false); + expect(f.store.snapshot(f.identity.scope)).toEqual(current); +}); +test.each( + resetPrecisionCases, +)("pending native promotion preserves reset precision and original age: %s", (_name, previousOffset, nextOffset, usedPercent, accepted, keptOffset) => { + const f = fixture(); + const reset = f.time() + 120_000; + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: precisionFrame(0, 30, reset + previousOffset), + }); + f.advance(); + f.store.ingest({ + ...f.identity, + receivedAt: f.time(), + source: "claude_statusline", + payload: precisionFrame(1, 30, reset + previousOffset), + }); + const previousObservedAt = f.time(); + const launch = { + launchId: "precision-pending", + sessionId: "pending-session", + generation: "c".repeat(64), + }; + f.store.captureLaunch(launch); + const pending = f.store.activeScope(launch); + if (!pending) throw new Error("missing pending launch"); + f.store.ingest({ + ...launch, + scope: pending.scope, + receivedAt: f.time(), + source: "claude_statusline", + payload: precisionFrame(0, usedPercent, reset + nextOffset), + }); + f.advance(); + f.store.ingest({ + ...launch, + scope: pending.scope, + receivedAt: f.time(), + source: "claude_statusline", + payload: precisionFrame(1, usedPercent, reset + nextOffset), + }); + const pendingObservedAt = f.time(); + f.advance(); + expect(f.store.promoteLaunch({ ...launch, scope: f.identity.scope })).toBe( + true, + ); + const current = f.store.snapshot(f.identity.scope); + expect(current[0]?.resetsAt).toBe(reset + keptOffset); + expect(current[0]?.usedPercent).toBe(accepted ? usedPercent : 30); + expect(current[0]?.observedAt).toBe( + accepted ? pendingObservedAt : previousObservedAt, + ); + expect(current[0]?.observedAt).not.toBe(f.time()); + expect(current[0]?.source).toBe("claude_statusline"); +}); +test("same-second reset precision cannot freshen stale or equal-counter receipts", () => { + const f = fixture(); + const reset = f.time() + 120_000; + const ingest = (counter: number, resetsAt: number, receivedAt = f.time()) => + f.store.ingest({ + ...f.identity, + receivedAt, + source: "claude_statusline", + payload: precisionFrame(counter, 30, resetsAt), + }); + ingest(0, reset + 213); + f.advance(); + ingest(1, reset + 213); + const measured = f.store.snapshot(f.identity.scope); + const observedAt = f.time(); + f.advance(); + expect(ingest(2, reset, observedAt - 1)).toBe(false); + expect(ingest(1, reset, observedAt)).toBe(false); + expect(f.store.snapshot(f.identity.scope)).toEqual(measured); + expect(ingest(2, reset)).toBe(true); + expect(f.store.snapshot(f.identity.scope)[0]?.resetsAt).toBe(reset + 213); + expect(f.store.snapshot(f.identity.scope)[0]?.observedAt).toBe(f.time()); +}); + +test("captured generation lookup refuses expired or future-dated launch records", () => { + const f = fixture(); + const launch = { launchId: "captured-launch", sessionId: "captured-session" }; + expect(f.store.captureLaunch({ ...launch, generation: "b".repeat(64) })).toBe( + true, + ); + expect(f.store.capturedGeneration(launch)).toBe("b".repeat(64)); + f.advance(-1); + expect(f.store.capturedGeneration(launch)).toBeNull(); + f.advance(14 * 24 * 60 * 60_000 + 2); + expect(f.store.capturedGeneration(launch)).toBeNull(); + expect( + f.store.capturedGeneration({ ...launch, sessionId: "foreign" }), + ).toBeNull(); +}); diff --git a/packages/host-service/src/trpc/router/usage/native-claude-usage.ts b/packages/host-service/src/trpc/router/usage/native-claude-usage.ts new file mode 100644 index 00000000000..58fa3488398 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/native-claude-usage.ts @@ -0,0 +1,663 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + closeSync, + constants, + fstatSync, + lstatSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { z } from "zod"; + +export type NativeClaudeWindowId = "five_hour" | "seven_day"; +export type NativeClaudeUsageSource = "claude_statusline" | "claude_sdk"; +export interface NativeClaudeUsageWindow { + id: NativeClaudeWindowId; + usedPercent: number; + resetsAt: number; + observedAt: number; + source: NativeClaudeUsageSource; +} +export interface NativeClaudeUsageInput { + scope: string; + launchId: string; + sessionId: string; + source: NativeClaudeUsageSource; + payload: unknown; + /** Host receipt before queues or asynchronous identity validation. Never provider input. */ + receivedAt: number; + responseCounter?: number; + quarantined?: boolean; +} +export const NATIVE_CLAUDE_FRESH_MS = 6 * 60_000; +const MAX_BYTES = 512 * 1024; +const MAX_SCOPES = 128; +const MAX_BINDINGS = 256; +const MAX_AGE_MS = 14 * 24 * 60 * 60_000; +const hash = (value: unknown) => + createHash("sha256").update(JSON.stringify(value)).digest("hex"); +const digest = z.string().regex(/^[a-f0-9]{64}$/); +const finiteTime = z.number().finite().nonnegative(); +const windowSchema = z.object({ + id: z.enum(["five_hour", "seven_day"]), + usedPercent: z.number().finite().min(0).max(100), + resetsAt: finiteTime, + observedAt: finiteTime, + source: z.enum(["claude_statusline", "claude_sdk"]), +}); +const stateSchema = z.object({ + version: z.literal(1), + scopes: z + .array( + z.object({ + key: digest, + windows: z.array(windowSchema).max(2), + updatedAt: finiteTime, + }), + ) + .max(MAX_SCOPES), + launches: z + .array( + z.object({ + key: digest, + scope: digest, + generation: digest.optional(), + pending: z.boolean().optional(), + updatedAt: finiteTime, + }), + ) + .max(MAX_BINDINGS), + bindings: z + .array( + z.object({ + key: digest, + counter: finiteTime.nullable(), + event: digest.nullable(), + signatures: z.record(z.string(), digest), + updatedAt: finiteTime, + }), + ) + .max(MAX_BINDINGS), +}); +type State = z.infer; +type Reading = Omit; +function object(value: unknown): Record | null { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} +function validId(value: string): boolean { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= 256 && + [...value].every((character) => character.charCodeAt(0) >= 32) + ); +} +function reading( + id: NativeClaudeWindowId, + percent: unknown, + reset: unknown, + now: number, +): Reading | null { + if ( + typeof percent !== "number" || + !Number.isFinite(percent) || + percent < 0 || + percent > 100 || + typeof reset !== "number" || + !Number.isFinite(reset) || + reset * 1000 <= now || + reset * 1000 > now + 366 * 24 * 60 * 60_000 + ) + return null; + return { id, usedPercent: percent, resetsAt: reset * 1000 }; +} +export function parseNativeClaudeStatusline( + payload: unknown, + now: number, +): { counter: number | null; windows: Reading[] } | null { + const root = object(payload); + if (!root) return null; + const cost = object(root.cost); + const duration = cost?.total_api_duration_ms; + const counter = + typeof duration === "number" && Number.isFinite(duration) && duration >= 0 + ? duration + : null; + const limits = object(root.rate_limits); + const windows = (["five_hour", "seven_day"] as const).flatMap((id) => { + const value = object(limits?.[id]); + const parsed = reading(id, value?.used_percentage, value?.resets_at, now); + return parsed ? [parsed] : []; + }); + return { counter, windows }; +} +export function parseNativeClaudeSdkUsage( + payload: unknown, + now: number, +): { event: string; windows: Reading[] } | null { + const root = object(payload); + const info = object(root?.rate_limit_info); + if ( + root?.type !== "rate_limit_event" || + typeof root.uuid !== "string" || + !validId(root.uuid) || + !info + ) + return null; + const windows: Reading[] = []; + const unified = object(info.unifiedWindows); + for (const id of ["five_hour", "seven_day"] as const) { + const value = object(unified?.[id]); + const utilization = value?.utilization; + const parsed = reading( + id, + typeof utilization === "number" && + utilization >= 0 && + Number.isFinite(utilization) + ? Math.min(100, utilization * 100) + : null, + value?.resetsAt, + now, + ); + if (parsed) windows.push(parsed); + } + if ( + info.rateLimitType === "five_hour" || + info.rateLimitType === "seven_day" + ) { + const utilization = info.utilization; + const parsed = reading( + info.rateLimitType, + typeof utilization === "number" && + utilization >= 0 && + Number.isFinite(utilization) + ? Math.min(100, utilization * 100) + : null, + info.resetsAt, + now, + ); + if (parsed && !windows.some((window) => window.id === parsed.id)) + windows.push(parsed); + } + return { event: hash(root.uuid), windows }; +} +function secureRead(file: string): string { + const fd = openSync( + file, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const stat = fstatSync(fd); + if ( + !stat.isFile() || + stat.nlink !== 1 || + stat.size > MAX_BYTES || + (process.platform !== "win32" && + ((stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())) + ) + throw new Error("Unsafe native usage storage"); + const contents = readFileSync(fd, "utf8"); + if (Buffer.byteLength(contents) > MAX_BYTES) + throw new Error("Oversized native usage storage"); + return contents; + } finally { + closeSync(fd); + } +} +export function createNativeClaudeUsageStore( + options: { file?: string; now?: () => number; persist?: boolean } = {}, +) { + const file = + options.file ?? + join( + process.env.SUPERSET_HOME_DIR?.trim() || join(homedir(), ".superset"), + "state", + "native-claude-usage.json", + ); + const now = options.now ?? Date.now; + let state: State | undefined; + function load(): State { + if (state) return state; + try { + state = stateSchema.parse(JSON.parse(secureRead(file))); + } catch { + state = { version: 1, scopes: [], launches: [], bindings: [] }; + } + return state; + } + function save() { + if (options.persist === false) return; + const data = JSON.stringify(stateSchema.parse(load())); + if (Buffer.byteLength(data) > MAX_BYTES) + throw new Error("Native usage storage is full"); + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + const directory = lstatSync(dirname(file)); + if ( + !directory.isDirectory() || + directory.isSymbolicLink() || + (process.platform !== "win32" && directory.uid !== process.getuid?.()) + ) + throw new Error("Unsafe native usage directory"); + try { + secureRead(file); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + const temporary = `${file}.${randomUUID()}.tmp`; + try { + writeFileSync(temporary, data, { flag: "wx", mode: 0o600 }); + renameSync(temporary, file); + } finally { + try { + unlinkSync(temporary); + } catch {} + } + } + function prune(at: number) { + const value = load(); + value.scopes = value.scopes + .filter( + (item) => item.updatedAt <= at && at - item.updatedAt <= MAX_AGE_MS, + ) + .sort((a, b) => b.updatedAt - a.updatedAt) + .slice(0, MAX_SCOPES); + value.launches = value.launches + .filter( + (item) => item.updatedAt <= at && at - item.updatedAt <= MAX_AGE_MS, + ) + .sort((a, b) => b.updatedAt - a.updatedAt) + .slice(0, MAX_BINDINGS); + value.bindings = value.bindings + .filter( + (item) => item.updatedAt <= at && at - item.updatedAt <= MAX_AGE_MS, + ) + .sort((a, b) => b.updatedAt - a.updatedAt) + .slice(0, MAX_BINDINGS); + } + function validReceipt(receivedAt: number, at: number): boolean { + return ( + Number.isFinite(at) && + at >= 0 && + Number.isFinite(receivedAt) && + receivedAt >= 0 && + receivedAt <= at && + at - receivedAt <= NATIVE_CLAUDE_FRESH_MS + ); + } + return { + isCurrentReceipt(receivedAt: number): boolean { + return validReceipt(receivedAt, now()); + }, + captureLaunch(input: { + generation: string; + launchId: string; + sessionId: string; + }): boolean { + if ( + !digest.safeParse(input.generation).success || + !validId(input.launchId) || + !validId(input.sessionId) + ) + return false; + const at = now(); + prune(at); + const value = load(); + const key = hash(["launch", input.launchId, input.sessionId]); + const existing = value.launches.find((item) => item.key === key); + if (existing) return existing.generation === input.generation; + value.launches.unshift({ + key, + scope: hash([ + "pending-native-claude-v1", + input.generation, + input.launchId, + input.sessionId, + ]), + generation: input.generation, + pending: true, + updatedAt: at, + }); + prune(at); + save(); + return true; + }, + capturedGeneration(input: { + launchId: string; + sessionId: string; + }): string | null { + if (!validId(input.launchId) || !validId(input.sessionId)) return null; + const at = now(); + const launch = load().launches.find( + (item) => + item.key === hash(["launch", input.launchId, input.sessionId]), + ); + return launch?.generation && + launch.updatedAt <= at && + at - launch.updatedAt <= MAX_AGE_MS + ? launch.generation + : null; + }, + activeScope(input: { + generation: string; + launchId: string; + sessionId: string; + }): { scope: string; pending: boolean } | null { + if (!digest.safeParse(input.generation).success) return null; + const value = load().launches.find( + (item) => + item.key === hash(["launch", input.launchId, input.sessionId]) && + item.generation === input.generation, + ); + return value + ? { scope: value.scope, pending: value.pending === true } + : null; + }, + promoteLaunch(input: { + generation: string; + scope: string; + launchId: string; + sessionId: string; + }): boolean { + if ( + !digest.safeParse(input.generation).success || + !digest.safeParse(input.scope).success + ) + return false; + const at = now(); + prune(at); + const value = load(); + const launch = value.launches.find( + (item) => + item.key === hash(["launch", input.launchId, input.sessionId]) && + item.generation === input.generation, + ); + if (!launch) return false; + if (!launch.pending) return launch.scope === input.scope; + const from = launch.scope; + for (const source of ["claude_statusline", "claude_sdk"] as const) { + const previousKey = hash([ + from, + input.launchId, + input.sessionId, + source, + ]); + const binding = value.bindings.find((item) => item.key === previousKey); + if (binding) + binding.key = hash([ + input.scope, + input.launchId, + input.sessionId, + source, + ]); + } + const pending = value.scopes.find((item) => item.key === from); + if (pending) { + let target = value.scopes.find((item) => item.key === input.scope); + if (!target) { + target = { + key: input.scope, + windows: [], + updatedAt: pending.updatedAt, + }; + value.scopes.unshift(target); + } + for (const window of pending.windows) { + const previous = target.windows.find((item) => item.id === window.id); + const previousEpoch = Math.floor( + (previous?.resetsAt ?? Number.NaN) / 1000, + ); + const nextEpoch = Math.floor(window.resetsAt / 1000); + if ( + window.observedAt > at || + window.resetsAt <= at || + (previous && + (previous.observedAt > window.observedAt || + previousEpoch > nextEpoch || + (previousEpoch === nextEpoch && + previous.usedPercent > window.usedPercent))) + ) + continue; + target.windows = [ + ...target.windows.filter((item) => item.id !== window.id), + { + ...window, + resetsAt: + previous && previousEpoch === nextEpoch + ? Math.max(previous.resetsAt, window.resetsAt) + : window.resetsAt, + }, + ]; + target.updatedAt = Math.max(target.updatedAt, pending.updatedAt); + } + value.scopes = value.scopes.filter((item) => item.key !== from); + } + launch.scope = input.scope; + launch.pending = false; + save(); + return true; + }, + bindLaunch(input: { + scope: string; + launchId: string; + sessionId: string; + }): boolean { + if ( + !digest.safeParse(input.scope).success || + !validId(input.launchId) || + !validId(input.sessionId) + ) + return false; + const at = now(); + prune(at); + const value = load(); + const key = hash(["launch", input.launchId, input.sessionId]); + const existing = value.launches.find((item) => item.key === key); + if (existing) return existing.scope === input.scope; + value.launches.unshift({ key, scope: input.scope, updatedAt: at }); + prune(at); + save(); + return true; + }, + hasLaunch(input: { + scope: string; + launchId: string; + sessionId: string; + }): boolean { + return ( + digest.safeParse(input.scope).success && + load().launches.some( + (item) => + item.key === hash(["launch", input.launchId, input.sessionId]) && + item.scope === input.scope, + ) + ); + }, + ingest(input: NativeClaudeUsageInput): boolean { + const at = now(); + if ( + !validReceipt(input.receivedAt, at) || + !digest.safeParse(input.scope).success || + !validId(input.launchId) || + !validId(input.sessionId) + ) + return false; + const parsed = + input.source === "claude_statusline" + ? parseNativeClaudeStatusline(input.payload, at) + : parseNativeClaudeSdkUsage(input.payload, at); + if (!parsed || !Number.isFinite(at) || at < 0) return false; + prune(at); + const value = load(); + if ( + !value.launches.some( + (item) => + item.key === hash(["launch", input.launchId, input.sessionId]) && + item.scope === input.scope, + ) + ) + return false; + const key = hash([ + input.scope, + input.launchId, + input.sessionId, + input.source, + ]); + let binding = value.bindings.find((item) => item.key === key); + const previous = binding; + if (previous && previous.updatedAt > input.receivedAt) return false; + const counter = + "counter" in parsed + ? parsed.counter + : typeof input.responseCounter === "number" && + Number.isFinite(input.responseCounter) && + input.responseCounter >= 0 + ? input.responseCounter + : null; + const event = "event" in parsed ? parsed.event : null; + if ( + counter === null || + (previous?.counter !== null && + previous?.counter !== undefined && + counter < previous.counter) + ) + return false; + const signatures = Object.fromEntries( + parsed.windows.map((window) => [window.id, hash(window)]), + ); + if (!binding) { + binding = { + key, + counter, + event, + signatures, + updatedAt: input.receivedAt, + }; + value.bindings.unshift(binding); + } + const advanced = + !!previous && + counter !== null && + previous.counter !== null && + counter > previous.counter; + const windows = parsed.windows.filter( + (window) => + advanced && + (input.source === "claude_statusline" || + previous?.signatures[window.id] !== signatures[window.id]), + ); + const baselineChanged = + binding.counter !== counter || + JSON.stringify(binding.signatures) !== JSON.stringify(signatures); + if (baselineChanged || !previous) + Object.assign(binding, { + counter, + event, + signatures, + updatedAt: input.receivedAt, + }); + let applied = false; + if (windows.length) { + let scope = value.scopes.find((item) => item.key === input.scope); + if (!scope) { + scope = { + key: input.scope, + windows: [], + updatedAt: input.receivedAt, + }; + value.scopes.unshift(scope); + } + for (const window of windows) { + const existing = scope.windows.find((item) => item.id === window.id); + const existingEpoch = Math.floor( + (existing?.resetsAt ?? Number.NaN) / 1000, + ); + const nextEpoch = Math.floor(window.resetsAt / 1000); + if ( + existing && + (existing.observedAt > input.receivedAt || + existingEpoch > nextEpoch || + (existingEpoch === nextEpoch && + existing.usedPercent > window.usedPercent)) + ) + continue; + applied = true; + scope.windows = [ + ...scope.windows.filter((item) => item.id !== window.id), + { + ...window, + resetsAt: + existing && existingEpoch === nextEpoch + ? Math.max(existing.resetsAt, window.resetsAt) + : window.resetsAt, + observedAt: input.receivedAt, + source: input.source, + }, + ]; + } + if (applied) + scope.updatedAt = Math.max(scope.updatedAt, input.receivedAt); + } + prune(at); + if (windows.length || baselineChanged || !previous) save(); + return applied; + }, + snapshot(scope: string): NativeClaudeUsageWindow[] { + if (!digest.safeParse(scope).success) return []; + const at = now(); + return ( + load() + .scopes.find((item) => item.key === scope) + ?.windows.filter( + (window) => + window.observedAt <= at && + at - window.observedAt <= MAX_AGE_MS && + window.resetsAt > at, + ) + .map((window) => ({ ...window })) ?? [] + ); + }, + forget(scope: string): void { + const value = load(); + value.scopes = value.scopes.filter((item) => item.key !== scope); + save(); + }, + }; +} +const listeners = new Set<() => void>(); +export function onNativeClaudeUsage(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} +const store = createNativeClaudeUsageStore(); +export const nativeClaudeUsage = { + ...store, + promoteLaunch(input: Parameters[0]): boolean { + const before = store.activeScope(input); + const promoted = store.promoteLaunch(input); + if (promoted && before?.pending && store.snapshot(input.scope).length) + emitNativeClaudeUsage(); + return promoted; + }, + ingest(input: NativeClaudeUsageInput): boolean { + const changed = store.ingest(input); + if (changed && !input.quarantined) emitNativeClaudeUsage(); + return changed; + }, +}; +function emitNativeClaudeUsage(): void { + for (const listener of listeners) { + try { + listener(); + } catch {} + } +} diff --git a/packages/host-service/src/trpc/router/usage/opencode-quota.ts b/packages/host-service/src/trpc/router/usage/opencode-quota.ts index 3a3a37ce709..49c298c9bc7 100644 --- a/packages/host-service/src/trpc/router/usage/opencode-quota.ts +++ b/packages/host-service/src/trpc/router/usage/opencode-quota.ts @@ -8,8 +8,8 @@ import { readFile } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; -import { fetchClaudeSubscriptionQuota } from "./claude"; -import { fetchCodexSubscriptionQuota } from "./codex"; +import { getCredentialQuota } from "./claude"; +import { getCodexCredentialQuota } from "./codex"; import { opencodeDataDir } from "./history/opencode"; import type { UsageAccount, UsageAccountCredentialKind } from "./types"; @@ -100,6 +100,7 @@ export function opencodeAuthPath(dataDir: string = opencodeDataDir()): string { async function fetchOpencodeAccount( login: OpencodeLogin, authPath: string, + forceRefresh: boolean, ): Promise { const dataDir = join(authPath, "..").replace(homedir(), "~"); const base = { @@ -137,7 +138,18 @@ async function fetchOpencodeAccount( } if (login.provider === "anthropic") { - const quota = await fetchClaudeSubscriptionQuota(login.accessToken); + const quota = await getCredentialQuota( + { + accessToken: login.accessToken, + expiresAt: null, + refreshTokenExpiresAt: null, + subscriptionType: null, + accountKey: base.accountKey, + sourceLabel: base.sourceLabel, + selection: base.accountKey, + }, + forceRefresh, + ); return { ...base, ...quota, @@ -147,9 +159,11 @@ async function fetchOpencodeAccount( : quota.statusDetail, }; } - const quota = await fetchCodexSubscriptionQuota( + const quota = await getCodexCredentialQuota( login.accessToken, login.accountId ?? undefined, + base.accountKey, + forceRefresh, ); return { ...base, @@ -163,6 +177,7 @@ async function fetchOpencodeAccount( export async function fetchOpencodeAccounts( authPath: string = opencodeAuthPath(), + forceRefresh = false, ): Promise { let raw: string; try { @@ -172,7 +187,7 @@ export async function fetchOpencodeAccounts( } return Promise.all( parseOpencodeLogins(raw).map((login) => - fetchOpencodeAccount(login, authPath), + fetchOpencodeAccount(login, authPath, forceRefresh), ), ); } diff --git a/packages/host-service/src/trpc/router/usage/profile-file.test.ts b/packages/host-service/src/trpc/router/usage/profile-file.test.ts new file mode 100644 index 00000000000..3a4efc2ee43 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/profile-file.test.ts @@ -0,0 +1,45 @@ +import { afterEach, expect, test } from "bun:test"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readProfileFile } from "./profile-file"; +import { API_BILLING_MARKER, readCodexProfileKind } from "./profiles"; +import { readAccountIdentity } from "./session-account/session-account"; + +const directories: string[] = []; +async function fixture() { + const dir = await mkdtemp(join(tmpdir(), "superset-profile-file-")); + directories.push(dir); + return dir; +} +afterEach(async () => { + await Promise.all( + directories + .splice(0) + .map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); + +test("reads regular profile metadata within the byte limit", async () => { + const dir = await fixture(); + const path = join(dir, "state"); + await writeFile(path, "four"); + expect(await readProfileFile(path, 4)).toMatchObject({ content: "four" }); + expect(await readProfileFile(path, 3)).toBeNull(); + expect(await readProfileFile(dir, 64)).toBeNull(); + expect(await readProfileFile(join(dir, "missing"), 64)).toBeNull(); +}); + +test.skipIf(process.platform === "win32")( + "profile discovery and identity reads reject FIFOs without a writer", + async () => { + const dir = await fixture(); + for (const name of ["auth.json", ".claude.json", API_BILLING_MARKER]) { + execFileSync("mkfifo", [join(dir, name)]); + } + expect(await readCodexProfileKind(dir)).toBeNull(); + expect(await readAccountIdentity("codex", dir)).toBeNull(); + expect(await readAccountIdentity("claude", dir)).toBeNull(); + }, +); diff --git a/packages/host-service/src/trpc/router/usage/profile-file.ts b/packages/host-service/src/trpc/router/usage/profile-file.ts new file mode 100644 index 00000000000..289cf4a5271 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/profile-file.ts @@ -0,0 +1,38 @@ +import { constants } from "node:fs"; +import { type FileHandle, open } from "node:fs/promises"; + +/** Read bounded metadata from one regular file, without waiting on a FIFO. */ +export async function readProfileFile( + path: string, + maxBytes: number, +): Promise<{ content: string; mtimeMs: number } | null> { + let file: FileHandle | undefined; + try { + file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK); + const info = await file.stat(); + if (!info.isFile() || info.size > maxBytes) return null; + // The extra byte detects a file growing between stat and read. Keep the + // original descriptor so a path replacement cannot introduce a pipe. + const buffer = Buffer.alloc(info.size + 1); + let total = 0; + while (total < buffer.length) { + const { bytesRead } = await file.read( + buffer, + total, + buffer.length - total, + total, + ); + if (bytesRead === 0) break; + total += bytesRead; + } + if (total > info.size) return null; + return { + content: buffer.toString("utf8", 0, total), + mtimeMs: info.mtimeMs, + }; + } catch { + return null; + } finally { + await file?.close(); + } +} diff --git a/packages/host-service/src/trpc/router/usage/profiles.test.ts b/packages/host-service/src/trpc/router/usage/profiles.test.ts index c10eba510f2..a3a5bed3e27 100644 --- a/packages/host-service/src/trpc/router/usage/profiles.test.ts +++ b/packages/host-service/src/trpc/router/usage/profiles.test.ts @@ -8,10 +8,12 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { captureCodexQuotaSnapshot } from "./codex"; import { API_BILLING_MARKER, claudeKeychainAccounts, discoverClaudeProfiles, + discoverCodexHomes, readCodexProfileKind, } from "./profiles"; @@ -158,3 +160,50 @@ describe("discoverClaudeProfiles", () => { }); }); }); + +describe("quota-only Codex discovery", () => { + it("retains broken secondary auth as unavailable without making it selectable", async () => { + const base = tempProfile(); + const malformed = tempProfile(); + writeFileSync(join(malformed, "auth.json"), "{"); + const unreadable = tempProfile(); + mkdirSync(join(unreadable, "auth.json")); + const api = tempProfile(); + writeFileSync( + join(api, "auth.json"), + JSON.stringify({ OPENAI_API_KEY: "synthetic-api" }), + ); + const empty = tempProfile(); + const options = { + defaultHome: base, + candidates: [malformed, unreadable, api, empty], + }; + expect( + (await discoverCodexHomes(options)).map((profile) => profile.home), + ).toEqual([base]); + const homes = await discoverCodexHomes({ + ...options, + includeUnavailable: true, + }); + expect(homes.map((profile) => profile.home)).toEqual([ + base, + malformed, + unreadable, + ]); + let fetches = 0; + const snapshot = await captureCodexQuotaSnapshot( + async () => homes, + async () => { + fetches++; + throw new Error("must not fetch unreadable auth"); + }, + ); + const cards = await snapshot.load(); + expect( + cards + .filter((card) => card.status === "unavailable") + .map((card) => card.selection), + ).toEqual([malformed, unreadable]); + expect(fetches).toBe(0); + }); +}); diff --git a/packages/host-service/src/trpc/router/usage/profiles.ts b/packages/host-service/src/trpc/router/usage/profiles.ts index a7c19384a54..8dc8d9b3c48 100644 --- a/packages/host-service/src/trpc/router/usage/profiles.ts +++ b/packages/host-service/src/trpc/router/usage/profiles.ts @@ -23,11 +23,18 @@ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; -import { readdir, readFile, stat } from "node:fs/promises"; +import { readdir } from "node:fs/promises"; import { homedir, platform, userInfo } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; import { resolveAmbientCodexHome } from "@superset/agent-setup"; +import { assertCodexFileCredentialStore } from "./codex-quota-config"; +import { readProfileFile } from "./profile-file"; +import { + parseQuotaCredentialJson, + QuotaCredentialReadError, + readQuotaCredentialFile, +} from "./quota-credentials"; const execFileAsync = promisify(execFile); @@ -61,6 +68,8 @@ export interface ClaudeProfile { } export interface CodexHome { + /** Quota-only discovery retains an unreadable profile; never selectable. */ + quotaUnavailable?: true; home: string; sourceLabel: string; credentialKind: ProfileCredentialKind; @@ -123,11 +132,9 @@ async function readClaudeIdentity( ): Promise<{ email: string | null } | null> { const statePath = join(configDir, ".claude.json"); try { - const info = await stat(statePath); - if (!info.isFile() || info.size > MAX_STATE_FILE_BYTES) return null; - const parsed: ClaudeStateFile = JSON.parse( - await readFile(statePath, "utf-8"), - ); + const file = await readProfileFile(statePath, MAX_STATE_FILE_BYTES); + if (!file) return null; + const parsed: ClaudeStateFile = JSON.parse(file.content); const account = parsed.oauthAccount; if (!account?.accountUuid && !account?.emailAddress) return null; return { email: account.emailAddress ?? null }; @@ -143,10 +150,8 @@ export async function readApiBillingFingerprint( ): Promise { const markerPath = join(profileDir, API_BILLING_MARKER); try { - const info = await stat(markerPath); - if (!info.isFile() || info.size > MAX_MARKER_BYTES) return null; - const content = (await readFile(markerPath, "utf-8")).trim(); - return content === agent ? `${info.mtimeMs}` : null; + const file = await readProfileFile(markerPath, MAX_MARKER_BYTES); + return file?.content.trim() === agent ? `${file.mtimeMs}` : null; } catch { return null; } @@ -229,23 +234,57 @@ export function claudeKeychainAccounts( * accounts are probed first; the unscoped lookup then covers items an older * client filed under a different name. */ -export async function readKeychainSecrets(service: string): Promise { +export async function readKeychainSecrets( + service: string, + strict = false, +): Promise { if (platform() !== "darwin") return []; - const secrets: string[] = []; const scopes = [ ...claudeKeychainAccounts().map((account) => ["-a", account]), [], ]; - for (const scope of scopes) { - try { + return collectKeychainSecrets( + scopes, + async (scope) => { const { stdout } = await execFileAsync( "security", ["find-generic-password", ...scope, "-s", service, "-w"], - { timeout: 5_000 }, + { timeout: strict ? 750 : 5_000, maxBuffer: 1024 * 1024 }, ); - const secret = stdout.trim(); + return stdout; + }, + strict, + ); +} + +export async function collectKeychainSecrets( + scopes: string[][], + read: (scope: string[]) => Promise, + strict: boolean, +): Promise { + if (strict) { + const groups = await Promise.all( + scopes.map((scope) => + read(scope).then( + (value) => (value.trim() ? [value.trim()] : []), + (error: unknown) => { + if ((error as { code?: unknown }).code === 44) return []; + throw new QuotaCredentialReadError(); + }, + ), + ), + ); + return [...new Set(groups.flat())]; + } + const secrets: string[] = []; + for (const scope of scopes) { + try { + const secret = (await read(scope)).trim(); if (secret && !secrets.includes(secret)) secrets.push(secret); - } catch { + } catch (error) { + if (strict && (error as { code?: unknown }).code !== 44) { + throw new QuotaCredentialReadError(); + } // No item under this scope. } } @@ -269,9 +308,12 @@ export async function readCodexProfileKind( return { credentialKind: "api_key", loginFingerprint: apiFingerprint }; } try { - const parsed: CodexAuthShape = JSON.parse( - await readFile(join(codexHome, "auth.json"), "utf-8"), + const file = await readProfileFile( + join(codexHome, "auth.json"), + MAX_STATE_FILE_BYTES, ); + if (!file) return null; + const parsed: CodexAuthShape = JSON.parse(file.content); return parsed.tokens?.access_token ? { credentialKind: "subscription", loginFingerprint: null } : null; @@ -281,6 +323,36 @@ export async function readCodexProfileKind( } } +async function readCodexQuotaProfileKind( + codexHome: string, +): Promise | null> { + const apiFingerprint = await readApiBillingFingerprint(codexHome, "codex"); + if (apiFingerprint) + return { credentialKind: "api_key", loginFingerprint: apiFingerprint }; + try { + await assertCodexFileCredentialStore(codexHome); + const file = await readQuotaCredentialFile(join(codexHome, "auth.json")); + if (!file) return null; + const parsed = parseQuotaCredentialJson(file); + if (parsed.tokens === undefined || parsed.tokens === null) return null; + if (typeof parsed.tokens !== "object" || Array.isArray(parsed.tokens)) + throw new QuotaCredentialReadError(); + const token = (parsed.tokens as Record).access_token; + if (typeof token !== "string" || !token.trim()) + throw new QuotaCredentialReadError(); + return { credentialKind: "subscription", loginFingerprint: null }; + } catch { + return { + credentialKind: "subscription", + loginFingerprint: null, + quotaUnavailable: true, + }; + } +} + /** * Codex homes: the ambient home (`~/.codex`, or a `CODEX_HOME` the user set * themselves — see resolveAmbientCodexHome for why Superset's own injected @@ -292,10 +364,18 @@ export async function readCodexProfileKind( * `selection: null`. It is listed even without an `auth.json` so the * add-account poller has a baseline to compare a fresh `codex login` against. */ -export async function discoverCodexHomes(): Promise { +export async function discoverCodexHomes( + options: { + includeUnavailable?: boolean; + candidates?: readonly string[]; + defaultHome?: string; + } = {}, +): Promise { const home = homedir(); - const defaultHome = resolveAmbientCodexHome(home); - const defaultKind = (await readCodexProfileKind(defaultHome)) ?? { + const defaultHome = options.defaultHome ?? resolveAmbientCodexHome(home); + const defaultKind = (await (options.includeUnavailable + ? readCodexQuotaProfileKind(defaultHome) + : readCodexProfileKind(defaultHome))) ?? { credentialKind: "subscription" as const, loginFingerprint: null, }; @@ -310,12 +390,16 @@ export async function discoverCodexHomes(): Promise { ], ]); - const candidates = (await listSubdirectories(home)).filter((path) => - path.slice(home.length + 1).startsWith(".codex"), - ); + const candidates = + options.candidates ?? + (await listSubdirectories(home)).filter((path) => + path.slice(home.length + 1).startsWith(".codex"), + ); for (const candidate of candidates) { if (homes.has(candidate)) continue; - const kind = await readCodexProfileKind(candidate); + const kind = await (options.includeUnavailable + ? readCodexQuotaProfileKind(candidate) + : readCodexProfileKind(candidate)); if (!kind) continue; homes.set(candidate, { home: candidate, diff --git a/packages/host-service/src/trpc/router/usage/quota-backoff.test.ts b/packages/host-service/src/trpc/router/usage/quota-backoff.test.ts new file mode 100644 index 00000000000..4884c6b20a4 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-backoff.test.ts @@ -0,0 +1,50 @@ +import { expect, test } from "bun:test"; +import { + copyQuotaRetry, + quotaRetryDelay, + readQuotaRetry, + readQuotaRetryHint, + recordQuotaRetry, +} from "./quota-backoff"; + +test("Retry-After accepts HTTP dates and integer seconds with bounded invalid input", () => { + const now = Date.UTC(2026, 9, 14); + expect(quotaRetryDelay("120", now)).toBe(120_000); + expect(quotaRetryDelay(new Date(now + 300_000).toUTCString(), now)).toBe( + 300_000, + ); + for (const value of [null, "nonsense", "-1", "1.5", "9".repeat(400)]) + expect(quotaRetryDelay(value, now)).toBe(0); + expect(quotaRetryDelay("9999999999", now)).toBe(24 * 60 * 60_000); +}); +test("rate limits get a minimum five-minute pause while ordinary authorization errors do not", () => { + expect( + readQuotaRetry(recordQuotaRetry({}, new Response("", { status: 429 }))), + ).toBe(300_000); + expect( + readQuotaRetry(recordQuotaRetry({}, new Response("", { status: 401 }))), + ).toBe(0); +}); + +test("transient provider failures get a private retry hint but authentication rejection does not", () => { + for (const status of [408, 500, 502, 503, 504, 529]) { + const value = recordQuotaRetry({}, new Response("", { status })); + expect(readQuotaRetry(value)).toBe(30_000); + expect(readQuotaRetryHint(value)?.kind).toBe("transient"); + expect(JSON.stringify(value)).toBe("{}"); + } + for (const status of [400, 401, 403, 404]) + expect( + readQuotaRetry(recordQuotaRetry({}, new Response("", { status }))), + ).toBe(0); +}); + +test("copying or reusing a response cannot retain an unrelated previous retry hint", () => { + const limited = recordQuotaRetry({}, new Response("", { status: 429 })); + const target = copyQuotaRetry(limited, {}); + expect(readQuotaRetryHint(target)).toBe(readQuotaRetryHint(limited)); + copyQuotaRetry({}, target); + expect(readQuotaRetry(target)).toBe(0); + recordQuotaRetry(limited, new Response("", { status: 200 })); + expect(readQuotaRetry(limited)).toBe(0); +}); diff --git a/packages/host-service/src/trpc/router/usage/quota-backoff.ts b/packages/host-service/src/trpc/router/usage/quota-backoff.ts new file mode 100644 index 00000000000..76a170350b9 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-backoff.ts @@ -0,0 +1,66 @@ +// Retry hints stay private. They are cache policy, not public account metadata. +type QuotaRetryHint = { + delayMs: number; + kind: "rate_limit" | "transient"; + retryAt?: number; +}; +const retryHints = new WeakMap(); +const responseRetries = new WeakMap(); +export function setQuotaResponseRetry( + response: T, + retryAt: number, +): T { + responseRetries.set(response, retryAt); + return response; +} +const MAX_RETRY_DELAY_MS = 24 * 60 * 60_000; + +export function quotaRetryDelay( + header: string | null, + now = Date.now(), +): number { + if (!header) return 0; + const text = header.trim(); + if (!/^\d+$/.test(text) && !/^[A-Za-z]{3}/.test(text)) return 0; + const delay = /^\d+$/.test(text) + ? Number(text) * 1000 + : Date.parse(text) - now; + return Number.isFinite(delay) + ? Math.min(MAX_RETRY_DELAY_MS, Math.max(0, delay)) + : 0; +} + +export function recordQuotaRetry( + value: T, + response: Pick, +): T { + retryHints.delete(value); + if ([408, 429, 500, 502, 503, 504, 529].includes(response.status)) { + retryHints.set(value, { + kind: response.status === 429 ? "rate_limit" : "transient", + retryAt: responseRetries.get(response), + delayMs: Math.max( + response.status === 429 ? 5 * 60_000 : 30_000, + quotaRetryDelay(response.headers?.get("retry-after") ?? null), + ), + }); + } + return value; +} + +export function copyQuotaRetry(source: object, target: T): T { + const hint = retryHints.get(source); + retryHints.delete(target); + if (hint) retryHints.set(target, hint); + return target; +} + +export function readQuotaRetry(value: object): number { + return retryHints.get(value)?.delayMs ?? 0; +} + +export function readQuotaRetryHint( + value: object, +): Readonly | undefined { + return retryHints.get(value); +} diff --git a/packages/host-service/src/trpc/router/usage/quota-cache.test.ts b/packages/host-service/src/trpc/router/usage/quota-cache.test.ts new file mode 100644 index 00000000000..9e9a69f5940 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-cache.test.ts @@ -0,0 +1,291 @@ +import { expect, test } from "bun:test"; +import { createQuotaCache } from "./quota-cache"; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +} + +test("same-slot rotation invalidates a valid five-minute cache", async () => { + let account = "A"; + let loads = 0; + let clock = 0; + const cache = createQuotaCache( + async () => { + const captured = account; + return { + revision: captured, + load: async () => { + loads++; + return captured; + }, + }; + }, + 300_000, + () => clock, + ); + expect(await cache.get()).toBe("A"); + clock = 1; + expect(await cache.get()).toBe("A"); + expect(loads).toBe(1); + account = "B"; + expect(await cache.get()).toBe("B"); + expect(loads).toBe(2); + clock = 300_001; + expect(await cache.get()).toBe("B"); + expect(loads).toBe(3); +}); + +test("normal and forced callers coalesce the same credential revision", async () => { + const ready = deferred(); + const response = deferred(); + let loads = 0; + const cache = createQuotaCache( + async () => ({ + revision: "A", + load: () => { + loads++; + ready.resolve(); + return response.promise; + }, + }), + 300_000, + ); + const first = cache.get(); + await ready.promise; + const second = cache.get(true); + const third = cache.get(); + response.resolve("A"); + expect(await Promise.all([first, second, third])).toEqual(["A", "A", "A"]); + expect(loads).toBe(1); +}); + +test("late A is rejected for its caller and cannot replace a completed B", async () => { + let account = "A"; + const ready = deferred(); + const response = deferred(); + const cache = createQuotaCache(async () => { + const captured = account; + return { + revision: captured, + load: () => { + if (captured === "A") { + ready.resolve(); + return response.promise; + } + return Promise.resolve(captured); + }, + }; + }, 300_000); + const old = cache.get().catch((error: Error) => error.message); + await ready.promise; + account = "B"; + expect(await cache.get(true)).toBe("B"); + response.resolve("A"); + expect(await old).toContain("changed during"); + expect(await cache.get()).toBe("B"); +}); + +test("rotation during an unobserved request refuses its result", async () => { + let account = "A"; + const ready = deferred(); + const response = deferred(); + const cache = createQuotaCache( + async () => ({ + revision: account, + load: () => { + ready.resolve(); + return response.promise; + }, + }), + 300_000, + ); + const old = cache.get().catch((error: Error) => error.message); + await ready.promise; + account = "B"; + response.resolve("A"); + expect(await old).toContain("changed during"); +}); + +test("A to B to A cannot read B through an earlier captured A snapshot", async () => { + let account = "A"; + const ready = deferred(); + const continueLoad = deferred(); + const loaded: string[] = []; + const cache = createQuotaCache(async () => { + const captured = account; + return { + revision: captured, + load: async () => { + ready.resolve(); + await continueLoad.promise; + loaded.push(captured); + return captured; + }, + }; + }, 300_000); + const result = cache.get(); + await ready.promise; + account = "B"; + continueLoad.resolve(); + account = "A"; + expect(await result).toBe("A"); + expect(loaded).toEqual(["A"]); +}); + +test("unreadable credentials evict quota and never reveal the reader error", async () => { + let unavailable = false; + let loads = 0; + const cache = createQuotaCache(async () => { + if (unavailable) throw new Error("synthetic-secret-must-not-escape"); + return { revision: "A", load: async () => ++loads }; + }, 300_000); + expect(await cache.get()).toBe(1); + unavailable = true; + await expect(cache.get()).rejects.toThrow( + "Quota credentials could not be verified. Try again.", + ); + unavailable = false; + expect(await cache.get()).toBe(2); +}); + +test("an observed A to B to A change does not revive the first A request", async () => { + let account = "A"; + let firstA = true; + const ready = deferred(); + const response = deferred(); + const cache = createQuotaCache(async () => { + const captured = account; + return { + revision: captured, + load: async () => { + if (captured === "A" && firstA) { + firstA = false; + ready.resolve(); + return response.promise; + } + return `${captured}-new`; + }, + }; + }, 300_000); + const old = cache.get().catch((error: Error) => error.message); + await ready.promise; + account = "B"; + expect(await cache.get()).toBe("B-new"); + account = "A"; + expect(await cache.get()).toBe("A-new"); + response.resolve("A-old"); + expect(await old).toContain("changed during"); + expect(await cache.get()).toBe("A-new"); +}); + +test("a response is refused if credentials become unreadable while it is pending", async () => { + let unavailable = false; + const ready = deferred(); + const response = deferred(); + const cache = createQuotaCache(async () => { + if (unavailable) throw new Error("synthetic read failure"); + return { + revision: "A", + load: () => { + ready.resolve(); + return response.promise; + }, + }; + }, 300_000); + const result = cache.get().catch((error: Error) => error.message); + await ready.promise; + unavailable = true; + response.resolve("A"); + expect(await result).toBe( + "Quota credentials could not be verified. Try again.", + ); +}); + +test("provider failure evicts the earlier cached value and can retry", async () => { + let fail = false; + let loads = 0; + const cache = createQuotaCache( + async () => ({ + revision: "A", + load: async () => { + loads++; + if (fail) throw new Error("offline"); + return loads; + }, + }), + 300_000, + ); + expect(await cache.get()).toBe(1); + fail = true; + await expect(cache.get(true)).rejects.toThrow("offline"); + fail = false; + expect(await cache.get()).toBe(3); +}); + +test("explicit invalidation refuses an earlier pending request", async () => { + const ready = deferred(); + const response = deferred(); + const cache = createQuotaCache( + async () => ({ + revision: "A", + load: () => { + ready.resolve(); + return response.promise; + }, + }), + 300_000, + ); + const result = cache.get().catch((error: Error) => error.message); + await ready.promise; + cache.invalidate(); + response.resolve("A"); + expect(await result).toContain("changed during"); +}); + +test("background completion expires a placeholder without invalidating credential authority", async () => { + let loads = 0; + const cache = createQuotaCache( + async () => ({ + revision: "unchanged-owner", + load: async () => ++loads, + }), + 300_000, + () => 1000, + ); + expect(await cache.get()).toBe(1); + cache.expire(); + expect(await cache.get()).toBe(2); +}); + +test("completion during a pending placeholder load cannot make that placeholder fresh", async () => { + let loads = 0; + let release!: () => void; + const pending = new Promise((resolve) => { + release = resolve; + }); + const cache = createQuotaCache( + async () => ({ + revision: "unchanged-owner", + load: async () => { + const result = ++loads; + if (result === 1) await pending; + return result; + }, + }), + 300_000, + () => 1000, + { isFailure: () => true }, + ); + const first = cache.get(); + for (let tick = 0; tick < 20 && loads === 0; tick++) await Promise.resolve(); + cache.expire(); + release(); + expect(await first).toBe(1); + expect(await cache.get()).toBe(2); +}); diff --git a/packages/host-service/src/trpc/router/usage/quota-cache.ts b/packages/host-service/src/trpc/router/usage/quota-cache.ts new file mode 100644 index 00000000000..9e2013e3499 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-cache.ts @@ -0,0 +1,162 @@ +import { + createQuotaRequestBudget, + QUOTA_CAPTURE_BUDGET_MS, +} from "./quota-request"; +export interface QuotaSnapshot { + revision: string; + load: (forceRefresh?: boolean) => Promise; +} + +export function createQuotaCache( + capture: () => Promise>, + ttlMs: number, + now = Date.now, + options: { + forceCooldownMs?: number; + retryOnFailure?: boolean; + isFailure?: (value: T) => boolean; + retryDelay?: (value: T) => number; + freshUntil?: (value: T) => number; + } = {}, +) { + let generation = 0; + let freshnessGeneration = 0; + let lastAttempt = Number.NEGATIVE_INFINITY; + let retryAt = 0; + let failures = 0; + let lastError: Error | undefined; + let revision: string | undefined; + let cached: { value: T; fetchedAt: number; freshUntil: number } | undefined; + let pending: Promise | undefined; + let reading: Promise = Promise.resolve(); + let checking: Promise> | undefined; + + function invalidate() { + generation++; + cached = undefined; + pending = undefined; + retryAt = 0; + lastError = undefined; + } + + function inspect() { + const result = reading + .then(() => + createQuotaRequestBudget(QUOTA_CAPTURE_BUDGET_MS).run(() => capture()), + ) + .then( + (snapshot) => { + if (snapshot.revision !== revision) { + invalidate(); + revision = snapshot.revision; + } + return snapshot; + }, + () => { + invalidate(); + lastError = new Error( + "Quota credentials could not be verified. Try again.", + ); + failures = options.retryOnFailure ? failures + 1 : 0; + retryAt = + now() + + (failures + ? Math.min(ttlMs, 30_000 * 2 ** Math.min(failures - 1, 4)) + : 0); + throw lastError; + }, + ); + reading = result.catch(() => {}); + return result; + } + + return { + async get(forceRefresh = false): Promise { + if (lastError && now() < retryAt) throw lastError; + if (!checking) { + const check = inspect().finally(() => { + if (checking === check) checking = undefined; + }); + checking = check; + } + const snapshot = await checking; + if (pending) return pending; + if ( + cached && + (now() < retryAt || + (forceRefresh + ? now() - lastAttempt < (options.forceCooldownMs ?? 0) + : now() < cached.freshUntil)) + ) { + return cached.value; + } + const requestGeneration = generation; + const requestFreshness = freshnessGeneration; + lastAttempt = now(); + const request = Promise.resolve() + .then(() => + createQuotaRequestBudget(9_000).run(() => + snapshot.load(forceRefresh), + ), + ) + .then(async (value) => { + const current = await inspect(); + if ( + generation !== requestGeneration || + current.revision !== snapshot.revision + ) { + throw new Error( + "Quota credentials changed during the request. Try again.", + ); + } + cached = { + value, + fetchedAt: now(), + freshUntil: + requestFreshness === freshnessGeneration + ? (options.freshUntil?.(value) ?? now() + ttlMs) + : Number.NEGATIVE_INFINITY, + }; + lastError = undefined; + failures = options.isFailure?.(value) ? failures + 1 : 0; + retryAt = + now() + + Math.max( + options.retryDelay?.(value) ?? 0, + failures + ? Math.min(ttlMs, 30_000 * 2 ** Math.min(failures - 1, 4)) + : 0, + ); + if (requestFreshness !== freshnessGeneration) retryAt = 0; + return value; + }) + .catch((error: unknown) => { + if (generation === requestGeneration) { + cached = undefined; + lastError = new Error( + "Quota could not be verified. Try again shortly.", + ); + failures = options.retryOnFailure ? failures + 1 : 0; + retryAt = + now() + + (failures + ? Math.min(ttlMs, 30_000 * 2 ** Math.min(failures - 1, 4)) + : 0); + } + throw error; + }) + .finally(() => { + if (pending === request) pending = undefined; + }); + pending = request; + return request; + }, + expire() { + freshnessGeneration++; + if (cached) cached.freshUntil = Number.NEGATIVE_INFINITY; + retryAt = 0; + lastError = undefined; + }, + invalidate, + }; +} diff --git a/packages/host-service/src/trpc/router/usage/quota-cooldown-store.ts b/packages/host-service/src/trpc/router/usage/quota-cooldown-store.ts new file mode 100644 index 00000000000..ddd75fe5ff2 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-cooldown-store.ts @@ -0,0 +1,160 @@ +import { createHash, randomUUID } from "node:crypto"; +import { + closeSync, + constants, + fstatSync, + lstatSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +export type QuotaEndpoint = "usage" | "profile" | "wallet"; +export interface QuotaCooldown { + key: string; + kind: "rate_limit" | "transient"; + status: number; + failures: number; + retryAt: number; + updatedAt: number; +} +export const hashQuotaScope = (value: unknown) => + createHash("sha256").update(JSON.stringify(value)).digest("hex"); +const MAX_RECORDS = 1024; +const MAX_BYTES = 512 * 1024; +const MAX_AGE_MS = 7 * 24 * 60 * 60_000; + +export function createQuotaCooldownStore( + path?: string, + now = () => Date.now(), +) { + let loaded = false; + const entries = new Map(); + function load() { + if (loaded) return; + loaded = true; + if (!path) return; + try { + const fd = openSync( + path, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + let contents: string; + try { + const info = fstatSync(fd); + if ( + !info.isFile() || + info.nlink !== 1 || + info.size > MAX_BYTES || + (process.platform !== "win32" && + ((info.mode & 0o077) !== 0 || info.uid !== process.getuid?.())) + ) + return; + contents = readFileSync(fd, "utf8"); + if (Buffer.byteLength(contents) > MAX_BYTES) return; + } finally { + closeSync(fd); + } + const state: unknown = JSON.parse(contents); + if ( + !state || + typeof state !== "object" || + !("version" in state) || + state.version !== 1 || + !("entries" in state) || + !Array.isArray(state.entries) || + state.entries.length > MAX_RECORDS + ) + return; + for (const value of state.entries) { + if ( + !value || + typeof value !== "object" || + !/^[a-f0-9]{64}$/.test(value.key) || + !["rate_limit", "transient"].includes(value.kind) || + ![408, 429, 500, 502, 503, 504, 529].includes(value.status) || + !Number.isInteger(value.failures) || + value.failures < 1 || + value.failures > 8 || + !Number.isFinite(value.retryAt) || + !Number.isFinite(value.updatedAt) || + value.updatedAt < now() - MAX_AGE_MS || + value.updatedAt > now() + 60_000 || + value.retryAt > value.updatedAt + 24 * 60 * 60_000 + ) + continue; + entries.set(value.key, value); + } + } catch { + /* Invalid retry metadata never supplies identity or quota authority. */ + } + } + function persist() { + if (!path) return; + const directory = dirname(path); + let temporary: string | undefined; + try { + mkdirSync(directory, { recursive: true, mode: 0o700 }); + const info = lstatSync(directory); + if ( + !info.isDirectory() || + info.isSymbolicLink() || + (process.platform !== "win32" && + (info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0)) + ) + return; + temporary = `${path}.${randomUUID()}.tmp`; + writeFileSync( + temporary, + JSON.stringify({ version: 1, entries: [...entries.values()] }), + { flag: "wx", mode: 0o600 }, + ); + renameSync(temporary, path); + } catch { + /* In-memory cooldowns remain authoritative if storage is unavailable. */ + } finally { + if (temporary) { + try { + unlinkSync(temporary); + } catch {} + } + } + } + return { + get(key: string) { + load(); + return entries.get(key); + }, + set(value: QuotaCooldown) { + load(); + if (!/^[a-f0-9]{64}$/.test(value.key)) + throw new Error("Invalid quota scope."); + if (!entries.has(value.key) && entries.size >= MAX_RECORDS) { + const disposable = [...entries.values()] + .filter((entry) => entry.retryAt <= now()) + .sort((a, b) => a.updatedAt - b.updatedAt)[0]; + if (!disposable) throw new Error("Usage retry storage is busy."); + entries.delete(disposable.key); + } + entries.set(value.key, { ...value }); + persist(); + }, + clear(key: string) { + load(); + if (entries.delete(key)) persist(); + }, + }; +} + +export const quotaCooldownStore = createQuotaCooldownStore( + join( + process.env.SUPERSET_HOME_DIR?.trim() || join(homedir(), ".superset"), + "state", + "usage-cooldowns.json", + ), +); diff --git a/packages/host-service/src/trpc/router/usage/quota-credentials.test.ts b/packages/host-service/src/trpc/router/usage/quota-credentials.test.ts new file mode 100644 index 00000000000..0cef3459d94 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-credentials.test.ts @@ -0,0 +1,127 @@ +import { afterEach, expect, test } from "bun:test"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { collectKeychainSecrets } from "./profiles"; +import { + parseQuotaCredentialJson, + readQuotaCredentialFile, + unavailableQuotaAccount, +} from "./quota-credentials"; + +const directories: string[] = []; +afterEach(async () => { + await Promise.all( + directories + .splice(0) + .map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); +async function directory() { + const dir = await mkdtemp(join(tmpdir(), "superset-quota-credentials-")); + directories.push(dir); + return dir; +} + +test("unavailable quota rows discard credential and private runtime fields", () => { + const credential = { + agent: "claude" as const, + accountKey: "fixture-account", + sourceLabel: "Fixture profile", + selection: "/fixture/profile", + accessToken: "synthetic-credential-secret", + expiresAt: 123, + refreshTokenExpiresAt: 456, + hasRefreshToken: true, + subscriptionType: "max", + privateExtension: "synthetic-private-extension", + }; + const row = unavailableQuotaAccount(credential); + expect(row).toMatchObject({ + agent: "claude", + accountKey: credential.accountKey, + sourceLabel: credential.sourceLabel, + selection: credential.selection, + status: "unavailable", + email: null, + }); + for (const key of [ + "accessToken", + "expiresAt", + "refreshTokenExpiresAt", + "hasRefreshToken", + "subscriptionType", + "privateExtension", + ]) + expect(row).not.toHaveProperty(key); + expect(JSON.stringify(row)).not.toContain("synthetic-credential-secret"); + expect(JSON.stringify(row)).not.toContain("synthetic-private-extension"); +}); + +test("missing credential files differ from unreadable paths", async () => { + const dir = await directory(); + expect(await readQuotaCredentialFile(join(dir, "absent"))).toBeNull(); + await writeFile(join(dir, "not-directory"), "synthetic"); + await expect( + readQuotaCredentialFile(join(dir, "not-directory", "child")), + ).rejects.toThrow("Quota credentials could not be verified."); +}); + +test("quota reads refuse non-regular, oversized and invalid UTF-8 data", async () => { + const dir = await directory(); + await expect(readQuotaCredentialFile(dir)).rejects.toThrow( + "could not be verified", + ); + const path = join(dir, "credentials"); + await writeFile(path, "five!"); + await expect(readQuotaCredentialFile(path, 4)).rejects.toThrow( + "could not be verified", + ); + await writeFile(path, Buffer.from([0xff])); + await expect(readQuotaCredentialFile(path)).rejects.toThrow( + "could not be verified", + ); + const fifo = join(dir, "fifo"); + execFileSync("mkfifo", [fifo]); + await expect(readQuotaCredentialFile(fifo)).rejects.toThrow( + "could not be verified", + ); +}); + +test("malformed or non-object credential JSON never exposes its contents", () => { + for (const raw of ["synthetic-secret", "null", "[]", '"synthetic-secret"']) { + expect(() => parseQuotaCredentialJson(raw)).toThrow( + "Quota credentials could not be verified.", + ); + } + expect(parseQuotaCredentialJson('{"tokens":{}}')).toEqual({ tokens: {} }); +}); + +test("strict Keychain reads distinguish missing items from permission and timeout failures", async () => { + const missing = async () => { + throw Object.assign(new Error("synthetic"), { code: 44 }); + }; + expect(await collectKeychainSecrets([[]], missing, true)).toEqual([]); + for (const error of [ + Object.assign(new Error("synthetic-secret"), { code: 128 }), + Object.assign(new Error("synthetic-secret"), { killed: true }), + ]) { + await expect( + collectKeychainSecrets( + [[]], + async () => { + throw error; + }, + true, + ), + ).rejects.toThrow("Quota credentials could not be verified."); + } + expect( + await collectKeychainSecrets( + [[], ["-a", "test"]], + async () => "same", + true, + ), + ).toEqual(["same"]); +}); diff --git a/packages/host-service/src/trpc/router/usage/quota-credentials.ts b/packages/host-service/src/trpc/router/usage/quota-credentials.ts new file mode 100644 index 00000000000..53a9f11e754 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-credentials.ts @@ -0,0 +1,92 @@ +import { constants } from "node:fs"; +import { type FileHandle, open } from "node:fs/promises"; +import type { UsageAccount } from "./types"; + +export type UnavailableQuotaSlot = Pick< + UsageAccount, + "agent" | "accountKey" | "sourceLabel" | "selection" +>; + +export function unavailableQuotaAccount( + slot: UnavailableQuotaSlot, +): UsageAccount { + return { + agent: slot.agent, + accountKey: slot.accountKey, + sourceLabel: slot.sourceLabel, + selection: slot.selection, + credentialKind: "subscription", + email: null, + plan: null, + status: "unavailable", + statusDetail: "Quota credentials could not be verified.", + windows: [], + creditsBalance: null, + extraUsage: null, + isDefault: false, + fetchedAt: new Date(), + }; +} + +export class QuotaCredentialReadError extends Error { + constructor() { + super("Quota credentials could not be verified."); + } +} + +export async function readQuotaCredentialFile( + path: string, + maxBytes = 1024 * 1024, +): Promise { + let file: FileHandle | undefined; + try { + file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; + throw new QuotaCredentialReadError(); + } + try { + const before = await file.stat(); + if (!before.isFile() || before.size > maxBytes) { + throw new QuotaCredentialReadError(); + } + const buffer = Buffer.alloc(before.size + 1); + let offset = 0; + while (offset < buffer.length) { + const { bytesRead } = await file.read( + buffer, + offset, + buffer.length - offset, + offset, + ); + if (bytesRead === 0) break; + offset += bytesRead; + } + const after = await file.stat(); + if ( + offset !== before.size || + after.size !== before.size || + after.mtimeMs !== before.mtimeMs || + after.ctimeMs !== before.ctimeMs + ) { + throw new QuotaCredentialReadError(); + } + return new TextDecoder("utf-8", { fatal: true }).decode( + buffer.subarray(0, offset), + ); + } catch { + throw new QuotaCredentialReadError(); + } finally { + await file.close(); + } +} + +export function parseQuotaCredentialJson(raw: string): Record { + try { + const value: unknown = JSON.parse(raw); + if (value && typeof value === "object" && !Array.isArray(value)) { + return value as Record; + } + } catch {} + throw new QuotaCredentialReadError(); +} diff --git a/packages/host-service/src/trpc/router/usage/quota-identity.test.ts b/packages/host-service/src/trpc/router/usage/quota-identity.test.ts new file mode 100644 index 00000000000..b7c72af9388 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-identity.test.ts @@ -0,0 +1,65 @@ +import { expect, test } from "bun:test"; +import { + bindClaudeQuotaIdentity, + copyQuotaIdentity, + verifiedClaudeQuotaOwner, + verifiedClaudeQuotaScope, +} from "./quota-identity"; + +const profile = { + account: { uuid: "11111111-1111-4111-8111-111111111111" }, + organization: { uuid: "22222222-2222-4222-8222-222222222222" }, +}; + +test("opaque owner proof is exact-token, independently dated and rejected after expiry", () => { + const value = bindClaudeQuotaIdentity({}, "fixture-token", profile, 1000); + const scope = verifiedClaudeQuotaScope( + value, + "fixture-token", + "/fixture/profile", + 2000, + ); + expect(scope).toMatch(/^[a-f0-9]{64}$/); + expect( + verifiedClaudeQuotaScope(value, "other-token", "/fixture/profile", 2000), + ).toBeNull(); + expect( + verifiedClaudeQuotaScope(value, "fixture-token", null, 2000), + ).toBeNull(); + expect(verifiedClaudeQuotaOwner(value, 999)).toBeNull(); + expect( + verifiedClaudeQuotaOwner(value, 1000 + 6 * 60 * 60_000 + 1), + ).toBeNull(); + expect( + verifiedClaudeQuotaScope( + value, + "fixture-token", + "/fixture/profile", + 1000 + 6 * 60 * 60_000 + 1, + ), + ).toBeNull(); + const copied = copyQuotaIdentity(value, { fetchedAt: new Date(100_000) }); + expect(verifiedClaudeQuotaOwner(copied, 100_000)?.verifiedAt).toEqual( + new Date(1000), + ); + expect(JSON.stringify(copied)).not.toContain("fixture-token"); +}); + +test("an undated or contradictory authenticated profile cannot mint owner authority", () => { + expect( + verifiedClaudeQuotaOwner( + bindClaudeQuotaIdentity({}, "fixture-token", profile), + 1000, + ), + ).toBeNull(); + const conflicting = { + ...profile, + account_uuid: "33333333-3333-4333-8333-333333333333", + }; + expect( + verifiedClaudeQuotaOwner( + bindClaudeQuotaIdentity({}, "fixture-token", conflicting, 1000), + 1000, + ), + ).toBeNull(); +}); diff --git a/packages/host-service/src/trpc/router/usage/quota-identity.ts b/packages/host-service/src/trpc/router/usage/quota-identity.ts new file mode 100644 index 00000000000..4e59db7a484 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-identity.ts @@ -0,0 +1,211 @@ +import { createHash } from "node:crypto"; +import { realpath } from "node:fs/promises"; +import { isAbsolute } from "node:path"; + +// Proof belongs to the authenticated response, never to a display email or a +// mutable profile slot. Keep it out of RPC serialization and object spreads. +export interface ClaudeQuotaProof { + tokenHash: string; + ownerHash: string; + registrationHash: string | null; + verifiedAt: number; +} +const identities = new WeakMap< + object, + ClaudeQuotaProof & { authenticated: boolean } +>(); +export const CLAUDE_PROOF_MAX_AGE_MS = 6 * 60 * 60_000; +const hash = (value: unknown) => + createHash("sha256").update(JSON.stringify(value)).digest("hex"); + +function record(value: unknown): Record | null { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +function consistentUuid(values: unknown[]): string | null { + const supplied = values.filter( + (value) => value !== undefined && value !== null, + ); + if ( + supplied.length === 0 || + supplied.some( + (value) => + typeof value !== "string" || + !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test( + value, + ), + ) + ) + return null; + const normalized = supplied.map((value) => (value as string).toLowerCase()); + return new Set(normalized).size === 1 ? (normalized[0] ?? null) : null; +} + +export function claudeProfileIdentity( + profile: unknown, +): { principal: string; organization: string } | null { + const root = record(profile); + if (!root) return null; + const account = record(root.account); + const organization = record(root.organization); + if ( + (root.account != null && !account) || + (root.organization != null && !organization) + ) + return null; + const principal = consistentUuid([ + account?.uuid, + root.accountUuid, + root.account_uuid, + ]); + const org = consistentUuid([ + organization?.uuid, + root.organizationUuid, + root.organization_uuid, + ]); + return principal && org ? { principal, organization: org } : null; +} + +/** Exact public SessionAccount tuple: the absent Claude subject serializes as null. */ +export function claudeProfileRegistration(profile: unknown): string | null { + const identity = claudeProfileIdentity(profile); + const root = record(profile); + const account = record(root?.account); + if (!identity || !root) return null; + const ids = [account?.uuid, root.accountUuid, root.account_uuid].filter( + (value) => value != null, + ); + const emails = [ + account?.email, + account?.email_address, + account?.emailAddress, + root.email, + ].filter((value) => value != null); + if ( + ids.length === 0 || + new Set(ids).size !== 1 || + emails.length === 0 || + emails.some((value) => typeof value !== "string" || !value.trim()) || + new Set(emails).size !== 1 + ) + return null; + return hash([ids[0], undefined, emails[0]]); +} + +export function claudeQuotaProof( + accessToken: string, + profile: unknown, + verifiedAt: number, +): ClaudeQuotaProof | null { + const identity = claudeProfileIdentity(profile); + return identity && accessToken.trim() && Number.isFinite(verifiedAt) + ? { + tokenHash: hash(accessToken), + ownerHash: hash([identity.principal, identity.organization]), + registrationHash: claudeProfileRegistration(profile), + verifiedAt, + } + : null; +} + +export function validClaudeQuotaProof( + proof: ClaudeQuotaProof, + now: number, +): boolean { + return ( + /^[a-f0-9]{64}$/.test(proof.tokenHash) && + /^[a-f0-9]{64}$/.test(proof.ownerHash) && + (proof.registrationHash === null || + /^[a-f0-9]{64}$/.test(proof.registrationHash)) && + Number.isFinite(proof.verifiedAt) && + proof.verifiedAt <= now && + now - proof.verifiedAt <= CLAUDE_PROOF_MAX_AGE_MS + ); +} + +/** Only call with the profile response fetched using this exact access token. */ +export function bindClaudeQuotaIdentity( + quota: T, + accessToken: string, + profile: unknown, + verifiedAt?: number, +): T { + identities.delete(quota); + const proof = + verifiedAt === undefined + ? null + : claudeQuotaProof(accessToken, profile, verifiedAt); + if (proof) identities.set(quota, { ...proof, authenticated: true }); + return quota; +} + +/** Opaque identity for appearance metadata, independently aged from usage. */ +export function verifiedClaudeQuotaOwner(value: object, now = Date.now()) { + const proof = identities.get(value); + return proof && validClaudeQuotaProof(proof, now) + ? { identity: proof.ownerHash, verifiedAt: new Date(proof.verifiedAt) } + : null; +} + +export function copyQuotaIdentity( + source: object, + target: T, +): T { + const identity = identities.get(source); + identities.delete(target); + if (identity) identities.set(target, identity); + return target; +} + +export function verifiedClaudeQuotaScope( + quota: object, + accessToken: string, + canonicalProfile: string | null, + now = Date.now(), +): string | null { + const identity = identities.get(quota); + return identity && + verifiedClaudeQuotaOwner(quota, now) && + canonicalProfile && + identity.tokenHash === hash(accessToken) + ? hash(["claude-principal-v1", identity.ownerHash, canonicalProfile]) + : null; +} + +export async function canonicalQuotaProfile( + path: string, +): Promise { + if (!isAbsolute(path)) return null; + try { + return await realpath(path); + } catch { + return null; + } +} + +/** Persisted proof supports dated appearance/history only, never native launch authority. */ +export function restoreClaudeQuotaIdentity( + quota: T, + proof: ClaudeQuotaProof, + now = Date.now(), +): T { + identities.delete(quota); + if (validClaudeQuotaProof(proof, now)) + identities.set(quota, { ...proof, authenticated: false }); + return quota; +} + +export function verifiedNativeClaudeQuotaScope( + quota: object, + accessToken: string, + canonicalProfile: string, + registrationHash: string, + now = Date.now(), +): string | null { + const proof = identities.get(quota); + if (!proof?.authenticated || proof.registrationHash !== registrationHash) + return null; + return verifiedClaudeQuotaScope(quota, accessToken, canonicalProfile, now); +} diff --git a/packages/host-service/src/trpc/router/usage/quota-provider-hardening.test.ts b/packages/host-service/src/trpc/router/usage/quota-provider-hardening.test.ts new file mode 100644 index 00000000000..84278d50f23 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-provider-hardening.test.ts @@ -0,0 +1,102 @@ +import { afterEach, expect, test } from "bun:test"; +import { fetchClaudeSubscriptionQuota, getCredentialQuota } from "./claude"; +import { getCodexCredentialQuota } from "./codex"; + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +test("optional Claude profile deadline cannot discard successful primary quota", async () => { + const calls: string[] = []; + globalThis.fetch = (async (input, init) => { + calls.push(String(input)); + expect(init?.cache).toBe("no-store"); + expect(init?.redirect).toBe("error"); + return Response.json({ + five_hour: { + utilization: 42, + resets_at: new Date(Date.now() + 1000).toISOString(), + }, + }); + }) as typeof fetch; + const result = await fetchClaudeSubscriptionQuota( + "synthetic-optional-budget", + { primaryMs: 8000, profileMs: 0 }, + ); + expect(result.status).toBe("ok"); + expect(result.windows[0]?.usedPercent).toBe(42); + expect(result.email).toBeNull(); + expect(calls).toHaveLength(1); +}); + +test("Claude Retry-After cannot be bypassed through another profile alias or force refresh", async () => { + let usageRequests = 0; + globalThis.fetch = (async (input) => { + if (String(input).endsWith("/profile")) + return Response.json({ email: "synthetic@example.test" }); + usageRequests++; + return new Response("limited", { + status: 429, + headers: { "Retry-After": "600" }, + }); + }) as typeof fetch; + const credential = { + accessToken: "synthetic-claude-pause-alias", + expiresAt: null, + refreshTokenExpiresAt: null, + subscriptionType: null, + accountKey: "a", + sourceLabel: "a", + selection: "/synthetic/a", + }; + const first = await getCredentialQuota(credential, true); + const alias = await getCredentialQuota( + { ...credential, accountKey: "b", selection: "/synthetic/b" }, + true, + ); + expect(first.status).toBe("unavailable"); + expect(alias).toBe(first); + expect(usageRequests).toBe(1); + expect(JSON.stringify(alias)).not.toContain(credential.accessToken); +}); + +test("Codex account header isolates a paused organization while profile aliases share its pause", async () => { + const requests: string[] = []; + globalThis.fetch = (async (_input, init) => { + const account = new Headers(init?.headers).get("chatgpt-account-id") ?? ""; + requests.push(account); + if (account === "paused") + return new Response("limited", { + status: 429, + headers: { "Retry-After": "600" }, + }); + return Response.json({ + rate_limit: { + primary_window: { used_percent: 20, reset_after_seconds: 300 }, + }, + }); + }) as typeof fetch; + const first = await getCodexCredentialQuota( + "synthetic-codex-header-pause", + "paused", + "/synthetic/a", + true, + ); + const alias = await getCodexCredentialQuota( + "synthetic-codex-header-pause", + "paused", + "/synthetic/b", + true, + ); + const healthy = await getCodexCredentialQuota( + "synthetic-codex-header-pause", + "healthy", + "/synthetic/c", + true, + ); + expect(first.status).toBe("unavailable"); + expect(alias).toBe(first); + expect(healthy.status).toBe("ok"); + expect(requests).toEqual(["paused", "healthy"]); +}); diff --git a/packages/host-service/src/trpc/router/usage/quota-request.test.ts b/packages/host-service/src/trpc/router/usage/quota-request.test.ts new file mode 100644 index 00000000000..d81efa6d36f --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-request.test.ts @@ -0,0 +1,39 @@ +import { expect, test } from "bun:test"; +import { createQuotaRequestBudget } from "./quota-request"; + +test("a compatibility fallback consumes the original deadline instead of opening a new one", async () => { + let now = 0, + calls = 0; + const budget = createQuotaRequestBudget(8_000, () => now); + expect( + await budget.run(async () => { + calls++; + now = 8_000; + return "unsupported"; + }), + ).toBe("unsupported"); + await expect( + budget.run(async () => { + calls++; + return "fallback"; + }), + ).rejects.toThrow("timed out"); + expect(calls).toBe(1); +}); +test("body failures and completed requests abort their own scope without aborting another request", async () => { + const budget = createQuotaRequestBudget(); + let signal: AbortSignal | undefined; + await expect( + budget.run(async (current) => { + signal = current; + throw new Error("body failed"); + }), + ).rejects.toThrow("body failed"); + expect(signal?.aborted).toBe(true); + expect( + await budget.run(async (current) => { + expect(current.aborted).toBe(false); + return 1; + }), + ).toBe(1); +}); diff --git a/packages/host-service/src/trpc/router/usage/quota-request.ts b/packages/host-service/src/trpc/router/usage/quota-request.ts new file mode 100644 index 00000000000..0061dd3a5c5 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-request.ts @@ -0,0 +1,43 @@ +// One deadline covers response headers, body reads and any compatibility fallback. +export const QUOTA_REQUEST_BUDGET_MS = 8_000; +export const OPTIONAL_QUOTA_BUDGET_MS = 2_000; +export const QUOTA_CAPTURE_BUDGET_MS = 2_000; + +export function createQuotaRequestBudget( + budgetMs = QUOTA_REQUEST_BUDGET_MS, + now = Date.now, + timers: { + set: ( + callback: () => void, + milliseconds: number, + ) => ReturnType; + clear: (timer: ReturnType) => void; + } = { set: setTimeout, clear: clearTimeout }, +) { + const deadline = now() + budgetMs; + return { + async run( + operation: (signal: AbortSignal) => Promise, + limitMs = budgetMs, + ): Promise { + const remaining = Math.min(limitMs, deadline - now()); + if (remaining <= 0) throw new Error("Usage request timed out."); + const controller = new AbortController(); + let timer: ReturnType | undefined; + try { + return await Promise.race([ + Promise.resolve().then(() => operation(controller.signal)), + new Promise((_, reject) => { + timer = timers.set(() => { + controller.abort(); + reject(new Error("Usage request timed out.")); + }, remaining); + }), + ]); + } finally { + if (timer !== undefined) timers.clear(timer); + controller.abort(); + } + }, + }; +} diff --git a/packages/host-service/src/trpc/router/usage/quota-snapshots.test.ts b/packages/host-service/src/trpc/router/usage/quota-snapshots.test.ts new file mode 100644 index 00000000000..ac7ce742031 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/quota-snapshots.test.ts @@ -0,0 +1,667 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + captureClaudeCredentialSlots, + captureClaudeQuotaSnapshot, + classifyLapsedToken, + readDefaultQuotaCredential, + readProfileCredential, +} from "./claude"; +import { captureCodexQuotaSnapshot } from "./codex"; +import { + type ClaudeProfile, + type CodexHome, + collectKeychainSecrets, +} from "./profiles"; +import { createQuotaCache } from "./quota-cache"; +import type { UsageAccount } from "./types"; + +const directories: string[] = []; +afterEach(async () => { + await Promise.all( + directories + .splice(0) + .map((dir) => rm(dir, { recursive: true, force: true })), + ); +}); +async function directory() { + const dir = await mkdtemp(join(tmpdir(), "superset-quota-snapshot-")); + directories.push(dir); + return dir; +} +function claudeProfile(home: string): ClaudeProfile { + return { + configDir: home, + sourceLabel: "synthetic", + email: "a@example.test", + credentialKind: "subscription", + loginFingerprint: null, + credentialsPath: join(home, ".credentials.json"), + keychainServices: [], + }; +} +const quota: UsageAccount = { + agent: "claude", + credentialKind: "subscription", + accountKey: "synthetic", + sourceLabel: "synthetic", + email: "a@example.test", + plan: "test", + status: "ok", + statusDetail: null, + windows: [], + creditsBalance: null, + extraUsage: null, + selection: null, + isDefault: false, + fetchedAt: new Date(0), +}; + +test("Claude snapshot fetch uses its captured token after mutable input changes", async () => { + const credentials = [ + { + accessToken: "synthetic-a", + expiresAt: null, + refreshTokenExpiresAt: null, + subscriptionType: null, + accountKey: "slot", + sourceLabel: "test", + selection: null, + }, + ]; + const loaded: string[] = []; + const snapshot = await captureClaudeQuotaSnapshot( + async () => ({ credentials, signedOutProfiles: [], apiProfiles: [] }), + async (credential) => { + loaded.push(credential.accessToken); + return quota; + }, + ); + const original = credentials[0]; + if (!original) throw new Error("Synthetic credential missing"); + original.accessToken = "synthetic-b"; + const next = await captureClaudeQuotaSnapshot( + async () => ({ credentials, signedOutProfiles: [], apiProfiles: [] }), + async () => quota, + ); + expect(snapshot.revision).not.toBe(next.revision); + await snapshot.load(); + expect(loaded).toEqual(["synthetic-a"]); + expect(JSON.stringify(snapshot)).not.toContain("synthetic-a"); +}); + +test("Claude strict profile reads reject malformed credentials instead of treating them as signed out", async () => { + const home = await directory(); + const profile = claudeProfile(home); + expect(await readProfileCredential(profile, true)).toBeNull(); + for (const raw of [ + "not-json", + '{"claudeAiOauth":{"accessToken":42}}', + '{"claudeAiOauth":null}', + ]) { + await writeFile(profile.credentialsPath, raw); + await expect(readProfileCredential(profile, true)).rejects.toThrow( + "could not be verified", + ); + } +}); + +test("Codex captures token and account header instead of reopening a rotated auth file", async () => { + const home = await directory(); + const homes: CodexHome[] = [ + { + home, + sourceLabel: "test", + credentialKind: "subscription", + loginFingerprint: null, + }, + ]; + const auth = (token: string, account: string) => + JSON.stringify({ + auth_mode: "chatgpt", + tokens: { access_token: token, account_id: account }, + }); + await writeFile(join(home, "auth.json"), auth("synthetic-a", "account-a")); + const loaded: unknown[] = []; + const fetchQuota = async (token: string, account?: string) => { + loaded.push([token, account]); + return { + email: "a@example.test", + plan: "test", + status: "ok" as const, + statusDetail: null, + windows: [], + creditsBalance: null, + }; + }; + const first = await captureCodexQuotaSnapshot(async () => homes, fetchQuota); + await writeFile(join(home, "auth.json"), auth("synthetic-b", "account-b")); + const second = await captureCodexQuotaSnapshot(async () => homes, fetchQuota); + expect(first.revision).not.toBe(second.revision); + await first.load(); + expect(loaded).toEqual([["synthetic-a", "account-a"]]); + expect(JSON.stringify(first)).not.toContain("synthetic-a"); +}); + +test("Codex missing credentials are distinct from malformed and unsupported storage", async () => { + const home = await directory(); + const homes: CodexHome[] = [ + { + home, + sourceLabel: "test", + credentialKind: "subscription", + loginFingerprint: null, + }, + ]; + const absent = await captureCodexQuotaSnapshot(async () => homes); + expect(await absent.load()).toEqual([]); + await writeFile(join(home, "auth.json"), "invalid-json"); + expect( + (await (await captureCodexQuotaSnapshot(async () => homes)).load())[0], + ).toMatchObject({ + status: "unavailable", + email: null, + plan: null, + windows: [], + }); + await writeFile( + join(home, "auth.json"), + JSON.stringify({ tokens: { access_token: "synthetic" } }), + ); + for (const config of [ + 'cli_auth_credentials_store = "keyring"', + 'cli_auth_credentials_store = "auto"', + 'cli_auth_credentials_store = "ephemeral"', + "bad = [", + ]) { + await writeFile(join(home, "config.toml"), config); + expect( + (await (await captureCodexQuotaSnapshot(async () => homes)).load())[0], + ).toMatchObject({ + status: "unavailable", + email: null, + plan: null, + windows: [], + }); + } +}); + +test("Claude unreadable A stays anonymous while healthy B loads and A can recover", async () => { + const homeA = await directory(); + const homeB = await directory(); + const profileA = claudeProfile(homeA); + const profileB = { ...claudeProfile(homeB), email: "b@example.test" }; + await writeFile( + profileA.credentialsPath, + '{"claudeAiOauth":{"accessToken":"synthetic-a"}}', + ); + await writeFile( + profileB.credentialsPath, + '{"claudeAiOauth":{"accessToken":"synthetic-b"}}', + ); + const capture = () => + captureClaudeCredentialSlots( + [profileA, profileB].map((profile) => ({ + profile, + source: { + agent: "claude" as const, + accountKey: profile.configDir, + sourceLabel: profile.sourceLabel, + selection: profile.configDir, + }, + read: () => readProfileCredential(profile, true), + })), + [], + ); + const loaded: string[] = []; + const cache = createQuotaCache( + () => + captureClaudeQuotaSnapshot(capture, async (credential) => { + loaded.push(credential.accessToken); + return { + ...quota, + accountKey: credential.accountKey, + email: credential.email ?? null, + }; + }), + 300_000, + ); + expect((await cache.get()).map((account) => account.email)).toEqual([ + "a@example.test", + "b@example.test", + ]); + await writeFile(profileA.credentialsPath, "malformed"); + const unreadable = await cache.get(); + expect( + unreadable.find((account) => account.accountKey === homeA), + ).toMatchObject({ + status: "unavailable", + email: null, + plan: null, + windows: [], + }); + expect( + unreadable.find((account) => account.email === "b@example.test")?.status, + ).toBe("ok"); + expect(loaded).toEqual(["synthetic-a", "synthetic-b", "synthetic-b"]); + await writeFile( + profileA.credentialsPath, + '{"claudeAiOauth":{"accessToken":"synthetic-a-new"}}', + ); + expect((await cache.get()).map((account) => account.status)).toEqual([ + "ok", + "ok", + ]); + expect(loaded).toContain("synthetic-a-new"); +}); + +test("Codex unreadable A does not block healthy B and changed credentials recover within cache TTL", async () => { + const homeA = await directory(); + const homeB = await directory(); + const homes: CodexHome[] = [homeA, homeB].map((home) => ({ + home, + sourceLabel: "test", + credentialKind: "subscription", + loginFingerprint: null, + })); + await writeFile(join(homeA, "auth.json"), "malformed"); + await writeFile( + join(homeB, "auth.json"), + '{"tokens":{"access_token":"synthetic-b"}}', + ); + const loaded: string[] = []; + const cache = createQuotaCache( + () => + captureCodexQuotaSnapshot( + async () => homes, + async (token) => { + loaded.push(token); + return { + email: `${token}@example.test`, + plan: "test", + status: "ok", + statusDetail: null, + windows: [], + creditsBalance: null, + }; + }, + ), + 300_000, + ); + const accounts = await cache.get(); + expect(accounts.map((account) => account.status)).toEqual([ + "unavailable", + "ok", + ]); + expect(accounts[0]).toMatchObject({ email: null, plan: null, windows: [] }); + expect(loaded).toEqual(["synthetic-b"]); + await writeFile( + join(homeA, "auth.json"), + '{"tokens":{"access_token":"synthetic-a"}}', + ); + expect((await cache.get()).map((account) => account.status)).toEqual([ + "ok", + "ok", + ]); + expect(loaded).toContain("synthetic-a"); +}); + +test("unreadable provider discovery yields only anonymous unavailable state and keeps the other provider loadable", async () => { + const failed = async (): Promise => { + throw new Error("must-not-be-shown"); + }; + for (const snapshot of [ + await captureClaudeQuotaSnapshot(failed), + await captureCodexQuotaSnapshot(failed), + ]) { + const accounts = await snapshot.load(); + expect(accounts).toHaveLength(1); + expect(accounts[0]).toMatchObject({ + status: "unavailable", + email: null, + plan: null, + windows: [], + }); + expect(JSON.stringify(accounts)).not.toContain("must-not-be-shown"); + } + const claude = await captureClaudeQuotaSnapshot(failed); + const codex = await captureCodexQuotaSnapshot(async () => [ + { + home: "/synthetic/api", + sourceLabel: "test", + credentialKind: "api_key", + loginFingerprint: null, + }, + ]); + expect( + (await Promise.all([claude.load(), codex.load()])) + .flat() + .map((account) => account.status), + ).toEqual(["unavailable", "ok"]); +}); + +test("API-billed Codex snapshots do not open auth files or fetch quota", async () => { + const home = await directory(); + await writeFile(join(home, "auth.json"), "must-not-be-read"); + const snapshot = await captureCodexQuotaSnapshot( + async () => [ + { + home, + sourceLabel: "test", + credentialKind: "api_key", + loginFingerprint: "marker", + }, + ], + async () => { + throw new Error("must not fetch"); + }, + ); + expect((await snapshot.load())[0]?.credentialKind).toBe("api_key"); +}); + +test("API-billed Claude profiles skip a matching explicit credential reader", async () => { + const profile = { + ...claudeProfile("/synthetic/api"), + credentialKind: "api_key" as const, + }; + let reads = 0; + const input = await captureClaudeCredentialSlots( + [ + { + source: { + agent: "claude", + accountKey: profile.configDir, + sourceLabel: profile.sourceLabel, + selection: profile.configDir, + }, + read: async () => { + reads++; + throw new Error("must not read API credential"); + }, + }, + ], + [profile], + ); + const snapshot = await captureClaudeQuotaSnapshot(async () => input); + expect(reads).toBe(0); + expect( + (await snapshot.load()).map((account) => account.credentialKind), + ).toEqual(["api_key"]); +}); + +test("optional Claude display metadata cannot hide a readable credential", async () => { + const credential = { + accessToken: "synthetic-default", + expiresAt: null, + refreshTokenExpiresAt: null, + subscriptionType: null, + accountKey: "default", + sourceLabel: "test", + selection: null, + }; + const result = await readDefaultQuotaCredential( + async () => [credential], + async () => { + throw new Error("metadata changed"); + }, + ); + expect(result).toEqual({ ...credential, email: null }); +}); + +test("Claude display-only email changes do not invalidate captured credentials", async () => { + const credential = { + accessToken: "synthetic-default", + expiresAt: null, + refreshTokenExpiresAt: null, + subscriptionType: null, + accountKey: "default", + sourceLabel: "test", + selection: null, + }; + const first = await captureClaudeQuotaSnapshot( + async () => ({ + credentials: [{ ...credential, email: "a@example.test" }], + signedOutProfiles: [], + apiProfiles: [], + }), + async () => quota, + ); + const next = await captureClaudeQuotaSnapshot( + async () => ({ + credentials: [{ ...credential, email: null }], + signedOutProfiles: [], + apiProfiles: [], + }), + async () => quota, + ); + expect(first.revision).toBe(next.revision); +}); + +test("default Claude credential failures remain strict despite optional metadata", async () => { + await expect( + readDefaultQuotaCredential( + async () => { + throw new Error("credential unreadable"); + }, + async () => "a@example.test", + ), + ).rejects.toThrow("credential unreadable"); +}); + +test("Codex null account ID is absent while non-string IDs remain unavailable", async () => { + const home = await directory(); + const homes: CodexHome[] = [ + { + home, + sourceLabel: "test", + credentialKind: "subscription", + loginFingerprint: null, + }, + ]; + const headers: Array = []; + const fetchQuota = async (_token: string, account?: string) => { + headers.push(account); + return { + email: "a@example.test", + plan: "test", + status: "ok" as const, + statusDetail: null, + windows: [], + creditsBalance: null, + }; + }; + await writeFile( + join(home, "auth.json"), + JSON.stringify({ tokens: { access_token: "synthetic", account_id: null } }), + ); + expect( + ( + await ( + await captureCodexQuotaSnapshot(async () => homes, fetchQuota) + ).load() + )[0]?.status, + ).toBe("ok"); + expect(headers).toEqual([undefined]); + for (const account_id of [42, {}, []]) { + await writeFile( + join(home, "auth.json"), + JSON.stringify({ tokens: { access_token: "synthetic", account_id } }), + ); + expect( + ( + await ( + await captureCodexQuotaSnapshot(async () => homes, fetchQuota) + ).load() + )[0]?.status, + ).toBe("unavailable"); + } + expect(headers).toEqual([undefined]); +}); + +test("Claude refresh-token presence with missing expiry remains renewable without exposing the token", async () => { + const home = await directory(); + const now = Date.now(); + for (const refreshToken of ["synthetic-refresh", " ", undefined]) { + await writeFile( + join(home, ".credentials.json"), + JSON.stringify({ + claudeAiOauth: { + accessToken: "synthetic-lapsed", + expiresAt: now - 1000, + refreshToken, + }, + }), + ); + const credential = await readProfileCredential(claudeProfile(home), true); + if (!credential) throw new Error("Expected readable credential"); + expect(credential.hasRefreshToken).toBe( + refreshToken === "synthetic-refresh", + ); + expect(classifyLapsedToken(credential, now)).toBe( + refreshToken === "synthetic-refresh" ? "token_stale" : "token_expired", + ); + expect(JSON.stringify(credential)).not.toContain("synthetic-refresh"); + } +}); + +test("Claude profiles sharing a token stay distinct without a shared account row", async () => { + const input = await captureClaudeCredentialSlots( + ["a", "b"].map((id) => ({ + source: { + agent: "claude" as const, + accountKey: id, + sourceLabel: id, + selection: `/synthetic/${id}`, + }, + read: async () => ({ + accessToken: "synthetic-shared-profile-token", + expiresAt: null, + refreshTokenExpiresAt: null, + subscriptionType: null, + accountKey: id, + sourceLabel: id, + selection: `/synthetic/${id}`, + }), + })), + [], + ); + expect(input.credentials.map((item) => item.selection)).toEqual([ + "/synthetic/a", + "/synthetic/b", + ]); +}); + +test("failed Claude request remains anonymous while a healthy sibling loads", async () => { + const snapshot = await captureClaudeQuotaSnapshot( + async () => ({ + credentials: ["unavailable", "healthy"].map((id) => ({ + accessToken: `synthetic-slot-${id}`, + expiresAt: null, + refreshTokenExpiresAt: null, + subscriptionType: null, + accountKey: id, + sourceLabel: id, + selection: `/synthetic/${id}`, + })), + signedOutProfiles: [], + apiProfiles: [], + }), + async (credential) => { + if (credential.accountKey === "unavailable") + throw new Error("synthetic-secret-not-for-output"); + return { ...quota, accountKey: credential.accountKey }; + }, + ); + const rows = await snapshot.load(); + expect(rows.map((row) => row.status)).toEqual(["unavailable", "ok"]); + expect(rows[0]?.email).toBeNull(); + expect(JSON.stringify(rows)).not.toContain("synthetic-secret-not-for-output"); + expect(JSON.stringify(rows)).not.toContain("synthetic-slot-unavailable"); + for (const key of [ + "accessToken", + "expiresAt", + "refreshTokenExpiresAt", + "hasRefreshToken", + "subscriptionType", + ]) + expect(rows[0]).not.toHaveProperty(key); +}); + +test("strict Keychain scope reads start together and preserve missing-item/error semantics", async () => { + let release!: () => void; + const gate = new Promise((done) => { + release = done; + }); + const calls: string[] = []; + const pending = collectKeychainSecrets( + [["a"], ["b"], []], + async (scope) => { + calls.push(scope[0] ?? "unscoped"); + await gate; + if (scope[0] === "b") + throw Object.assign(new Error("missing"), { code: 44 }); + return " synthetic-scope-secret "; + }, + true, + ); + await Promise.resolve(); + const started = [...calls]; + release(); + expect(await pending).toEqual(["synthetic-scope-secret"]); + expect(started).toEqual(["a", "b", "unscoped"]); + await expect( + collectKeychainSecrets( + [[]], + async () => { + throw new Error("secret-error"); + }, + true, + ), + ).rejects.toThrow("Quota credentials could not be verified."); +}); + +test("Codex homes sharing one subscription keep separate rows while deduplicating transport", async () => { + const homes: CodexHome[] = []; + for (const id of ["a", "b"]) { + const home = await directory(); + await writeFile( + join(home, "auth.json"), + JSON.stringify({ + tokens: { + access_token: "synthetic-codex-shared-rows", + account_id: "same-account", + }, + }), + ); + homes.push({ + home, + sourceLabel: id, + credentialKind: "subscription", + loginFingerprint: null, + }); + } + let requests = 0; + const snapshot = await captureCodexQuotaSnapshot( + async () => homes, + async () => { + requests++; + return { + email: "same@example.test", + plan: "test", + status: "ok", + statusDetail: null, + windows: [], + creditsBalance: null, + }; + }, + ); + const rows = await snapshot.load(); + expect(rows).toHaveLength(2); + const second = homes[1]; + if (!second) throw new Error("Expected second synthetic profile"); + expect(rows.map((row) => row.selection)).toEqual([null, second.home]); + expect(requests).toBe(1); + expect(rows[0]?.fetchedAt).toEqual(rows[1]?.fetchedAt); +}); diff --git a/packages/host-service/src/trpc/router/usage/session-account/session-account.test.ts b/packages/host-service/src/trpc/router/usage/session-account/session-account.test.ts index a4afa442b88..d8d3c99e66f 100644 --- a/packages/host-service/src/trpc/router/usage/session-account/session-account.test.ts +++ b/packages/host-service/src/trpc/router/usage/session-account/session-account.test.ts @@ -2,7 +2,12 @@ import { afterEach, describe, expect, test } from "bun:test"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { readAccountIdentity, validateSessionAccount } from "./session-account"; +import { + readAccountIdentity, + type SessionAccount, + sameSessionAccountContext, + validateSessionAccount, +} from "./session-account"; const dirs: string[] = []; async function directory() { @@ -90,3 +95,41 @@ describe("session account identity", () => { expect(await readAccountIdentity("codex", dir)).toBeNull(); }); }); + +describe("durable account context equality", () => { + const account: SessionAccount = { + agent: "claude", + selection: "/fixture", + directory: "/fixture", + credentialKind: "subscription", + identity: "alice", + pinned: true, + }; + test("ignores object order and display email", () => { + expect( + sameSessionAccountContext(account, { + email: "renamed@example.com", + ...account, + }), + ).toBe(true); + }); + test("rejects missing context and all routing or safety changes", () => { + expect(sameSessionAccountContext(null, null)).toBe(false); + expect(sameSessionAccountContext(undefined, account)).toBe(false); + for (const changed of [ + { agent: "codex" }, + { selection: null }, + { directory: "/other" }, + { credentialKind: "api_key" }, + { identity: "bob" }, + { pinned: undefined }, + { conflict: true }, + ]) + expect( + sameSessionAccountContext(account, { + ...account, + ...changed, + } as SessionAccount), + ).toBe(false); + }); +}); diff --git a/packages/host-service/src/trpc/router/usage/session-account/session-account.ts b/packages/host-service/src/trpc/router/usage/session-account/session-account.ts index 34c59ff3303..e4d2b403467 100644 --- a/packages/host-service/src/trpc/router/usage/session-account/session-account.ts +++ b/packages/host-service/src/trpc/router/usage/session-account/session-account.ts @@ -1,7 +1,9 @@ import { createHash } from "node:crypto"; -import { readFile, realpath, stat } from "node:fs/promises"; +import { realpath } from "node:fs/promises"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; +import { z } from "zod"; +import { readProfileFile } from "../profile-file"; import { API_BILLING_MARKER, discoverClaudeProfiles, @@ -9,6 +11,10 @@ import { } from "../profiles"; export interface SessionAccount { + /** Explicit launch selection; an observed account alone is not a pin. */ + pinned?: true; + /** A same-launch hook reported another login; automatic recovery is refused. */ + conflict?: true; agent: "claude" | "codex"; selection: string | null; credentialKind: "subscription" | "api_key"; @@ -17,14 +23,63 @@ export interface SessionAccount { email?: string; } +const persistedAccountSchema = z + .object({ + agent: z.enum(["claude", "codex"]), + selection: z.string().nullable(), + credentialKind: z.enum(["subscription", "api_key"]), + identity: z.string().min(1), + directory: z.string().optional(), + email: z.string().optional(), + pinned: z.literal(true).optional(), + conflict: z.literal(true).optional(), + }) + .superRefine((account, ctx) => { + if ( + account.pinned && + (account.credentialKind !== "subscription" || !account.directory) + ) { + ctx.addIssue({ code: "custom", message: "Invalid pinned account" }); + } + }); + +/** Malformed saved context must not silently become a default-account launch. */ +export function parsePersistedSessionAccount( + value: string | null, +): SessionAccount | undefined | null { + if (value === null) return undefined; + try { + const parsed = persistedAccountSchema.safeParse(JSON.parse(value)); + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} + +/** Compare durable routing context independently of JSON order and display metadata. */ +export function sameSessionAccountContext( + left: SessionAccount | null | undefined, + right: SessionAccount | null | undefined, +): boolean { + if (!left || !right) return false; + return ( + left.agent === right.agent && + left.credentialKind === right.credentialKind && + left.identity === right.identity && + left.selection === right.selection && + left.directory === right.directory && + (left.pinned === true) === (right.pinned === true) && + (left.conflict === true) === (right.conflict === true) + ); +} + async function hasApiMarker( agent: string, directory: string, ): Promise { try { - const file = join(directory, API_BILLING_MARKER); - if ((await stat(file)).size > 64) return false; - return (await readFile(file, "utf8")).trim() === agent; + const file = await readProfileFile(join(directory, API_BILLING_MARKER), 64); + return file?.content.trim() === agent; } catch { return false; } @@ -46,8 +101,9 @@ export async function readAccountIdentity( (await canonical(join(homedir(), ".claude"))) ? join(homedir(), ".claude.json") : join(directory, ".claude.json"); - if ((await stat(file)).size > 50 * 1024 * 1024) return null; - const data = JSON.parse(await readFile(file, "utf8")); + const state = await readProfileFile(file, 50 * 1024 * 1024); + if (!state) return null; + const data = JSON.parse(state.content); const claims = agent === "codex" && typeof data.tokens?.id_token === "string" ? JSON.parse( @@ -91,53 +147,85 @@ export async function captureSessionAccount( identity: "api-env", }; - const profiles = - agent === "claude" - ? [ - { - directory: join(homedir(), ".claude"), - selection: null, - credentialKind: (await hasApiMarker( - "claude", - join(homedir(), ".claude"), - )) - ? ("api_key" as const) - : ("subscription" as const), - }, - ...(await discoverClaudeProfiles()).map((p) => ({ - directory: p.configDir, - selection: p.configDir, - credentialKind: p.credentialKind, - })), - ] - : (await discoverCodexHomes()).map((p, index) => ({ - directory: p.home, - selection: index === 0 ? null : p.home, - credentialKind: p.credentialKind, - })); + const profiles = await discoverSessionAccountProfiles(agent); const directory = await canonical(profile || profiles[0]?.directory || ""); for (const candidate of profiles) { if ((await canonical(candidate.directory)) !== directory) continue; - if (candidate.credentialKind === "api_key") - return { - agent, - selection: candidate.selection, - credentialKind: "api_key", - identity: "api-profile", - }; - const identity = await readAccountIdentity(agent, candidate.directory); - if (identity) - return { - agent, - selection: candidate.selection, - credentialKind: "subscription", - ...identity, - directory: candidate.directory, - }; + return readSessionAccount(agent, candidate); } return undefined; } +interface SessionAccountProfile { + directory: string; + selection: string | null; + credentialKind: "subscription" | "api_key"; +} + +async function discoverSessionAccountProfiles( + agent: "claude" | "codex", +): Promise { + return agent === "claude" + ? [ + { + directory: join(homedir(), ".claude"), + selection: null, + credentialKind: (await hasApiMarker( + "claude", + join(homedir(), ".claude"), + )) + ? ("api_key" as const) + : ("subscription" as const), + }, + ...(await discoverClaudeProfiles()).map((p) => ({ + directory: p.configDir, + selection: p.configDir, + credentialKind: p.credentialKind, + })), + ] + : (await discoverCodexHomes()).map((p, index) => ({ + directory: p.home, + selection: index === 0 ? null : p.home, + credentialKind: p.credentialKind, + })); +} + +async function readSessionAccount( + agent: "claude" | "codex", + candidate: SessionAccountProfile, +): Promise { + if (candidate.credentialKind === "api_key") + return { + agent, + selection: candidate.selection, + credentialKind: "api_key", + identity: "api-profile", + }; + const identity = await readAccountIdentity(agent, candidate.directory); + if (identity) + return { + agent, + selection: candidate.selection, + credentialKind: "subscription", + ...identity, + directory: candidate.directory, + }; + return undefined; +} + +/** Existing profiles only; this never reads keychain secrets or refreshes login. */ +export async function discoverSessionAccounts( + agent: "claude" | "codex", +): Promise { + const profiles = await discoverSessionAccountProfiles(agent); + const accounts = await Promise.all( + profiles.map((profile) => readSessionAccount(agent, profile)), + ); + return accounts.filter( + (account): account is SessionAccount => account !== undefined, + ); +} + export async function validateSessionAccount( snapshot: SessionAccount, ): Promise { diff --git a/packages/host-service/src/trpc/router/usage/types.ts b/packages/host-service/src/trpc/router/usage/types.ts index 25c4f954772..af3ec8cdedd 100644 --- a/packages/host-service/src/trpc/router/usage/types.ts +++ b/packages/host-service/src/trpc/router/usage/types.ts @@ -67,6 +67,8 @@ export type UsageAccountStatus = | "signed_out"; export interface UsageQuotaWindow { + observedAt?: Date; + source?: "provider" | "claude_statusline" | "claude_sdk"; /** Stable identifier within the account, e.g. "five_hour", "seven_day", * or a model-scoped key. */ id: string; @@ -76,6 +78,8 @@ export interface UsageQuotaWindow { } export interface UsageAccount { + /** Inventory discovery failed; this placeholder is not a discovered account. */ + discoveryFailed?: boolean; agent: QuotaCapableAgent; credentialKind: UsageAccountCredentialKind; /** Stable key for the credential source (config path or keychain item), @@ -89,6 +93,11 @@ export interface UsageAccount { /** Human-readable detail for non-ok statuses. */ statusDetail: string | null; windows: UsageQuotaWindow[]; + retryAt?: Date; + /** Display history only; never evidence of currently available allowance. */ + lastKnownUsage?: { fetchedAt: Date; windows: UsageQuotaWindow[] }; + /** Actual prepaid funds in major currency units, separate from the spend cap. */ + prepaidBalance?: { amount: number; currency: string | null; checkedAt: Date }; /** Codex prepaid credits balance, when present. */ creditsBalance: number | null; /** Claude extra-usage spend, in cents, when present. */ diff --git a/packages/host-service/src/trpc/router/usage/usage-quota.test.ts b/packages/host-service/src/trpc/router/usage/usage-quota.test.ts new file mode 100644 index 00000000000..aaa8060f2fc --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/usage-quota.test.ts @@ -0,0 +1,374 @@ +import { expect, test } from "bun:test"; +import { createCredentialQuotaCache } from "./credential-quota-cache"; +import { copyQuotaRetry, recordQuotaRetry } from "./quota-backoff"; +import { unavailableQuotaAccount } from "./quota-credentials"; +import type { UsageAccount } from "./types"; +import { createUsageQuotaReader } from "./usage-quota"; + +const account = (agent: "claude" | "codex", value = 20): UsageAccount => ({ + ...unavailableQuotaAccount({ + agent, + accountKey: agent, + sourceLabel: agent, + selection: null, + }), + status: "ok", + statusDetail: null, + windows: [ + { id: "session", label: "Session", usedPercent: value, resetsAt: null }, + ], +}); + +test("provider rejection cannot erase a healthy provider or claim a logout", async () => { + let reads = 0; + const reader = createUsageQuotaReader([ + { + agent: "claude", + capture: async () => { + throw new Error("private-reader-error"); + }, + }, + { + agent: "codex", + capture: async () => ({ + revision: "codex", + load: async () => { + reads++; + return [account("codex")]; + }, + }), + }, + ]); + const first = await reader.get(); + expect(first.map((item) => item.status)).toEqual(["unavailable", "ok"]); + expect(first[0]?.discoveryFailed).toBe(true); + expect(first[0]).not.toHaveProperty("quotaIdentity"); + expect(JSON.stringify(first)).not.toContain("private-reader-error"); + await reader.get(true); + expect(reads).toBe(1); +}); + +test("surfaces share force cooldown, five-minute polling and independent credential revisions", async () => { + let now = 0, + claudeLoads = 0, + codexLoads = 0, + codexRevision = "A"; + const reader = createUsageQuotaReader( + [ + { + agent: "claude", + capture: async () => ({ + revision: "claude", + load: async () => { + claudeLoads++; + return [account("claude")]; + }, + }), + }, + { + agent: "codex", + capture: async () => ({ + revision: codexRevision, + load: async () => { + codexLoads++; + return [account("codex")]; + }, + }), + }, + ], + () => now, + ); + await reader.get(); + await Promise.all([reader.get(true), reader.get(), reader.get(true)]); + expect([claudeLoads, codexLoads]).toEqual([1, 1]); + now = 29_999; + await reader.get(true); + expect([claudeLoads, codexLoads]).toEqual([1, 1]); + codexRevision = "B"; + await reader.get(); + expect([claudeLoads, codexLoads]).toEqual([1, 2]); + now = 30_000; + await reader.get(true); + expect([claudeLoads, codexLoads]).toEqual([2, 2]); + now = 329_998; + await reader.get(); + expect([claudeLoads, codexLoads]).toEqual([2, 2]); + now = 330_000; + await reader.get(); + expect([claudeLoads, codexLoads]).toEqual([3, 3]); +}); + +test("failed provider force reads have shared bounded exponential backoff", async () => { + let now = 0, + loads = 0; + const reader = createUsageQuotaReader( + [ + { + agent: "claude", + capture: async () => ({ + revision: "A", + load: async () => { + loads++; + return [{ ...account("claude"), status: "unavailable" }]; + }, + }), + }, + ], + () => now, + ); + await reader.get(); + now = 29_999; + await reader.get(true); + expect(loads).toBe(1); + now = 30_000; + await reader.get(true); + expect(loads).toBe(2); + now = 89_999; + await reader.get(true); + expect(loads).toBe(2); + now = 90_000; + await reader.get(true); + expect(loads).toBe(3); +}); + +test("one account Retry-After survives sibling credential rotation while healthy siblings refresh", async () => { + let now = 0, + aLoads = 0, + bLoads = 0, + bToken = "B1"; + const credentials = createCredentialQuotaCache( + 300_000, + () => now, + ); + const limited = copyQuotaRetry( + recordQuotaRetry( + account("claude"), + new Response("", { status: 429, headers: { "Retry-After": "600" } }), + ), + { ...account("claude"), status: "unavailable" as const }, + ); + const reader = createUsageQuotaReader( + [ + { + agent: "claude", + capture: async () => { + const capturedB = bToken; + return { + revision: capturedB, + load: async (force = false) => + Promise.all([ + credentials.get( + "A", + async () => { + aLoads++; + return limited; + }, + force, + ), + credentials.get( + capturedB, + async () => { + bLoads++; + return account("claude"); + }, + force, + ), + ]), + }; + }, + }, + ], + () => now, + ); + await reader.get(); + expect([aLoads, bLoads]).toEqual([1, 1]); + now = 1; + bToken = "B2"; + await reader.get(true); + expect([aLoads, bLoads]).toEqual([1, 2]); + now = 30_001; + await reader.get(true); + expect([aLoads, bLoads]).toEqual([1, 3]); + now = 599_999; + await reader.get(true); + expect([aLoads, bLoads]).toEqual([1, 4]); + now = 630_000; + await reader.get(true); + expect([aLoads, bLoads]).toEqual([2, 5]); + expect(JSON.stringify(limited)).not.toContain("retry"); +}); + +test("sibling rotation does not extend another account's original five-minute observation lifetime", async () => { + let now = 0, + aLoads = 0, + bToken = "B1"; + const credentials = createCredentialQuotaCache( + 300_000, + () => now, + ); + const reader = createUsageQuotaReader( + [ + { + agent: "claude", + capture: async () => { + const captured = bToken; + return { + revision: captured, + load: async (force = false) => + Promise.all([ + credentials.get( + "A", + async () => { + aLoads++; + return { ...account("claude"), fetchedAt: new Date(now) }; + }, + force, + ), + credentials.get( + captured, + async () => ({ + ...account("claude"), + fetchedAt: new Date(now), + }), + force, + ), + ]), + }; + }, + }, + ], + () => now, + ); + const first = await reader.get(); + now = 240_000; + bToken = "B2"; + const rotated = await reader.get(); + expect(rotated[0]?.fetchedAt).toBe(first[0]?.fetchedAt); + expect(aLoads).toBe(1); + now = 300_000; + await reader.get(); + expect(aLoads).toBe(2); +}); + +test("a provider completion refreshes its placeholder and disposal unsubscribes owned work", async () => { + let completed: (() => void) | undefined; + let loads = 0, + unsubscribed = 0, + disposed = 0; + const reader = createUsageQuotaReader([ + { + agent: "claude", + subscribe: (listener) => { + completed = listener; + return () => { + unsubscribed++; + }; + }, + dispose: async () => { + disposed++; + }, + capture: async () => ({ + revision: "same-owner", + load: async () => { + loads++; + return [account("claude", loads)]; + }, + }), + }, + ]); + expect((await reader.get())[0]?.windows[0]?.usedPercent).toBe(1); + completed?.(); + expect((await reader.get())[0]?.windows[0]?.usedPercent).toBe(2); + await reader.dispose(); + expect([unsubscribed, disposed]).toEqual([1, 1]); +}); + +test("native completion refreshes the shared snapshot without relabeling HTTP or wallet dates", async () => { + let now = 1_800_000_000_000; + const httpAt = new Date(now - 20 * 60_000); + const walletAt = new Date(now - 25 * 60_000); + let loads = 0; + let changed: (() => void) | undefined; + let disposed = false; + const reader = createUsageQuotaReader( + [ + { + agent: "claude", + subscribe: (listener) => { + changed = listener; + return () => { + disposed = true; + }; + }, + capture: async () => ({ + revision: "same-native-owner", + load: async () => { + loads++; + return [ + { + ...account("claude"), + fetchedAt: httpAt, + prepaidBalance: { + amount: 10, + currency: "USD", + checkedAt: walletAt, + }, + windows: [ + { + id: "five_hour", + label: "Session (5h)", + usedPercent: 20, + resetsAt: new Date(now + 60 * 60_000), + observedAt: new Date(now), + source: "claude_statusline" as const, + }, + ], + }, + ]; + }, + }), + }, + ], + () => now, + ); + await reader.get(); + now += 60_000; + const same = await reader.get(); + expect(loads).toBe(1); + expect(same[0]?.fetchedAt).toBe(httpAt); + expect(same[0]?.prepaidBalance?.checkedAt).toBe(walletAt); + changed?.(); + const refreshed = await reader.get(); + expect(loads).toBe(2); + expect(refreshed[0]?.fetchedAt).toBe(httpAt); + expect(refreshed[0]?.windows[0]?.observedAt).toEqual(new Date(now)); + await reader.dispose(); + expect(disposed).toBe(true); +}); + +test("per-provider inventory timing expires only the short-lived provider", async () => { + let now = 0; + const calls = { claude: 0, codex: 0 }; + const reader = createUsageQuotaReader( + (["claude", "codex"] as const).map((agent) => ({ + agent, + ttlMs: agent === "claude" ? 60_000 : 300_000, + capture: async () => ({ + revision: agent, + load: async () => { + calls[agent]++; + return [{ ...account(agent), fetchedAt: new Date(now) }]; + }, + }), + })), + () => now, + ); + await reader.get(); + now = 60_000; + await reader.get(); + expect(calls).toEqual({ claude: 2, codex: 1 }); + reader.expire("claude"); + await reader.get(); + expect(calls).toEqual({ claude: 3, codex: 1 }); + await reader.dispose(); +}); diff --git a/packages/host-service/src/trpc/router/usage/usage-quota.ts b/packages/host-service/src/trpc/router/usage/usage-quota.ts new file mode 100644 index 00000000000..8661c7a1fc9 --- /dev/null +++ b/packages/host-service/src/trpc/router/usage/usage-quota.ts @@ -0,0 +1,106 @@ +import { readQuotaRetry } from "./quota-backoff"; +import { createQuotaCache, type QuotaSnapshot } from "./quota-cache"; +import { unavailableQuotaAccount } from "./quota-credentials"; +import type { UsageAccount } from "./types"; + +export const QUOTA_CACHE_TTL_MS = 5 * 60_000; +export const QUOTA_FORCE_COOLDOWN_MS = 30_000; + +export interface UsageQuotaProvider { + agent: UsageAccount["agent"]; + ttlMs?: number; + capture: () => Promise>; + subscribe?: (listener: () => void) => () => void; + dispose?: () => Promise; +} + +// Separate caches isolate provider failures and credential changes. Every surface +// still shares each provider's one accepted request and polling limits. +export function createUsageQuotaReader( + providers: UsageQuotaProvider[], + now = Date.now, +) { + const readers = providers.map( + ({ agent, capture, subscribe, dispose, ttlMs = QUOTA_CACHE_TTL_MS }) => { + const cache = createQuotaCache(capture, ttlMs, now, { + forceCooldownMs: QUOTA_FORCE_COOLDOWN_MS, + retryOnFailure: true, + freshUntil: (accounts) => + Math.min( + now() + ttlMs, + ...accounts.map((account) => { + const observedAt = Math.max( + new Date(account.fetchedAt).getTime(), + ...account.windows.flatMap((window) => { + if ( + window.source !== "claude_statusline" && + window.source !== "claude_sdk" + ) + return []; + const at = window.observedAt?.getTime(); + return at !== undefined && + Number.isFinite(at) && + at <= now() && + window.resetsAt !== null && + window.resetsAt.getTime() > now() && + Number.isFinite(window.usedPercent) && + window.usedPercent >= 0 && + window.usedPercent <= 100 + ? [at] + : []; + }), + ); + return Number.isFinite(observedAt) && observedAt <= now() + ? observedAt + Math.max(ttlMs, readQuotaRetry(account)) + : now() + ttlMs; + }), + ), + isFailure: (accounts) => + accounts.length > 0 && + accounts.every((account) => account.status === "unavailable"), + }); + return { + agent, + cache, + unsubscribe: subscribe?.(() => cache.expire()), + dispose, + }; + }, + ); + return { + async get(forceRefresh = false): Promise { + return ( + await Promise.all( + readers.map(async ({ agent, cache }) => { + try { + return await cache.get(forceRefresh); + } catch { + return [ + { + ...unavailableQuotaAccount({ + agent, + accountKey: `${agent}:discovery`, + sourceLabel: `${agent} accounts`, + selection: null, + }), + discoveryFailed: true, + }, + ]; + } + }), + ) + ).flat(); + }, + async dispose() { + for (const reader of readers) reader.unsubscribe?.(); + await Promise.all(readers.map((reader) => reader.dispose?.())); + }, + expire(agent: UsageAccount["agent"]) { + for (const reader of readers) + if (reader.agent === agent) reader.cache.expire(); + }, + invalidate() { + for (const { cache } of readers) cache.invalidate(); + }, + }; +} diff --git a/packages/host-service/src/trpc/router/usage/usage.ts b/packages/host-service/src/trpc/router/usage/usage.ts index 4e4debac5df..7a059bf2c5d 100644 --- a/packages/host-service/src/trpc/router/usage/usage.ts +++ b/packages/host-service/src/trpc/router/usage/usage.ts @@ -18,17 +18,21 @@ import { } from "./account-provisioning"; import { fetchAgyAccounts } from "./agy-quota"; import { - fetchClaudeAccounts, + CLAUDE_QUOTA_POLL_MS, + captureClaudeQuotaSnapshot, + disposeClaudeQuotaCollection, + onClaudeQuotaUpdate, readClaudeLoginFingerprint, readDefaultLoginEmail, } from "./claude"; -import { fetchCodexAccounts } from "./codex"; +import { captureCodexQuotaSnapshot } from "./codex"; import { getDefaultAccountSelections, setDefaultAccountSelection, } from "./default-account"; import { fetchGrokAccounts } from "./grok-quota"; import { countAgentPrsByDay } from "./history/agent-prs"; +import { onNativeClaudeUsage } from "./native-claude-usage"; import { fetchOpencodeAccounts } from "./opencode-quota"; import { removeClaudeProfile, removeCodexHome } from "./profile-remove"; import { @@ -37,47 +41,61 @@ import { readCodexProfileKind, } from "./profiles"; import { validateSessionAccount } from "./session-account/session-account"; -import type { UsageAccount } from "./types"; +import { createUsageQuotaReader } from "./usage-quota"; -/** - * Agent quota endpoints are undocumented and rate-limit-sensitive, so - * results are cached briefly and concurrent callers share one in-flight - * request. The cached promise is evicted on rejection so a failure does not - * replay for the whole TTL. - */ -// >=5 min: Anthropic 429-blacklists faster pollers of the oauth/usage -// endpoint (ccusage deprecated its live gauge over this; CodexBar #30930). -const QUOTA_CACHE_TTL_MS = 5 * 60 * 1000; - -let cachedQuota: { promise: Promise; cachedAt: number } | null = - null; - -function loadAccounts(): Promise { - return Promise.all([ - fetchClaudeAccounts(), - fetchCodexAccounts(), - fetchGrokAccounts(), - fetchAgyAccounts(), - fetchOpencodeAccounts(), - ]).then((groups) => groups.flat()); +let quotaCache: ReturnType | undefined; +function getQuotaReader() { + if (!quotaCache) + quotaCache = createUsageQuotaReader([ + { + agent: "claude", + ttlMs: CLAUDE_QUOTA_POLL_MS, + capture: captureClaudeQuotaSnapshot, + subscribe: (listener) => { + const stopHttp = onClaudeQuotaUpdate(listener); + const stopNative = onNativeClaudeUsage(listener); + return () => { + stopHttp(); + stopNative(); + }; + }, + dispose: disposeClaudeQuotaCollection, + }, + { agent: "codex", capture: captureCodexQuotaSnapshot }, + { + agent: "grok", + capture: async () => ({ + revision: "grok", + load: () => fetchGrokAccounts(), + }), + }, + { + agent: "agy", + capture: async () => ({ + revision: "agy", + load: () => fetchAgyAccounts(), + }), + }, + { + agent: "opencode", + capture: async () => ({ + revision: "opencode", + load: (forceRefresh = false) => + fetchOpencodeAccounts(undefined, forceRefresh), + }), + }, + ]); + return quotaCache; +} +const getQuota = (forceRefresh: boolean) => getQuotaReader().get(forceRefresh); +export function expireUsageQuota(agent: "claude" | "codex") { + quotaCache?.expire(agent); } -function getQuota(forceRefresh: boolean): Promise { - if ( - !forceRefresh && - cachedQuota && - Date.now() - cachedQuota.cachedAt < QUOTA_CACHE_TTL_MS - ) { - return cachedQuota.promise; - } - - const promise = loadAccounts(); - const entry = { promise, cachedAt: Date.now() }; - cachedQuota = entry; - promise.catch(() => { - if (cachedQuota === entry) cachedQuota = null; - }); - return promise; +export async function disposeUsageQuota() { + const retiring = quotaCache; + quotaCache = undefined; + await retiring?.dispose(); } export const leaderboardPayloadInput = z.object({ @@ -282,7 +300,7 @@ export const usageRouter = router({ } // The quota cache still lists the removed account; drop it so the // next query re-discovers. - cachedQuota = null; + getQuotaReader().invalidate(); return { success: true as const }; }), diff --git a/packages/host-service/src/workers/tasks/harness.test.ts b/packages/host-service/src/workers/tasks/harness.test.ts index bc276c9f797..430956bc396 100644 --- a/packages/host-service/src/workers/tasks/harness.test.ts +++ b/packages/host-service/src/workers/tasks/harness.test.ts @@ -1,8 +1,10 @@ import { afterEach, describe, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; import { mkdirSync, mkdtempSync, readFileSync, + realpathSync, rmSync, writeFileSync, } from "node:fs"; @@ -10,7 +12,11 @@ import { tmpdir } from "node:os"; import * as path from "node:path"; import { claudeProjectDirName } from "../../terminal-agents/harness-sessions/claude.ts"; import { HostWorkerPool } from "../host-worker-pool.ts"; -import { harnessTasks, harnessTranscriptTask } from "./harness.ts"; +import { + harnessTasks, + harnessTranscriptTask, + inspectSavedConversationTask, +} from "./harness.ts"; const WORKER_ENTRY = path.resolve(import.meta.dirname, "..", "host-worker.ts"); const NATIVE_MODULES = ["better-sqlite3", "node-pty", "@parcel/watcher"]; @@ -47,6 +53,7 @@ function importGraph(entry: string): Map { describe("harness worker tasks", () => { test("registers every task and has no duplicate types", () => { expect(harnessTasks).toContain(harnessTranscriptTask); + expect(harnessTasks).toContain(inspectSavedConversationTask); const types = harnessTasks.map((task) => task.type); expect(types).toEqual([...new Set(types)]); }); @@ -94,3 +101,55 @@ describe("harness worker tasks", () => { expect(result).toEqual({ text: "User: off the loop", harness: "claude" }); }); }); + +test("saved-history worker returns only stable identity evidence and refuses invalid history", async () => { + const temporary = mkdtempSync(path.join(tmpdir(), "saved-history-task-")); + cleanup.push(() => rmSync(temporary, { recursive: true, force: true })); + const configDir = realpathSync(temporary); + const cwd = path.join(configDir, "workspace"); + mkdirSync(cwd); + const sessionId = "55555555-6666-4777-8888-999900001111"; + const directory = path.join(configDir, "projects", claudeProjectDirName(cwd)); + mkdirSync(directory, { recursive: true }); + const file = path.join(directory, `${sessionId}.jsonl`); + const content = `${JSON.stringify({ type: "user", sessionId, cwd, uuid: "11111111-2222-4333-8444-555555555555", message: { role: "user", content: "synthetic worker validation" } })}\n`; + writeFileSync(file, content); + const pool = new HostWorkerPool({ scriptPathResolver: () => WORKER_ENTRY }); + cleanup.push(() => pool.dispose()); + const input = { + provider: "claude" as const, + sourceDirectory: configDir, + targetDirectory: configDir, + sessionId, + cwd, + }; + const workerOnlyTask: typeof inspectSavedConversationTask = { + ...inspectSavedConversationTask, + handler: async (): Promise => { + throw new Error("This fixture must not run inline"); + }, + }; + expect(pool.getMode()).toBe("worker"); + const result = await pool.run(workerOnlyTask, input); + expect(result).toEqual({ + path: file, + device: expect.any(Number), + inode: expect.any(Number), + size: Buffer.byteLength(content), + modifiedAt: expect.any(Number), + changedAt: expect.any(Number), + sha256: createHash("sha256").update(content).digest("hex"), + storeBindings: [ + { + path: path.join(input.sourceDirectory, "projects"), + canonical: realpathSync(path.join(configDir, "projects")), + }, + { + path: path.join(input.targetDirectory, "projects"), + canonical: realpathSync(path.join(configDir, "projects")), + }, + ], + }); + writeFileSync(file, "{invalid JSON}\n"); + expect(await pool.run(workerOnlyTask, input)).toBeNull(); +}); diff --git a/packages/host-service/src/workers/tasks/harness.ts b/packages/host-service/src/workers/tasks/harness.ts index 3a64c12012f..e8bcff487a0 100644 --- a/packages/host-service/src/workers/tasks/harness.ts +++ b/packages/host-service/src/workers/tasks/harness.ts @@ -7,6 +7,11 @@ import { readHarnessTranscript, } from "../../terminal-agents/harness-sessions/transcript.ts"; import type { HarnessSessionRef } from "../../terminal-agents/harness-sessions/types.ts"; +import { + type AccountResumeHistory, + inspectNativeResumeHistory, + type NativeResumeHistoryInput, +} from "../../terminal-agents/saved-conversations/inspect-native-history.ts"; import { defineWorkerTask } from "../define-worker-task.ts"; export const harnessTranscriptTask = defineWorkerTask< @@ -17,4 +22,15 @@ export const harnessTranscriptTask = defineWorkerTask< handler: async ({ ref, maxChars }) => readHarnessTranscript(ref, maxChars), }); -export const harnessTasks = [harnessTranscriptTask]; +export const inspectSavedConversationTask = defineWorkerTask< + NativeResumeHistoryInput, + AccountResumeHistory | null +>({ + type: "harness/inspectSavedConversation", + handler: inspectNativeResumeHistory, +}); + +export const harnessTasks = [ + harnessTranscriptTask, + inspectSavedConversationTask, +]; diff --git a/packages/i18n/locales/cs/messages.po b/packages/i18n/locales/cs/messages.po index 486ef9c0c1c..d8c12efef63 100644 --- a/packages/i18n/locales/cs/messages.po +++ b/packages/i18n/locales/cs/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} z {total}" +msgid "{remainingPercent} remaining" +msgstr "Zbývá {remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} není v účtu {installedAccountLogin}, kde je nainstalovaná GitHub App této organizace." @@ -2064,6 +2067,12 @@ msgstr "Relace agenta spuštěna" msgid "agent settings" msgstr "nastavení agenta" +msgid "Agent terminal with account" +msgstr "Terminál agenta s výběrem účtu" + +msgid "Agent terminal with account…" +msgstr "Terminál agenta s výběrem účtu…" + msgid "Agent usage rankings" msgstr "Žebříček využití agentů" @@ -3715,6 +3724,9 @@ msgstr "Relace chatu nenalezena" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Plochy chatu: zprávy, uvažování, návrhy" +msgid "Chat with account" +msgstr "Chat s účtem" + msgid "Check again" msgstr "Zkontrolovat znovu" @@ -4116,6 +4128,9 @@ msgstr "Zavřít okno" msgid "Close modal backdrop" msgstr "Zavřít pozadí okna" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Ukončit pouze tohoto nečinného agenta a přepnout účet. Nejprve dokončete práci na pozadí a uložte neodeslaný koncept." + msgid "Close or delete the current workspace" msgstr "Zavřít nebo smazat aktuální pracovní prostor" @@ -4522,6 +4537,9 @@ msgstr "Potvrdit před ukončením" msgid "Confirm switch" msgstr "Potvrdit změnu" +msgid "Confirm that this agent can close safely before switching." +msgstr "Před přepnutím potvrďte, že lze tohoto agenta bezpečně ukončit." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Konflikty s {0}" @@ -5089,6 +5107,9 @@ msgstr "Soubor se nepodařilo smazat" msgid "Could not delete this page" msgstr "Tuto stránku se nepodařilo smazat" +msgid "Could not discard the queued message." +msgstr "Zprávu ve frontě se nepodařilo zahodit." + msgid "Could not disconnect." msgstr "Odpojení se nezdařilo." @@ -5104,6 +5125,9 @@ msgstr "Nepodařilo se opustit frontu" msgid "Could not list directory" msgstr "Nepodařilo se vypsat adresář" +msgid "Could not load accounts" +msgstr "Účty se nepodařilo načíst" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Nepodařilo se načíst agenty z {0}" @@ -5189,6 +5213,9 @@ msgstr "Nepodařilo se obnovit" msgid "Could not read MCP servers." msgstr "MCP servery se nepodařilo načíst." +msgid "Could not read queued messages." +msgstr "Zprávy ve frontě se nepodařilo přečíst." + msgid "Could not read selected file" msgstr "Vybraný soubor se nepodařilo přečíst" @@ -5204,6 +5231,9 @@ msgstr "Nepodařilo se zaznamenat cloudový pracovní prostor" msgid "Could not record environment" msgstr "Prostředí se nepodařilo uložit" +msgid "Could not refresh usage" +msgstr "Využití se nepodařilo obnovit" + msgid "Could not remove access" msgstr "Přístup se nepodařilo odebrat" @@ -5234,6 +5264,9 @@ msgstr "Pokračování se nezdařilo" msgid "Could not resume the chat" msgstr "V chatu se nepodařilo pokračovat" +msgid "Could not resume this conversation" +msgstr "Tuto konverzaci se nepodařilo obnovit" + msgid "Could not send" msgstr "Nepodařilo se odeslat" @@ -5249,6 +5282,12 @@ msgstr "Nepodařilo se sdílet" msgid "Could not start agent" msgstr "Nepodařilo se spustit agenta" +msgid "Could not start agent terminal" +msgstr "Terminál agenta se nepodařilo spustit" + +msgid "Could not start chat" +msgstr "Chat se nepodařilo spustit" + msgid "Could not start checkout. Please try again." msgstr "Platbu se nepodařilo zahájit. Zkuste to znovu." @@ -5270,12 +5309,18 @@ msgstr "Nepodařilo se ho zastavit" msgid "Could not stop the agent" msgstr "Agenta se nepodařilo zastavit" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Agenta se nepodařilo zastavit. Zkontrolujte zprávy ve frontě nebo aktualizujte tohoto hostitele a zkuste to znovu." + msgid "Could not stop watching" msgstr "Nepodařilo se přestat sledovat" msgid "Could not submit prompt. Try again." msgstr "Prompt se nepodařilo odeslat. Zkuste to znovu." +msgid "Could not switch account" +msgstr "Účet se nepodařilo přepnout" + msgid "Could not take a screenshot" msgstr "Nepodařilo se pořídit snímek obrazovky" @@ -6442,6 +6487,9 @@ msgstr "Zahodit změny v souboru „{discardBasename}“?" msgid "Discard changes?" msgstr "Zahodit změny?" +msgid "Discard queued message" +msgstr "Zahodit zprávu ve frontě" + msgid "Discard recording" msgstr "Zahodit nahrávku" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braillův spinner" msgid "Loading" msgstr "Načítání" +msgid "Loading accounts…" +msgstr "Načítání účtů…" + msgid "Loading agent settings..." msgstr "Načítám nastavení agenta..." @@ -11111,6 +11162,9 @@ msgstr "Nenalezeni žádní autoři." msgid "No automations match" msgstr "Žádná automatizace neodpovídá" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Nejsou k dispozici žádné účty s předplatným. Přidejte účet nebo se přihlaste v části Využití a poté obnovte seznam." + msgid "No branches found" msgstr "Nenalezeny žádné větve" @@ -14431,6 +14485,12 @@ msgstr "Znovu otevřít zavřenou kartu" msgid "Reopen PR" msgstr "Znovu otevřít PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Znovu otevřít uloženou konverzaci ve stejném pracovním prostoru. Žádná zpráva se neodešle. Práce na pozadí se nepřenáší." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Znovu otevřít přesně tuto uloženou konverzaci s jiným účtem. Ostatní chaty zůstanou spuštěné. Žádná zpráva se neodešle." + msgid "Reopen thread" msgstr "Znovu otevřít vlákno" @@ -14787,6 +14847,12 @@ msgstr "Argumenty pro pokračování" msgid "Resume automation" msgstr "Pokračovat v automatizaci" +msgid "Resume conversation" +msgstr "Obnovit konverzaci" + +msgid "Resume with another account" +msgstr "Obnovit s jiným účtem" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Obnovuji {0}…" @@ -16719,12 +16785,18 @@ msgstr "Začněte konverzaci a zprávy se objeví tady" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Spustí novou relaci agenta s nedávným kontextem tohoto terminálu. Zdrojem pravdy zůstávají soubory v pracovním prostoru." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Spusťte nativní chat pomocí existujícího přihlášení. Obnovení zachová tento účet i pracovní složku." + msgid "Start a new agent session each run" msgstr "Při každém spuštění začít novou relaci agenta" msgid "Start a new chat" msgstr "Zahájit nový chat" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Spusťte nový terminál se stávajícím přihlášením. Ostatní chaty a výchozí účet zůstanou beze změny." + msgid "Start a session" msgstr "Spustit relaci" @@ -16746,6 +16818,9 @@ msgstr "Začněte prohlížet" msgid "Start building in two." msgstr "Začněte stavět ve dvou." +msgid "Start chat" +msgstr "Zahájit chat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Spouštějte kódovací agenty, sledujte je živě a kontrolujte diff z iPhonu nebo iPadu. K dispozici v App Storu; Android brzy." @@ -16773,6 +16848,9 @@ msgstr "Spusťte ji pomocí + v liště karet." msgid "Start or stop the workspace run command" msgstr "Spustit nebo zastavit spouštěcí příkaz pracovního prostoru" +msgid "Start terminal" +msgstr "Spustit terminál" + msgid "Start voice mode" msgstr "Spustit hlasový režim" @@ -16884,6 +16962,12 @@ msgstr "Zastavit {label}" msgid "Stop {name}" msgstr "Zastavit {name}" +msgid "Stop agent" +msgstr "Zastavit agenta" + +msgid "Stop agent and background work" +msgstr "Zastavit agenta a úlohy na pozadí" + msgid "Stop dictation" msgstr "Zastavit diktování" @@ -16903,6 +16987,9 @@ msgstr "Zastavit agenta a odeslat hned" msgid "Stop the agent before you edit a message" msgstr "Před úpravou zprávy zastavte agenta" +msgid "Stop this agent and its background work?" +msgstr "Zastavit tohoto agenta a jeho úlohy na pozadí?" + msgid "Stop watching" msgstr "Přestat sledovat" @@ -17044,6 +17131,9 @@ msgstr "Vytrvalost" msgid "Sustain · active days in 30" msgstr "Pravidelnost · aktivní dny z 30" +msgid "Switch account" +msgstr "Přepnout účet" + msgid "Switch agents. Keep your workflow" msgstr "Vyměňte agenta. Workflow zůstane" @@ -17792,6 +17882,12 @@ msgstr "Stejná aplikace běží na iPadu nativně, na výšku i na šířku." msgid "The scorecard" msgstr "Hodnocení" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Chat vybraného účtu se nepodařilo ověřit v uložených datech rozvržení. Tento pokus nic nespustil. Pokud je úložiště plné, uvolněte místo a poté přejmenujte tuto kartu, aby se před dalším pokusem uložilo její rozvržení. Pokud problém přetrvává, ponechte kartu otevřenou." + +msgid "The selected login changed. Choose an account again." +msgstr "Vybrané přihlášení se změnilo. Vyberte účet znovu." + msgid "The self-driving software factory" msgstr "Samořídící softwarová továrna" @@ -17870,6 +17966,9 @@ msgstr "Tyto příkazy se spustí automaticky při vytvoření pracovního prost msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Tyto složky stále obsahují vaše soubory, ale do nového Paradevu se samy nepřenesly." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Tyto zprávy nebyly odeslány. Zkopírujte, co potřebujete, a před pokračováním vyprázdněte frontu." + msgid "These ports are still in use" msgstr "Tyto porty se stále používají" @@ -17903,6 +18002,9 @@ msgstr "Tento agent neumí rozvětvit konverzaci" msgid "This agent can't run in a cloud workspace" msgstr "Tento agent nemůže běžet v cloudovém pracovním prostoru" +msgid "This agent configuration does not support account selection." +msgstr "Tato konfigurace agenta nepodporuje výběr účtu." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Tento agent už na vybraném zařízení neexistuje (jeho agenti mohli být resetováni). Běhy budou selhávat, dokud nevyberete jiného." @@ -17931,6 +18033,9 @@ msgstr "Tato automatizace je v jiné organizaci" msgid "This cannot be undone." msgstr "Nelze vrátit zpět." +msgid "This chat could not be opened with its saved account." +msgstr "Tento chat se nepodařilo otevřít s uloženým účtem." + msgid "This chat has ended." msgstr "Tento chat skončil." @@ -17958,6 +18063,12 @@ msgstr "Tento cloudový pracovní prostor nelze spustit" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Tento cloudový workspace se probouzí, což může po nečinnosti trvat až 30 sekund." +msgid "This conversation cannot be resumed with another account." +msgstr "Tuto konverzaci nelze obnovit s jiným účtem." + +msgid "This conversation is no longer available to resume." +msgstr "Tato konverzace již není k dispozici pro obnovení." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Tímto se smaže uložený scrollback používaný k obnovení po restartu nebo pádu." @@ -18000,6 +18111,9 @@ msgstr "Tato instalace GitHubu je už připojená k jiné organizaci Paradev. Od msgid "This host" msgstr "Tento host" +msgid "This host does not support account selection for native chats." +msgstr "Tento hostitel nepodporuje výběr účtu pro nativní chaty." + msgid "This host has not reported a version yet." msgstr "Tento hostitel zatím nenahlásil verzi." @@ -18162,6 +18276,9 @@ msgstr "Tento slug je již obsazený" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Tím se zastaví všechny spouštěče Teams ve vaší organizaci a z tenantu se odeberou odběry oznámení. Kdykoli se můžete připojit znovu." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Tím se zastaví proces agenta a všechny jeho úlohy na pozadí. Uložená konverzace zůstane dostupná. Nejprve zkontrolujte a zahoďte zprávy ve frontě. Poté můžete zvolit Pokračovat." + msgid "This subagent can't move to the background now" msgstr "Tento subagent se teď nedá přesunout na pozadí" @@ -18943,6 +19060,9 @@ msgstr "Pro úpravu konfigurace pracovního prostoru aktualizujte Superset na to msgid "update the branch prefix" msgstr "aktualizovat prefix větve" +msgid "Update this host to choose an account for a new terminal." +msgstr "Aktualizujte tohoto hostitele, abyste mohli vybrat účet pro nový terminál." + msgid "Update this host to message subagents" msgstr "Aktualizujte tohoto hostitele, abyste mohli psát subagentům" @@ -19034,6 +19154,9 @@ msgstr "Údaje o využití jsou zastaralé" msgid "Usage sections" msgstr "Sekce využití" +msgid "Usage unavailable" +msgstr "Údaje o využití nejsou k dispozici" + msgid "Usage unavailable." msgstr "Využití není dostupné." diff --git a/packages/i18n/locales/de/messages.po b/packages/i18n/locales/de/messages.po index a86ff612fcc..e2f6206f565 100644 --- a/packages/i18n/locales/de/messages.po +++ b/packages/i18n/locales/de/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} von {total}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} verbleibend" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} liegt nicht bei {installedAccountLogin}, wo die GitHub App dieser Organisation installiert ist." @@ -2064,6 +2067,12 @@ msgstr "Agenten-Sitzung gestartet" msgid "agent settings" msgstr "Agenten-Einstellungen" +msgid "Agent terminal with account" +msgstr "Agent-Terminal mit Konto" + +msgid "Agent terminal with account…" +msgstr "Agent-Terminal mit Konto…" + msgid "Agent usage rankings" msgstr "Ranglisten zur Agentennutzung" @@ -3715,6 +3724,9 @@ msgstr "Chat-Sitzung nicht gefunden" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Chat-Oberflächen: Nachrichten, Reasoning, Vorschläge" +msgid "Chat with account" +msgstr "Chat mit Konto" + msgid "Check again" msgstr "Erneut prüfen" @@ -4116,6 +4128,9 @@ msgstr "Modal schließen" msgid "Close modal backdrop" msgstr "Modal-Hintergrund schließen" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Nur diesen inaktiven Agenten schließen und das Konto wechseln. Beenden Sie zuerst Hintergrundaufgaben und speichern Sie ungesendete Entwürfe." + msgid "Close or delete the current workspace" msgstr "Den aktuellen Arbeitsbereich schließen oder löschen" @@ -4522,6 +4537,9 @@ msgstr "Vor dem Beenden bestätigen" msgid "Confirm switch" msgstr "Wechsel bestätigen" +msgid "Confirm that this agent can close safely before switching." +msgstr "Bestätigen Sie vor dem Wechsel, dass dieser Agent sicher geschlossen werden kann." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Konflikte mit {0}" @@ -5089,6 +5107,9 @@ msgstr "Datei konnte nicht gelöscht werden" msgid "Could not delete this page" msgstr "Diese Seite konnte nicht gelöscht werden" +msgid "Could not discard the queued message." +msgstr "Die Nachricht in der Warteschlange konnte nicht verworfen werden." + msgid "Could not disconnect." msgstr "Trennen fehlgeschlagen." @@ -5104,6 +5125,9 @@ msgstr "Warteschlange konnte nicht verlassen werden" msgid "Could not list directory" msgstr "Verzeichnis konnte nicht gelistet werden" +msgid "Could not load accounts" +msgstr "Konten konnten nicht geladen werden" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Agenten von {0} konnten nicht geladen werden" @@ -5189,6 +5213,9 @@ msgstr "Reaktivierung nicht möglich" msgid "Could not read MCP servers." msgstr "MCP-Server konnten nicht gelesen werden." +msgid "Could not read queued messages." +msgstr "Nachrichten in der Warteschlange konnten nicht gelesen werden." + msgid "Could not read selected file" msgstr "Ausgewählte Datei konnte nicht gelesen werden" @@ -5204,6 +5231,9 @@ msgstr "Cloud-Arbeitsbereich konnte nicht erfasst werden" msgid "Could not record environment" msgstr "Umgebung konnte nicht gespeichert werden" +msgid "Could not refresh usage" +msgstr "Nutzungsdaten konnten nicht aktualisiert werden" + msgid "Could not remove access" msgstr "Zugriff konnte nicht entfernt werden" @@ -5234,6 +5264,9 @@ msgstr "Fortsetzen nicht möglich" msgid "Could not resume the chat" msgstr "Der Chat konnte nicht fortgesetzt werden" +msgid "Could not resume this conversation" +msgstr "Diese Unterhaltung konnte nicht fortgesetzt werden" + msgid "Could not send" msgstr "Senden nicht möglich" @@ -5249,6 +5282,12 @@ msgstr "Teilen nicht möglich" msgid "Could not start agent" msgstr "Agent konnte nicht gestartet werden" +msgid "Could not start agent terminal" +msgstr "Agent-Terminal konnte nicht gestartet werden" + +msgid "Could not start chat" +msgstr "Chat konnte nicht gestartet werden" + msgid "Could not start checkout. Please try again." msgstr "Checkout konnte nicht gestartet werden. Bitte versuche es erneut." @@ -5270,12 +5309,18 @@ msgstr "Konnte nicht beendet werden" msgid "Could not stop the agent" msgstr "Agent konnte nicht gestoppt werden" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Der Agent konnte nicht gestoppt werden. Prüfe die Nachrichten in der Warteschlange oder aktualisiere diesen Host und versuche es erneut." + msgid "Could not stop watching" msgstr "Beobachten ließ sich nicht beenden" msgid "Could not submit prompt. Try again." msgstr "Prompt konnte nicht eingereicht werden. Versuche es erneut." +msgid "Could not switch account" +msgstr "Konto konnte nicht gewechselt werden" + msgid "Could not take a screenshot" msgstr "Es konnte kein Screenshot erstellt werden" @@ -6442,6 +6487,9 @@ msgstr "Änderungen an \"{discardBasename}\" verwerfen?" msgid "Discard changes?" msgstr "Änderungen verwerfen?" +msgid "Discard queued message" +msgstr "Nachricht aus Warteschlange verwerfen" + msgid "Discard recording" msgstr "Aufnahme verwerfen" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille-Spinner" msgid "Loading" msgstr "Wird geladen" +msgid "Loading accounts…" +msgstr "Konten werden geladen…" + msgid "Loading agent settings..." msgstr "Agenten-Einstellungen werden geladen..." @@ -11111,6 +11162,9 @@ msgstr "Keine Autoren gefunden." msgid "No automations match" msgstr "Keine passenden Automatisierungen" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Keine verfügbaren Abonnementkonten. Füge unter Nutzung ein Konto hinzu oder melde dich an und aktualisiere dann die Liste." + msgid "No branches found" msgstr "Keine Branches gefunden" @@ -14431,6 +14485,12 @@ msgstr "Geschlossenen Tab wieder öffnen" msgid "Reopen PR" msgstr "PR wieder öffnen" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Die gespeicherte Unterhaltung im selben Arbeitsbereich erneut öffnen. Es wird keine Nachricht gesendet. Hintergrundaufgaben werden nicht übertragen." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Genau diese gespeicherte Unterhaltung mit einem anderen Konto öffnen. Andere Chats laufen weiter. Es wird keine Nachricht gesendet." + msgid "Reopen thread" msgstr "Thread wieder öffnen" @@ -14787,6 +14847,12 @@ msgstr "Resume-Argumente" msgid "Resume automation" msgstr "Automatisierung fortsetzen" +msgid "Resume conversation" +msgstr "Unterhaltung fortsetzen" + +msgid "Resume with another account" +msgstr "Mit anderem Konto fortsetzen" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "{0} wird fortgesetzt…" @@ -16719,12 +16785,18 @@ msgstr "Starte eine Unterhaltung, damit hier Nachrichten erscheinen" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Startet eine neue Agent-Sitzung mit dem jüngsten Kontext dieses Terminals. Maßgeblich bleiben die Dateien im Workspace." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Starte einen nativen Chat mit einer bestehenden Anmeldung. Bei der Wiederherstellung bleiben dieses Konto und dieser Arbeitsordner erhalten." + msgid "Start a new agent session each run" msgstr "Bei jedem Lauf eine neue Agent-Sitzung starten" msgid "Start a new chat" msgstr "Neuen Chat starten" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Starte ein neues Terminal mit einer bestehenden Anmeldung. Andere Chats und dein Standardkonto bleiben unverändert." + msgid "Start a session" msgstr "Sitzung starten" @@ -16746,6 +16818,9 @@ msgstr "Losbrowsen" msgid "Start building in two." msgstr "In zwei Schritten loslegen." +msgid "Start chat" +msgstr "Chat starten" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Coding-Agents starten, live verfolgen und den Diff auf iPhone oder iPad prüfen. Im App Store erhältlich; Android folgt bald." @@ -16773,6 +16848,9 @@ msgstr "Starte eine mit + in der Tab-Leiste." msgid "Start or stop the workspace run command" msgstr "Den Run-Befehl des Arbeitsbereichs starten oder stoppen" +msgid "Start terminal" +msgstr "Terminal starten" + msgid "Start voice mode" msgstr "Sprachmodus starten" @@ -16884,6 +16962,12 @@ msgstr "{label} stoppen" msgid "Stop {name}" msgstr "{name} stoppen" +msgid "Stop agent" +msgstr "Agent stoppen" + +msgid "Stop agent and background work" +msgstr "Agent und Hintergrundaufgaben stoppen" + msgid "Stop dictation" msgstr "Diktat beenden" @@ -16903,6 +16987,9 @@ msgstr "Agent stoppen und jetzt senden" msgid "Stop the agent before you edit a message" msgstr "Stoppe den Agenten, bevor du eine Nachricht bearbeitest" +msgid "Stop this agent and its background work?" +msgstr "Diesen Agenten und seine Hintergrundaufgaben stoppen?" + msgid "Stop watching" msgstr "Nicht mehr beobachten" @@ -17044,6 +17131,9 @@ msgstr "Ausdauer" msgid "Sustain · active days in 30" msgstr "Beständigkeit · aktive Tage von 30" +msgid "Switch account" +msgstr "Konto wechseln" + msgid "Switch agents. Keep your workflow" msgstr "Agenten wechseln. Workflow behalten" @@ -17792,6 +17882,12 @@ msgstr "Dieselbe App läuft nativ auf dem iPad, im Hoch- und im Querformat." msgid "The scorecard" msgstr "Der Scorecard" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Der Chat des ausgewählten Kontos konnte in den gespeicherten Layoutdaten nicht bestätigt werden. Bei diesem Versuch wurde nichts gestartet. Falls der Speicher voll ist, gib Speicherplatz frei und benenne diesen Tab um, um sein Layout vor dem nächsten Versuch zu speichern. Lass den Tab geöffnet, falls es weiterhin fehlschlägt." + +msgid "The selected login changed. Choose an account again." +msgstr "Die ausgewählte Anmeldung hat sich geändert. Wähle erneut ein Konto." + msgid "The self-driving software factory" msgstr "Die selbstfahrende Softwarefabrik" @@ -17870,6 +17966,9 @@ msgstr "Diese Befehle laufen automatisch, wenn ein Arbeitsbereich erstellt wird. msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Diese Ordner enthalten noch deine Dateien, wurden aber nicht automatisch in das neue Paradev übernommen." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Diese Nachrichten wurden nicht gesendet. Kopiere alles, was du brauchst, und leere dann die Warteschlange, bevor du fortfährst." + msgid "These ports are still in use" msgstr "Diese Ports sind noch in Benutzung" @@ -17903,6 +18002,9 @@ msgstr "Dieser Agent kann keine Unterhaltung verzweigen" msgid "This agent can't run in a cloud workspace" msgstr "Dieser Agent kann nicht in einem Cloud-Arbeitsbereich laufen" +msgid "This agent configuration does not support account selection." +msgstr "Diese Agent-Konfiguration unterstützt keine Kontoauswahl." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Diesen Agenten gibt es auf dem gewählten Gerät nicht mehr (seine Agenten wurden möglicherweise zurückgesetzt). Läufe schlagen fehl, bis du einen neuen auswählst." @@ -17931,6 +18033,9 @@ msgstr "Diese Automatisierung befindet sich in einer anderen Organisation" msgid "This cannot be undone." msgstr "Das lässt sich nicht rückgängig machen." +msgid "This chat could not be opened with its saved account." +msgstr "Dieser Chat konnte nicht mit seinem gespeicherten Konto geöffnet werden." + msgid "This chat has ended." msgstr "Dieser Chat ist beendet." @@ -17958,6 +18063,12 @@ msgstr "Dieser Cloud-Arbeitsbereich kann nicht starten" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Dieser Cloud-Workspace wird gerade aufgeweckt. Nach Inaktivität kann das bis zu 30 Sekunden dauern." +msgid "This conversation cannot be resumed with another account." +msgstr "Diese Unterhaltung kann nicht mit einem anderen Konto fortgesetzt werden." + +msgid "This conversation is no longer available to resume." +msgstr "Diese Unterhaltung kann nicht mehr fortgesetzt werden." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Damit wird der gespeicherte Scrollback gelöscht, der für Neustart- und Absturzwiederherstellung genutzt wird." @@ -18000,6 +18111,9 @@ msgstr "Diese GitHub-Installation ist bereits mit einer anderen Paradev-Organisa msgid "This host" msgstr "Dieser Host" +msgid "This host does not support account selection for native chats." +msgstr "Dieser Host unterstützt keine Kontoauswahl für native Chats." + msgid "This host has not reported a version yet." msgstr "Dieser Host hat noch keine Version gemeldet." @@ -18162,6 +18276,9 @@ msgstr "Dieser Slug ist bereits vergeben" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Das stoppt jeden Teams-Trigger in deiner Organisation und entfernt die Benachrichtigungs-Abos aus deinem Tenant. Du kannst jederzeit neu verbinden." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Dies stoppt den Agentenprozess und alle zugehörigen Hintergrundaufgaben. Deine gespeicherte Unterhaltung bleibt verfügbar. Prüfe zuerst die Nachrichten in der Warteschlange und verwirf sie. Danach kannst du Fortsetzen wählen." + msgid "This subagent can't move to the background now" msgstr "Dieser Subagent kann gerade nicht in den Hintergrund verschoben werden" @@ -18943,6 +19060,9 @@ msgstr "Aktualisiere Superset auf diesem Host, um die Arbeitsbereich-Konfigurati msgid "update the branch prefix" msgstr "das Branch-Präfix aktualisieren" +msgid "Update this host to choose an account for a new terminal." +msgstr "Aktualisiere diesen Host, um ein Konto für ein neues Terminal auszuwählen." + msgid "Update this host to message subagents" msgstr "Aktualisiere diesen Host, um Subagents Nachrichten zu senden" @@ -19034,6 +19154,9 @@ msgstr "Die Nutzungsdaten sind veraltet" msgid "Usage sections" msgstr "Nutzungsbereiche" +msgid "Usage unavailable" +msgstr "Nutzungsdaten nicht verfügbar" + msgid "Usage unavailable." msgstr "Nutzung nicht verfügbar." diff --git a/packages/i18n/locales/en/messages.po b/packages/i18n/locales/en/messages.po index b918c99ef3b..8cb88366155 100644 --- a/packages/i18n/locales/en/messages.po +++ b/packages/i18n/locales/en/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} of {total}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} remaining" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." @@ -2064,6 +2067,12 @@ msgstr "Agent session started" msgid "agent settings" msgstr "agent settings" +msgid "Agent terminal with account" +msgstr "Agent terminal with account" + +msgid "Agent terminal with account…" +msgstr "Agent terminal with account…" + msgid "Agent usage rankings" msgstr "Agent usage rankings" @@ -3715,6 +3724,9 @@ msgstr "Chat session not found" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Chat surfaces: messages, reasoning, suggestions" +msgid "Chat with account" +msgstr "Chat with account" + msgid "Check again" msgstr "Check again" @@ -4116,6 +4128,9 @@ msgstr "Close modal" msgid "Close modal backdrop" msgstr "Close modal backdrop" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Close only this idle agent and switch. Finish background work and save any unsent draft first." + msgid "Close or delete the current workspace" msgstr "Close or delete the current workspace" @@ -4522,6 +4537,9 @@ msgstr "Confirm before quitting" msgid "Confirm switch" msgstr "Confirm switch" +msgid "Confirm that this agent can close safely before switching." +msgstr "Confirm that this agent can close safely before switching." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Conflicts with {0}" @@ -5089,6 +5107,9 @@ msgstr "Could not delete file" msgid "Could not delete this page" msgstr "Could not delete this page" +msgid "Could not discard the queued message." +msgstr "Could not discard the queued message." + msgid "Could not disconnect." msgstr "Could not disconnect." @@ -5104,6 +5125,9 @@ msgstr "Could not leave the queue" msgid "Could not list directory" msgstr "Could not list directory" +msgid "Could not load accounts" +msgstr "Could not load accounts" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Could not load agents from {0}" @@ -5189,6 +5213,9 @@ msgstr "Could not reactivate" msgid "Could not read MCP servers." msgstr "Could not read MCP servers." +msgid "Could not read queued messages." +msgstr "Could not read queued messages." + msgid "Could not read selected file" msgstr "Could not read selected file" @@ -5204,6 +5231,9 @@ msgstr "Could not record cloud workspace" msgid "Could not record environment" msgstr "Could not record environment" +msgid "Could not refresh usage" +msgstr "Could not refresh usage" + msgid "Could not remove access" msgstr "Could not remove access" @@ -5234,6 +5264,9 @@ msgstr "Could not resume" msgid "Could not resume the chat" msgstr "Could not resume the chat" +msgid "Could not resume this conversation" +msgstr "Could not resume this conversation" + msgid "Could not send" msgstr "Could not send" @@ -5249,6 +5282,12 @@ msgstr "Could not share" msgid "Could not start agent" msgstr "Could not start agent" +msgid "Could not start agent terminal" +msgstr "Could not start agent terminal" + +msgid "Could not start chat" +msgstr "Could not start chat" + msgid "Could not start checkout. Please try again." msgstr "Could not start checkout. Please try again." @@ -5270,12 +5309,18 @@ msgstr "Could not stop it" msgid "Could not stop the agent" msgstr "Could not stop the agent" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Could not stop the agent. Review queued messages or update this host, then try again." + msgid "Could not stop watching" msgstr "Could not stop watching" msgid "Could not submit prompt. Try again." msgstr "Could not submit prompt. Try again." +msgid "Could not switch account" +msgstr "Could not switch account" + msgid "Could not take a screenshot" msgstr "Could not take a screenshot" @@ -6442,6 +6487,9 @@ msgstr "Discard changes to \"{discardBasename}\"?" msgid "Discard changes?" msgstr "Discard changes?" +msgid "Discard queued message" +msgstr "Discard queued message" + msgid "Discard recording" msgstr "Discard recording" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "Loading" +msgid "Loading accounts…" +msgstr "Loading accounts…" + msgid "Loading agent settings..." msgstr "Loading agent settings..." @@ -11111,6 +11162,9 @@ msgstr "No authors found." msgid "No automations match" msgstr "No automations match" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "No available subscription accounts. Add or sign in to an account in Usage, then refresh." + msgid "No branches found" msgstr "No branches found" @@ -14431,6 +14485,12 @@ msgstr "Reopen Closed Tab" msgid "Reopen PR" msgstr "Reopen PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." + msgid "Reopen thread" msgstr "Reopen thread" @@ -14787,6 +14847,12 @@ msgstr "Resume args" msgid "Resume automation" msgstr "Resume automation" +msgid "Resume conversation" +msgstr "Resume conversation" + +msgid "Resume with another account" +msgstr "Resume with another account" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Resuming {0}…" @@ -16719,12 +16785,18 @@ msgstr "Start a conversation to see messages here" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Start a native chat using an existing login. Recovery keeps this account and working folder." + msgid "Start a new agent session each run" msgstr "Start a new agent session each run" msgid "Start a new chat" msgstr "Start a new chat" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Start a new terminal using an existing login. Other chats and your default account stay unchanged." + msgid "Start a session" msgstr "Start a session" @@ -16746,6 +16818,9 @@ msgstr "Start browsing" msgid "Start building in two." msgstr "Start building in two." +msgid "Start chat" +msgstr "Start chat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." @@ -16773,6 +16848,9 @@ msgstr "Start one with + in the tab strip." msgid "Start or stop the workspace run command" msgstr "Start or stop the workspace run command" +msgid "Start terminal" +msgstr "Start terminal" + msgid "Start voice mode" msgstr "Start voice mode" @@ -16884,6 +16962,12 @@ msgstr "Stop {label}" msgid "Stop {name}" msgstr "Stop {name}" +msgid "Stop agent" +msgstr "Stop agent" + +msgid "Stop agent and background work" +msgstr "Stop agent and background work" + msgid "Stop dictation" msgstr "Stop dictation" @@ -16903,6 +16987,9 @@ msgstr "Stop the agent and send this now" msgid "Stop the agent before you edit a message" msgstr "Stop the agent before you edit a message" +msgid "Stop this agent and its background work?" +msgstr "Stop this agent and its background work?" + msgid "Stop watching" msgstr "Stop watching" @@ -17044,6 +17131,9 @@ msgstr "Sustain" msgid "Sustain · active days in 30" msgstr "Sustain · active days in 30" +msgid "Switch account" +msgstr "Switch account" + msgid "Switch agents. Keep your workflow" msgstr "Switch agents. Keep your workflow" @@ -17792,6 +17882,12 @@ msgstr "The same app runs natively on iPad, in portrait and landscape." msgid "The scorecard" msgstr "The scorecard" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." + +msgid "The selected login changed. Choose an account again." +msgstr "The selected login changed. Choose an account again." + msgid "The self-driving software factory" msgstr "The self-driving software factory" @@ -17870,6 +17966,9 @@ msgstr "These commands run automatically when a workspace is created. <0>Read ou msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "These folders still have your files, but they did not come over to the new Paradev on their own." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "These messages were not sent. Copy anything you need, then discard the queue before resuming." + msgid "These ports are still in use" msgstr "These ports are still in use" @@ -17903,6 +18002,9 @@ msgstr "This agent can't branch a conversation" msgid "This agent can't run in a cloud workspace" msgstr "This agent can't run in a cloud workspace" +msgid "This agent configuration does not support account selection." +msgstr "This agent configuration does not support account selection." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." @@ -17931,6 +18033,9 @@ msgstr "This automation is in another organization" msgid "This cannot be undone." msgstr "This cannot be undone." +msgid "This chat could not be opened with its saved account." +msgstr "This chat could not be opened with its saved account." + msgid "This chat has ended." msgstr "This chat has ended." @@ -17958,6 +18063,12 @@ msgstr "This cloud workspace can't start" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." +msgid "This conversation cannot be resumed with another account." +msgstr "This conversation cannot be resumed with another account." + +msgid "This conversation is no longer available to resume." +msgstr "This conversation is no longer available to resume." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "This deletes the saved scrollback used for reboot/crash recovery." @@ -18000,6 +18111,9 @@ msgstr "This GitHub installation is already connected to another Paradev organiz msgid "This host" msgstr "This host" +msgid "This host does not support account selection for native chats." +msgstr "This host does not support account selection for native chats." + msgid "This host has not reported a version yet." msgstr "This host has not reported a version yet." @@ -18162,6 +18276,9 @@ msgstr "This slug is already taken" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." + msgid "This subagent can't move to the background now" msgstr "This subagent can't move to the background now" @@ -18943,6 +19060,9 @@ msgstr "Update Superset on this host to edit its workspace config." msgid "update the branch prefix" msgstr "update the branch prefix" +msgid "Update this host to choose an account for a new terminal." +msgstr "Update this host to choose an account for a new terminal." + msgid "Update this host to message subagents" msgstr "Update this host to message subagents" @@ -19034,6 +19154,9 @@ msgstr "Usage is out of date" msgid "Usage sections" msgstr "Usage sections" +msgid "Usage unavailable" +msgstr "Usage unavailable" + msgid "Usage unavailable." msgstr "Usage unavailable." diff --git a/packages/i18n/locales/es/messages.po b/packages/i18n/locales/es/messages.po index e02476bb182..65d7c7c9515 100644 --- a/packages/i18n/locales/es/messages.po +++ b/packages/i18n/locales/es/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} de {total}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} restante" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} no está en {installedAccountLogin}, donde está instalada la GitHub App de esta organización." @@ -2064,6 +2067,12 @@ msgstr "Sesión de agente iniciada" msgid "agent settings" msgstr "configuración del agente" +msgid "Agent terminal with account" +msgstr "Terminal de agente con cuenta" + +msgid "Agent terminal with account…" +msgstr "Terminal de agente con cuenta…" + msgid "Agent usage rankings" msgstr "Rankings de uso de agentes" @@ -3715,6 +3724,9 @@ msgstr "Sesión de chat no encontrada" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Superficies de chat: mensajes, razonamiento, sugerencias" +msgid "Chat with account" +msgstr "Chat con cuenta" + msgid "Check again" msgstr "Volver a comprobar" @@ -4116,6 +4128,9 @@ msgstr "Cerrar el modal" msgid "Close modal backdrop" msgstr "Cerrar el fondo del modal" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Cerrar solo este agente inactivo y cambiar de cuenta. Primero termina el trabajo en segundo plano y guarda los borradores sin enviar." + msgid "Close or delete the current workspace" msgstr "Cerrar o eliminar el espacio de trabajo actual" @@ -4522,6 +4537,9 @@ msgstr "Confirmar antes de salir" msgid "Confirm switch" msgstr "Confirmar cambio" +msgid "Confirm that this agent can close safely before switching." +msgstr "Confirma que este agente se puede cerrar de forma segura antes de cambiar." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Conflictos con {0}" @@ -5089,6 +5107,9 @@ msgstr "No se pudo eliminar el archivo" msgid "Could not delete this page" msgstr "No se pudo eliminar esta página" +msgid "Could not discard the queued message." +msgstr "No se pudo descartar el mensaje en cola." + msgid "Could not disconnect." msgstr "No se pudo desconectar." @@ -5104,6 +5125,9 @@ msgstr "No se pudo salir de la cola" msgid "Could not list directory" msgstr "No se pudo listar el directorio" +msgid "Could not load accounts" +msgstr "No se pudieron cargar las cuentas" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "No se pudieron cargar los agentes de {0}" @@ -5189,6 +5213,9 @@ msgstr "No se pudo reactivar" msgid "Could not read MCP servers." msgstr "No se pudieron leer los servidores MCP." +msgid "Could not read queued messages." +msgstr "No se pudieron leer los mensajes en cola." + msgid "Could not read selected file" msgstr "No se pudo leer el archivo seleccionado" @@ -5204,6 +5231,9 @@ msgstr "No se pudo registrar el espacio de trabajo en la nube" msgid "Could not record environment" msgstr "No se pudo guardar el entorno" +msgid "Could not refresh usage" +msgstr "No se pudo actualizar el uso" + msgid "Could not remove access" msgstr "No se pudo quitar el acceso" @@ -5234,6 +5264,9 @@ msgstr "No se pudo reanudar" msgid "Could not resume the chat" msgstr "No se pudo reanudar el chat" +msgid "Could not resume this conversation" +msgstr "No se pudo reanudar esta conversación" + msgid "Could not send" msgstr "No se pudo enviar" @@ -5249,6 +5282,12 @@ msgstr "No se pudo compartir" msgid "Could not start agent" msgstr "No se pudo iniciar el agente" +msgid "Could not start agent terminal" +msgstr "No se pudo iniciar el terminal del agente" + +msgid "Could not start chat" +msgstr "No se pudo iniciar el chat" + msgid "Could not start checkout. Please try again." msgstr "No se pudo iniciar el pago. Inténtalo de nuevo." @@ -5270,12 +5309,18 @@ msgstr "No se pudo detener" msgid "Could not stop the agent" msgstr "No se pudo detener el agente" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "No se pudo detener el agente. Revisa los mensajes en cola o actualiza este host y vuelve a intentarlo." + msgid "Could not stop watching" msgstr "No se pudo dejar de observar" msgid "Could not submit prompt. Try again." msgstr "No se pudo enviar el prompt. Inténtalo de nuevo." +msgid "Could not switch account" +msgstr "No se pudo cambiar de cuenta" + msgid "Could not take a screenshot" msgstr "No se pudo hacer la captura" @@ -6442,6 +6487,9 @@ msgstr "¿Descartar los cambios de \"{discardBasename}\"?" msgid "Discard changes?" msgstr "¿Descartar los cambios?" +msgid "Discard queued message" +msgstr "Descartar mensaje en cola" + msgid "Discard recording" msgstr "Descartar la grabación" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "Cargando" +msgid "Loading accounts…" +msgstr "Cargando cuentas…" + msgid "Loading agent settings..." msgstr "Cargando la configuración del agente..." @@ -11111,6 +11162,9 @@ msgstr "No se encontraron autores." msgid "No automations match" msgstr "Ninguna automatización coincide" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "No hay cuentas de suscripción disponibles. Ve a Uso para añadir una cuenta o iniciar sesión en ella y luego actualiza." + msgid "No branches found" msgstr "No se encontraron ramas" @@ -14431,6 +14485,12 @@ msgstr "Reabrir pestaña cerrada" msgid "Reopen PR" msgstr "Reabrir PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Vuelve a abrir la conversación guardada en el mismo espacio de trabajo. No se envía ningún mensaje. El trabajo en segundo plano no se transfiere." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Reabrir esta misma conversación guardada con otra cuenta. Los demás chats siguen funcionando. No se envía ningún mensaje." + msgid "Reopen thread" msgstr "Reabrir el hilo" @@ -14787,6 +14847,12 @@ msgstr "Argumentos de reanudación" msgid "Resume automation" msgstr "Reanudar la automatización" +msgid "Resume conversation" +msgstr "Reanudar conversación" + +msgid "Resume with another account" +msgstr "Reanudar con otra cuenta" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Retomando {0}…" @@ -16719,12 +16785,18 @@ msgstr "Inicia una conversación para ver los mensajes aquí" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Inicia una nueva sesión de agente con el contexto reciente de este terminal. Los archivos del espacio de trabajo siguen siendo la fuente de verdad." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Inicia un chat nativo usando una cuenta ya conectada. La recuperación mantiene esta cuenta y carpeta de trabajo." + msgid "Start a new agent session each run" msgstr "Iniciar una nueva sesión de agente en cada ejecución" msgid "Start a new chat" msgstr "Iniciar un chat nuevo" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Inicia un nuevo terminal usando una cuenta ya conectada. Los demás chats y tu cuenta predeterminada no cambiarán." + msgid "Start a session" msgstr "Iniciar una sesión" @@ -16746,6 +16818,9 @@ msgstr "Empezar a navegar" msgid "Start building in two." msgstr "Empieza a construir en dos." +msgid "Start chat" +msgstr "Iniciar chat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Inicia agentes de código, síguelos en directo y revisa el diff desde tu iPhone o iPad. Disponible en la App Store; Android llegará pronto." @@ -16773,6 +16848,9 @@ msgstr "Inicia una con + en la barra de pestañas." msgid "Start or stop the workspace run command" msgstr "Iniciar o detener el comando de ejecución del espacio de trabajo" +msgid "Start terminal" +msgstr "Iniciar terminal" + msgid "Start voice mode" msgstr "Iniciar el modo de voz" @@ -16884,6 +16962,12 @@ msgstr "Detener {label}" msgid "Stop {name}" msgstr "Detener {name}" +msgid "Stop agent" +msgstr "Detener agente" + +msgid "Stop agent and background work" +msgstr "Detener agente y tareas en segundo plano" + msgid "Stop dictation" msgstr "Detener el dictado" @@ -16903,6 +16987,9 @@ msgstr "Detener el agente y enviar ahora" msgid "Stop the agent before you edit a message" msgstr "Detén el agente antes de editar un mensaje" +msgid "Stop this agent and its background work?" +msgstr "¿Detener este agente y sus tareas en segundo plano?" + msgid "Stop watching" msgstr "Dejar de observar" @@ -17044,6 +17131,9 @@ msgstr "Constancia" msgid "Sustain · active days in 30" msgstr "Constancia · días activos de 30" +msgid "Switch account" +msgstr "Cambiar de cuenta" + msgid "Switch agents. Keep your workflow" msgstr "Cambia de agente. Conserva tu flujo de trabajo" @@ -17792,6 +17882,12 @@ msgstr "La misma app funciona de forma nativa en iPad, en vertical y en horizont msgid "The scorecard" msgstr "El cuadro de resultados" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "No se pudo verificar el chat de la cuenta seleccionada en los datos de diseño guardados. Este intento no inició nada. Si el almacenamiento está lleno, libera espacio y cambia el nombre de esta pestaña para guardar su diseño antes de volver a intentarlo. Mantén esta pestaña abierta si el problema persiste." + +msgid "The selected login changed. Choose an account again." +msgstr "El inicio de sesión seleccionado ha cambiado. Vuelve a elegir una cuenta." + msgid "The self-driving software factory" msgstr "La fábrica de software autónoma" @@ -17870,6 +17966,9 @@ msgstr "Estos comandos se ejecutan automáticamente al crear un espacio de traba msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Estas carpetas aún tienen tus archivos, pero no se pasaron solas al nuevo Paradev." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Estos mensajes no se enviaron. Copia lo que necesites y luego vacía la cola antes de reanudar." + msgid "These ports are still in use" msgstr "Estos puertos siguen en uso" @@ -17903,6 +18002,9 @@ msgstr "Este agente no puede bifurcar una conversación" msgid "This agent can't run in a cloud workspace" msgstr "Este agente no puede ejecutarse en un espacio de trabajo en la nube" +msgid "This agent configuration does not support account selection." +msgstr "Esta configuración de agente no permite seleccionar una cuenta." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Este agente ya no existe en el dispositivo seleccionado (puede que sus agentes se hayan restablecido). Las ejecuciones fallarán hasta que elijas uno nuevo." @@ -17931,6 +18033,9 @@ msgstr "Esta automatización está en otra organización" msgid "This cannot be undone." msgstr "Esto no se puede deshacer." +msgid "This chat could not be opened with its saved account." +msgstr "No se pudo abrir este chat con su cuenta guardada." + msgid "This chat has ended." msgstr "Este chat ha terminado." @@ -17958,6 +18063,12 @@ msgstr "No se puede iniciar este espacio de trabajo en la nube" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Este espacio de trabajo en la nube se está reactivando, lo que puede tardar hasta 30 segundos tras un periodo de inactividad." +msgid "This conversation cannot be resumed with another account." +msgstr "Esta conversación no se puede reanudar con otra cuenta." + +msgid "This conversation is no longer available to resume." +msgstr "Esta conversación ya no está disponible para reanudarla." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Esto elimina el historial guardado que se usa para recuperarse tras un reinicio o un cierre inesperado." @@ -18000,6 +18111,9 @@ msgstr "Esta instalación de GitHub ya está conectada a otra organización de P msgid "This host" msgstr "Este host" +msgid "This host does not support account selection for native chats." +msgstr "Este host no admite la selección de cuentas para chats nativos." + msgid "This host has not reported a version yet." msgstr "Este host aún no ha informado de una versión." @@ -18162,6 +18276,9 @@ msgstr "Este slug ya está en uso" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Esto detiene todos los disparadores de Teams de tu organización y quita las suscripciones de notificaciones de tu tenant. Puedes volver a conectarlo cuando quieras." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Esto detiene el proceso del agente y sus tareas en segundo plano. La conversación guardada seguirá disponible. Primero revisa y descarta los mensajes en cola. Después puedes elegir Reanudar." + msgid "This subagent can't move to the background now" msgstr "Este subagente no se puede mover a segundo plano ahora" @@ -18943,6 +19060,9 @@ msgstr "Actualiza Superset en este host para editar la configuración del espaci msgid "update the branch prefix" msgstr "actualizar el prefijo de rama" +msgid "Update this host to choose an account for a new terminal." +msgstr "Actualiza este host para elegir una cuenta para un nuevo terminal." + msgid "Update this host to message subagents" msgstr "Actualiza este host para enviar mensajes a los subagentes" @@ -19034,6 +19154,9 @@ msgstr "Los datos de uso están desactualizados" msgid "Usage sections" msgstr "Secciones de uso" +msgid "Usage unavailable" +msgstr "Uso no disponible" + msgid "Usage unavailable." msgstr "Uso no disponible." diff --git a/packages/i18n/locales/fr/messages.po b/packages/i18n/locales/fr/messages.po index 15dd53cc216..54dd84cd2b6 100644 --- a/packages/i18n/locales/fr/messages.po +++ b/packages/i18n/locales/fr/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} sur {total}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} restants" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} n'est pas sur {installedAccountLogin}, où la GitHub App de cette organisation est installée." @@ -2064,6 +2067,12 @@ msgstr "Session d'agent démarrée" msgid "agent settings" msgstr "paramètres de l'agent" +msgid "Agent terminal with account" +msgstr "Terminal d’agent avec un compte" + +msgid "Agent terminal with account…" +msgstr "Terminal d’agent avec un compte…" + msgid "Agent usage rankings" msgstr "Classements d'utilisation des agents" @@ -3715,6 +3724,9 @@ msgstr "Session de chat introuvable" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Surfaces de chat : messages, raisonnement, suggestions" +msgid "Chat with account" +msgstr "Conversation avec un compte" + msgid "Check again" msgstr "Vérifier à nouveau" @@ -4116,6 +4128,9 @@ msgstr "Fermer la fenêtre" msgid "Close modal backdrop" msgstr "Fermer l'arrière-plan de la fenêtre" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Fermer uniquement cet agent inactif et changer de compte. Terminez d’abord les tâches en arrière-plan et enregistrez les brouillons non envoyés." + msgid "Close or delete the current workspace" msgstr "Fermer ou supprimer l'espace de travail actuel" @@ -4522,6 +4537,9 @@ msgstr "Confirmer avant de quitter" msgid "Confirm switch" msgstr "Confirmer le changement" +msgid "Confirm that this agent can close safely before switching." +msgstr "Confirmez que cet agent peut être fermé sans risque avant de changer de compte." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Conflits avec {0}" @@ -5089,6 +5107,9 @@ msgstr "Impossible de supprimer le fichier" msgid "Could not delete this page" msgstr "Impossible de supprimer cette page" +msgid "Could not discard the queued message." +msgstr "Impossible de supprimer le message en attente." + msgid "Could not disconnect." msgstr "Impossible de déconnecter." @@ -5104,6 +5125,9 @@ msgstr "Impossible de quitter la file" msgid "Could not list directory" msgstr "Impossible de lister le répertoire" +msgid "Could not load accounts" +msgstr "Impossible de charger les comptes" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Impossible de charger les agents depuis {0}" @@ -5189,6 +5213,9 @@ msgstr "Réactivation impossible" msgid "Could not read MCP servers." msgstr "Impossible de lire les serveurs MCP." +msgid "Could not read queued messages." +msgstr "Impossible de lire les messages en attente." + msgid "Could not read selected file" msgstr "Impossible de lire le fichier sélectionné" @@ -5204,6 +5231,9 @@ msgstr "Impossible d'enregistrer l'espace de travail cloud" msgid "Could not record environment" msgstr "Impossible d'enregistrer l'environnement" +msgid "Could not refresh usage" +msgstr "Impossible d’actualiser l’utilisation" + msgid "Could not remove access" msgstr "Impossible de retirer l’accès" @@ -5234,6 +5264,9 @@ msgstr "Impossible de reprendre" msgid "Could not resume the chat" msgstr "Impossible de reprendre la discussion" +msgid "Could not resume this conversation" +msgstr "Impossible de reprendre cette conversation" + msgid "Could not send" msgstr "Échec de l'envoi" @@ -5249,6 +5282,12 @@ msgstr "Impossible de partager" msgid "Could not start agent" msgstr "Impossible de démarrer l'agent" +msgid "Could not start agent terminal" +msgstr "Impossible de démarrer le terminal d’agent" + +msgid "Could not start chat" +msgstr "Impossible de démarrer la discussion" + msgid "Could not start checkout. Please try again." msgstr "Impossible de lancer le paiement. Veuillez réessayer." @@ -5270,12 +5309,18 @@ msgstr "Impossible de l'arrêter" msgid "Could not stop the agent" msgstr "Impossible d'arrêter l'agent" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Impossible d’arrêter l’agent. Vérifiez les messages en attente ou mettez cet hôte à jour, puis réessayez." + msgid "Could not stop watching" msgstr "Impossible d'arrêter la surveillance" msgid "Could not submit prompt. Try again." msgstr "Impossible de soumettre le prompt. Réessayez." +msgid "Could not switch account" +msgstr "Impossible de changer de compte" + msgid "Could not take a screenshot" msgstr "Impossible de prendre une capture d'écran" @@ -6442,6 +6487,9 @@ msgstr "Abandonner les modifications de « {discardBasename} » ?" msgid "Discard changes?" msgstr "Abandonner les modifications ?" +msgid "Discard queued message" +msgstr "Supprimer le message en attente" + msgid "Discard recording" msgstr "Supprimer l'enregistrement" @@ -9998,6 +10046,9 @@ msgstr "Chargeur · Spinner braille" msgid "Loading" msgstr "Chargement" +msgid "Loading accounts…" +msgstr "Chargement des comptes…" + msgid "Loading agent settings..." msgstr "Chargement des paramètres de l'agent..." @@ -11111,6 +11162,9 @@ msgstr "Aucun auteur trouvé." msgid "No automations match" msgstr "Aucune automatisation ne correspond" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Aucun compte avec abonnement disponible. Ajoutez un compte ou connectez-vous dans Utilisation, puis actualisez." + msgid "No branches found" msgstr "Aucune branche trouvée" @@ -14431,6 +14485,12 @@ msgstr "Rouvrir l'onglet fermé" msgid "Reopen PR" msgstr "Rouvrir la PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Rouvrir la conversation enregistrée dans le même espace de travail. Aucun message n’est envoyé. Les tâches en arrière-plan ne sont pas transférées." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Rouvrir exactement cette conversation enregistrée avec un autre compte. Les autres chats continuent de fonctionner. Aucun message n’est envoyé." + msgid "Reopen thread" msgstr "Rouvrir le fil" @@ -14787,6 +14847,12 @@ msgstr "Arguments de reprise" msgid "Resume automation" msgstr "Reprendre l'automatisation" +msgid "Resume conversation" +msgstr "Reprendre la conversation" + +msgid "Resume with another account" +msgstr "Reprendre avec un autre compte" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Reprise de {0}…" @@ -16719,12 +16785,18 @@ msgstr "Démarrez une conversation pour voir les messages ici" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Démarre une nouvelle session d'agent avec le contexte récent de ce terminal. Les fichiers de l'espace de travail restent la source de vérité." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Démarrez un chat natif avec une connexion existante. La récupération conserve ce compte et ce dossier de travail." + msgid "Start a new agent session each run" msgstr "Démarrer une nouvelle session d'agent à chaque exécution" msgid "Start a new chat" msgstr "Démarrer une nouvelle discussion" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Démarrez un nouveau terminal avec une connexion existante. Les autres discussions et votre compte par défaut restent inchangés." + msgid "Start a session" msgstr "Démarrer une session" @@ -16746,6 +16818,9 @@ msgstr "Commencer à naviguer" msgid "Start building in two." msgstr "Commencez à construire en deux." +msgid "Start chat" +msgstr "Démarrer le chat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Lancez des agents de code, suivez-les en direct et relisez le diff depuis votre iPhone ou iPad. Disponible sur l'App Store ; Android arrive bientôt." @@ -16773,6 +16848,9 @@ msgstr "Démarrez-en une avec + dans la barre d'onglets." msgid "Start or stop the workspace run command" msgstr "Démarrer ou arrêter la commande de l'espace de travail" +msgid "Start terminal" +msgstr "Démarrer le terminal" + msgid "Start voice mode" msgstr "Démarrer le mode vocal" @@ -16884,6 +16962,12 @@ msgstr "Arrêter {label}" msgid "Stop {name}" msgstr "Arrêter {name}" +msgid "Stop agent" +msgstr "Arrêter l’agent" + +msgid "Stop agent and background work" +msgstr "Arrêter l’agent et ses tâches en arrière-plan" + msgid "Stop dictation" msgstr "Arrêter la dictée" @@ -16903,6 +16987,9 @@ msgstr "Arrêter l'agent et envoyer maintenant" msgid "Stop the agent before you edit a message" msgstr "Arrêtez l'agent avant de modifier un message" +msgid "Stop this agent and its background work?" +msgstr "Arrêter cet agent et ses tâches en arrière-plan ?" + msgid "Stop watching" msgstr "Arrêter la surveillance" @@ -17044,6 +17131,9 @@ msgstr "Régularité" msgid "Sustain · active days in 30" msgstr "Régularité · jours actifs sur 30" +msgid "Switch account" +msgstr "Changer de compte" + msgid "Switch agents. Keep your workflow" msgstr "Changez d'agent. Gardez votre flux de travail" @@ -17792,6 +17882,12 @@ msgstr "La même app fonctionne nativement sur iPad, en portrait comme en paysag msgid "The scorecard" msgstr "Le bilan" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Le chat du compte sélectionné n’a pas pu être vérifié dans les données de disposition enregistrées. Cette tentative n’a rien lancé. Si le stockage est plein, libérez de l’espace, puis renommez cet onglet pour enregistrer sa disposition avant de réessayer. Gardez cet onglet ouvert si le problème persiste." + +msgid "The selected login changed. Choose an account again." +msgstr "La connexion sélectionnée a changé. Choisissez à nouveau un compte." + msgid "The self-driving software factory" msgstr "L'usine logicielle autonome" @@ -17870,6 +17966,9 @@ msgstr "Ces commandes s'exécutent automatiquement lorsqu'un espace de travail e msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Ces dossiers contiennent toujours vos fichiers, mais ils n’ont pas été transférés seuls vers le nouveau Paradev." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Ces messages n’ont pas été envoyés. Copiez ce dont vous avez besoin, puis videz la file d’attente avant de reprendre." + msgid "These ports are still in use" msgstr "Ces ports sont toujours utilisés" @@ -17903,6 +18002,9 @@ msgstr "Cet agent ne peut pas dupliquer une conversation" msgid "This agent can't run in a cloud workspace" msgstr "Cet agent ne peut pas s'exécuter dans un espace de travail cloud" +msgid "This agent configuration does not support account selection." +msgstr "Cette configuration d’agent ne permet pas de choisir un compte." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Cet agent n'existe plus sur l'appareil sélectionné (ses agents ont peut-être été réinitialisés). Les exécutions échoueront tant que vous n'en aurez pas choisi un nouveau." @@ -17931,6 +18033,9 @@ msgstr "Cette automatisation se trouve dans une autre organisation" msgid "This cannot be undone." msgstr "Cette action est irréversible." +msgid "This chat could not be opened with its saved account." +msgstr "Impossible d’ouvrir ce chat avec son compte enregistré." + msgid "This chat has ended." msgstr "Ce chat est terminé." @@ -17958,6 +18063,12 @@ msgstr "Impossible de démarrer cet espace de travail cloud" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Cet espace de travail cloud est en train de se réveiller, ce qui peut prendre jusqu’à 30 secondes après une période d’inactivité." +msgid "This conversation cannot be resumed with another account." +msgstr "Cette conversation ne peut pas être reprise avec un autre compte." + +msgid "This conversation is no longer available to resume." +msgstr "Cette conversation n’est plus disponible pour être reprise." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Cette action supprime l'historique de défilement enregistré, utilisé pour la reprise après redémarrage ou plantage." @@ -18000,6 +18111,9 @@ msgstr "Cette installation GitHub est déjà connectée à une autre organisatio msgid "This host" msgstr "Cet hôte" +msgid "This host does not support account selection for native chats." +msgstr "Cet hôte ne permet pas de sélectionner un compte pour les chats natifs." + msgid "This host has not reported a version yet." msgstr "Cet hôte n'a pas encore signalé de version." @@ -18162,6 +18276,9 @@ msgstr "Ce slug est déjà pris" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Cela arrête tous les déclencheurs Teams de votre organisation et supprime les abonnements aux notifications de votre tenant. Vous pouvez vous reconnecter à tout moment." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Cette action arrête le processus de l’agent et toutes ses tâches en arrière-plan. Votre conversation enregistrée reste disponible. Vérifiez et supprimez d’abord les messages en attente. Vous pourrez ensuite choisir Reprendre." + msgid "This subagent can't move to the background now" msgstr "Ce sous-agent ne peut pas passer en arrière-plan pour le moment" @@ -18943,6 +19060,9 @@ msgstr "Mettez à jour Superset sur cet hôte pour modifier la configuration de msgid "update the branch prefix" msgstr "mettre à jour le préfixe de branche" +msgid "Update this host to choose an account for a new terminal." +msgstr "Mettez à jour cet hôte pour choisir un compte pour un nouveau terminal." + msgid "Update this host to message subagents" msgstr "Mettez à jour cet hôte pour envoyer des messages aux sous-agents" @@ -19034,6 +19154,9 @@ msgstr "Les données d’utilisation ne sont plus à jour" msgid "Usage sections" msgstr "Sections d'utilisation" +msgid "Usage unavailable" +msgstr "Utilisation indisponible" + msgid "Usage unavailable." msgstr "Utilisation indisponible." diff --git a/packages/i18n/locales/id/messages.po b/packages/i18n/locales/id/messages.po index ff0ad63c017..b9c859cf241 100644 --- a/packages/i18n/locales/id/messages.po +++ b/packages/i18n/locales/id/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} dari {total}" +msgid "{remainingPercent} remaining" +msgstr "Sisa {remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} tidak ada di {installedAccountLogin}, tempat GitHub App organisasi ini dipasang." @@ -2064,6 +2067,12 @@ msgstr "Sesi agen dimulai" msgid "agent settings" msgstr "pengaturan agen" +msgid "Agent terminal with account" +msgstr "Terminal agen dengan akun" + +msgid "Agent terminal with account…" +msgstr "Terminal agen dengan akun…" + msgid "Agent usage rankings" msgstr "Peringkat penggunaan agen" @@ -3715,6 +3724,9 @@ msgstr "Sesi chat tidak ditemukan" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Permukaan chat: pesan, penalaran, saran" +msgid "Chat with account" +msgstr "Obrolan dengan akun" + msgid "Check again" msgstr "Periksa lagi" @@ -4116,6 +4128,9 @@ msgstr "Tutup modal" msgid "Close modal backdrop" msgstr "Tutup latar modal" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Tutup hanya agen yang sedang diam ini dan ganti akun. Selesaikan pekerjaan latar belakang dan simpan draf yang belum dikirim terlebih dahulu." + msgid "Close or delete the current workspace" msgstr "Tutup atau hapus workspace saat ini" @@ -4522,6 +4537,9 @@ msgstr "Konfirmasi sebelum keluar" msgid "Confirm switch" msgstr "Konfirmasi perpindahan" +msgid "Confirm that this agent can close safely before switching." +msgstr "Pastikan agen ini dapat ditutup dengan aman sebelum mengganti akun." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Konflik dengan {0}" @@ -5089,6 +5107,9 @@ msgstr "Tidak bisa menghapus file" msgid "Could not delete this page" msgstr "Tidak bisa menghapus halaman ini" +msgid "Could not discard the queued message." +msgstr "Pesan dalam antrean tidak dapat dibuang." + msgid "Could not disconnect." msgstr "Tidak dapat memutuskan." @@ -5104,6 +5125,9 @@ msgstr "Tidak bisa keluar dari antrean" msgid "Could not list directory" msgstr "Tidak bisa menampilkan isi direktori" +msgid "Could not load accounts" +msgstr "Tidak dapat memuat akun" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Tidak bisa memuat agen dari {0}" @@ -5189,6 +5213,9 @@ msgstr "Tidak bisa mengaktifkan kembali" msgid "Could not read MCP servers." msgstr "Tidak bisa membaca server MCP." +msgid "Could not read queued messages." +msgstr "Pesan dalam antrean tidak dapat dibaca." + msgid "Could not read selected file" msgstr "Tidak bisa membaca file yang dipilih" @@ -5204,6 +5231,9 @@ msgstr "Tidak bisa mencatat workspace cloud" msgid "Could not record environment" msgstr "Tidak dapat menyimpan environment" +msgid "Could not refresh usage" +msgstr "Gagal memperbarui penggunaan" + msgid "Could not remove access" msgstr "Tidak bisa menghapus akses" @@ -5234,6 +5264,9 @@ msgstr "Tidak dapat melanjutkan" msgid "Could not resume the chat" msgstr "Tidak dapat melanjutkan obrolan" +msgid "Could not resume this conversation" +msgstr "Tidak dapat melanjutkan percakapan ini" + msgid "Could not send" msgstr "Tidak bisa mengirim" @@ -5249,6 +5282,12 @@ msgstr "Tidak bisa membagikan" msgid "Could not start agent" msgstr "Tidak bisa memulai agen" +msgid "Could not start agent terminal" +msgstr "Tidak dapat memulai terminal agen" + +msgid "Could not start chat" +msgstr "Gagal memulai obrolan" + msgid "Could not start checkout. Please try again." msgstr "Tidak dapat memulai checkout. Coba lagi." @@ -5270,12 +5309,18 @@ msgstr "Tidak bisa dihentikan" msgid "Could not stop the agent" msgstr "Tidak dapat menghentikan agen" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Agen tidak dapat dihentikan. Tinjau pesan dalam antrean atau perbarui host ini, lalu coba lagi." + msgid "Could not stop watching" msgstr "Tidak bisa berhenti memantau" msgid "Could not submit prompt. Try again." msgstr "Tidak bisa mengirim prompt. Coba lagi." +msgid "Could not switch account" +msgstr "Gagal mengganti akun" + msgid "Could not take a screenshot" msgstr "Tidak bisa mengambil tangkapan layar" @@ -6442,6 +6487,9 @@ msgstr "Buang perubahan pada \"{discardBasename}\"?" msgid "Discard changes?" msgstr "Buang perubahan?" +msgid "Discard queued message" +msgstr "Buang pesan dalam antrean" + msgid "Discard recording" msgstr "Buang rekaman" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "Memuat" +msgid "Loading accounts…" +msgstr "Memuat akun…" + msgid "Loading agent settings..." msgstr "Memuat pengaturan agen..." @@ -11111,6 +11162,9 @@ msgstr "Tidak ada penulis ditemukan." msgid "No automations match" msgstr "Tidak ada otomatisasi yang cocok" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Tidak ada akun langganan yang tersedia. Tambahkan akun atau masuk di Penggunaan, lalu muat ulang." + msgid "No branches found" msgstr "Tidak ada branch ditemukan" @@ -14431,6 +14485,12 @@ msgstr "Buka Lagi Tab yang Ditutup" msgid "Reopen PR" msgstr "Buka Lagi PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Buka kembali percakapan tersimpan di ruang kerja yang sama. Tidak ada pesan yang dikirim. Pekerjaan latar belakang tidak dipindahkan." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Buka kembali percakapan tersimpan yang sama ini dengan akun lain. Chat lain tetap berjalan. Tidak ada pesan yang dikirim." + msgid "Reopen thread" msgstr "Buka lagi thread" @@ -14787,6 +14847,12 @@ msgstr "Argumen resume" msgid "Resume automation" msgstr "Lanjutkan otomatisasi" +msgid "Resume conversation" +msgstr "Lanjutkan percakapan" + +msgid "Resume with another account" +msgstr "Lanjutkan dengan akun lain" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Melanjutkan {0}…" @@ -16719,12 +16785,18 @@ msgstr "Mulai percakapan untuk melihat pesan di sini" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Memulai sesi agen baru dengan konteks terbaru dari terminal ini. Berkas di ruang kerja tetap menjadi sumber kebenaran." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Mulai obrolan bawaan menggunakan login yang ada. Pemulihan mempertahankan akun dan folder kerja ini." + msgid "Start a new agent session each run" msgstr "Mulai sesi agen baru setiap kali dijalankan" msgid "Start a new chat" msgstr "Mulai chat baru" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Mulai terminal baru menggunakan login yang sudah ada. Chat lain dan akun default Anda tidak berubah." + msgid "Start a session" msgstr "Mulai sesi" @@ -16746,6 +16818,9 @@ msgstr "Mulai menjelajah" msgid "Start building in two." msgstr "Mulai membangun dalam dua." +msgid "Start chat" +msgstr "Mulai chat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Mulai agen coding, ikuti secara langsung, dan tinjau diff dari iPhone atau iPad Anda. Tersedia di App Store; Android segera hadir." @@ -16773,6 +16848,9 @@ msgstr "Mulai satu dengan + di bilah tab." msgid "Start or stop the workspace run command" msgstr "Mulai atau hentikan perintah run workspace" +msgid "Start terminal" +msgstr "Mulai terminal" + msgid "Start voice mode" msgstr "Mulai mode suara" @@ -16884,6 +16962,12 @@ msgstr "Hentikan {label}" msgid "Stop {name}" msgstr "Hentikan {name}" +msgid "Stop agent" +msgstr "Hentikan agen" + +msgid "Stop agent and background work" +msgstr "Hentikan agen dan tugas latar belakang" + msgid "Stop dictation" msgstr "Hentikan dikte" @@ -16903,6 +16987,9 @@ msgstr "Hentikan agen dan kirim sekarang" msgid "Stop the agent before you edit a message" msgstr "Hentikan agen sebelum mengedit pesan" +msgid "Stop this agent and its background work?" +msgstr "Hentikan agen ini dan tugas latar belakangnya?" + msgid "Stop watching" msgstr "Berhenti memantau" @@ -17044,6 +17131,9 @@ msgstr "Konsistensi" msgid "Sustain · active days in 30" msgstr "Konsistensi · hari aktif dari 30" +msgid "Switch account" +msgstr "Ganti akun" + msgid "Switch agents. Keep your workflow" msgstr "Ganti agen. Pertahankan alur kerja Anda" @@ -17792,6 +17882,12 @@ msgstr "Aplikasi yang sama berjalan native di iPad, dalam mode potret dan lanska msgid "The scorecard" msgstr "Kartu skor" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Obrolan akun yang dipilih tidak dapat diverifikasi dalam data tata letak tersimpan. Tidak ada yang diluncurkan pada percobaan ini. Jika penyimpanan penuh, kosongkan ruang, lalu ganti nama tab ini untuk menyimpan tata letaknya sebelum mencoba lagi. Biarkan tab ini terbuka jika masih gagal." + +msgid "The selected login changed. Choose an account again." +msgstr "Login yang dipilih telah berubah. Pilih akun lagi." + msgid "The self-driving software factory" msgstr "Pabrik perangkat lunak yang menyetir sendiri" @@ -17870,6 +17966,9 @@ msgstr "Perintah ini berjalan otomatis saat workspace dibuat. <0>Baca dokumentas msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Folder ini masih berisi file Anda, tetapi tidak otomatis dipindahkan ke Paradev yang baru." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Pesan-pesan ini belum dikirim. Salin yang Anda perlukan, lalu kosongkan antrean sebelum melanjutkan." + msgid "These ports are still in use" msgstr "Port ini masih dipakai" @@ -17903,6 +18002,9 @@ msgstr "Agen ini tidak dapat mencabangkan percakapan" msgid "This agent can't run in a cloud workspace" msgstr "Agen ini tidak bisa berjalan di workspace cloud" +msgid "This agent configuration does not support account selection." +msgstr "Konfigurasi agen ini tidak mendukung pemilihan akun." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Agen ini sudah tidak ada di perangkat yang dipilih (agennya mungkin telah direset). Run akan gagal sampai Anda memilih yang baru." @@ -17931,6 +18033,9 @@ msgstr "Otomatisasi ini berada di organisasi lain" msgid "This cannot be undone." msgstr "Ini tidak bisa dibatalkan." +msgid "This chat could not be opened with its saved account." +msgstr "Obrolan ini tidak dapat dibuka dengan akun tersimpannya." + msgid "This chat has ended." msgstr "Chat ini telah berakhir." @@ -17958,6 +18063,12 @@ msgstr "Workspace cloud ini tidak dapat dimulai" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Workspace cloud ini sedang dibangunkan, yang bisa memakan waktu hingga 30 detik setelah tidak aktif." +msgid "This conversation cannot be resumed with another account." +msgstr "Percakapan ini tidak dapat dilanjutkan dengan akun lain." + +msgid "This conversation is no longer available to resume." +msgstr "Percakapan ini tidak lagi tersedia untuk dilanjutkan." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Ini menghapus scrollback tersimpan yang dipakai untuk pemulihan setelah reboot/crash." @@ -18000,6 +18111,9 @@ msgstr "Instalasi GitHub ini sudah terhubung ke organisasi Paradev lain. Putuska msgid "This host" msgstr "Host ini" +msgid "This host does not support account selection for native chats." +msgstr "Host ini tidak mendukung pemilihan akun untuk obrolan bawaan." + msgid "This host has not reported a version yet." msgstr "Host ini belum melaporkan versi." @@ -18162,6 +18276,9 @@ msgstr "Slug ini sudah dipakai" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Ini menghentikan setiap pemicu Teams di organisasi Anda dan menghapus langganan notifikasi dari tenant Anda. Anda bisa menghubungkan ulang kapan saja." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Tindakan ini menghentikan proses agen dan semua tugas latar belakang yang dikelolanya. Percakapan tersimpan Anda tetap tersedia. Tinjau dan buang pesan dalam antrean terlebih dahulu. Setelah itu, Anda dapat memilih Lanjutkan." + msgid "This subagent can't move to the background now" msgstr "Subagen ini tidak bisa dipindahkan ke latar belakang sekarang" @@ -18943,6 +19060,9 @@ msgstr "Perbarui Superset di host ini untuk mengedit konfigurasi workspace-nya." msgid "update the branch prefix" msgstr "memperbarui prefix branch" +msgid "Update this host to choose an account for a new terminal." +msgstr "Perbarui host ini untuk memilih akun bagi terminal baru." + msgid "Update this host to message subagents" msgstr "Perbarui host ini untuk mengirim pesan ke subagen" @@ -19034,6 +19154,9 @@ msgstr "Data penggunaan sudah tidak mutakhir" msgid "Usage sections" msgstr "Bagian penggunaan" +msgid "Usage unavailable" +msgstr "Data penggunaan tidak tersedia" + msgid "Usage unavailable." msgstr "Penggunaan tidak tersedia." diff --git a/packages/i18n/locales/it/messages.po b/packages/i18n/locales/it/messages.po index e1ad9453d04..c6175c8a0d9 100644 --- a/packages/i18n/locales/it/messages.po +++ b/packages/i18n/locales/it/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} di {total}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} rimanente" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} non è su {installedAccountLogin}, dove è installata la GitHub App di questa organizzazione." @@ -2064,6 +2067,12 @@ msgstr "Sessione dell'agente avviata" msgid "agent settings" msgstr "impostazioni dell'agente" +msgid "Agent terminal with account" +msgstr "Terminale agente con account" + +msgid "Agent terminal with account…" +msgstr "Terminale agente con account…" + msgid "Agent usage rankings" msgstr "Classifiche d'uso degli agenti" @@ -3715,6 +3724,9 @@ msgstr "Sessione di chat non trovata" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Superfici della chat: messaggi, ragionamento, suggerimenti" +msgid "Chat with account" +msgstr "Chat con account" + msgid "Check again" msgstr "Controlla di nuovo" @@ -4116,6 +4128,9 @@ msgstr "Chiudi la finestra" msgid "Close modal backdrop" msgstr "Chiudi lo sfondo della finestra" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Chiudi solo questo agente inattivo e cambia account. Prima termina le attività in background e salva le bozze non inviate." + msgid "Close or delete the current workspace" msgstr "Chiudi o elimina il workspace corrente" @@ -4522,6 +4537,9 @@ msgstr "Chiedi conferma prima di uscire" msgid "Confirm switch" msgstr "Conferma cambio" +msgid "Confirm that this agent can close safely before switching." +msgstr "Conferma che questo agente può essere chiuso in sicurezza prima di cambiare account." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Conflitti con {0}" @@ -5089,6 +5107,9 @@ msgstr "Impossibile eliminare il file" msgid "Could not delete this page" msgstr "Impossibile eliminare questa pagina" +msgid "Could not discard the queued message." +msgstr "Impossibile eliminare il messaggio in coda." + msgid "Could not disconnect." msgstr "Impossibile disconnettere." @@ -5104,6 +5125,9 @@ msgstr "Impossibile uscire dalla coda" msgid "Could not list directory" msgstr "Impossibile elencare la directory" +msgid "Could not load accounts" +msgstr "Impossibile caricare gli account" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Impossibile caricare gli agenti da {0}" @@ -5189,6 +5213,9 @@ msgstr "Impossibile riattivare" msgid "Could not read MCP servers." msgstr "Impossibile leggere i server MCP." +msgid "Could not read queued messages." +msgstr "Impossibile leggere i messaggi in coda." + msgid "Could not read selected file" msgstr "Impossibile leggere il file selezionato" @@ -5204,6 +5231,9 @@ msgstr "Impossibile registrare il workspace cloud" msgid "Could not record environment" msgstr "Impossibile salvare l'ambiente" +msgid "Could not refresh usage" +msgstr "Impossibile aggiornare l’utilizzo" + msgid "Could not remove access" msgstr "Impossibile rimuovere l’accesso" @@ -5234,6 +5264,9 @@ msgstr "Impossibile riprendere" msgid "Could not resume the chat" msgstr "Impossibile riprendere la chat" +msgid "Could not resume this conversation" +msgstr "Impossibile riprendere questa conversazione" + msgid "Could not send" msgstr "Impossibile inviare" @@ -5249,6 +5282,12 @@ msgstr "Impossibile condividere" msgid "Could not start agent" msgstr "Impossibile avviare l'agente" +msgid "Could not start agent terminal" +msgstr "Impossibile avviare il terminale agente" + +msgid "Could not start chat" +msgstr "Impossibile avviare la chat" + msgid "Could not start checkout. Please try again." msgstr "Impossibile avviare il checkout. Riprova." @@ -5270,12 +5309,18 @@ msgstr "Impossibile arrestarlo" msgid "Could not stop the agent" msgstr "Impossibile fermare l'agente" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Impossibile arrestare l’agente. Controlla i messaggi in coda o aggiorna questo host, poi riprova." + msgid "Could not stop watching" msgstr "Impossibile smettere di osservare" msgid "Could not submit prompt. Try again." msgstr "Impossibile inviare il prompt. Riprova." +msgid "Could not switch account" +msgstr "Impossibile cambiare account" + msgid "Could not take a screenshot" msgstr "Impossibile fare uno screenshot" @@ -6442,6 +6487,9 @@ msgstr "Scartare le modifiche a \"{discardBasename}\"?" msgid "Discard changes?" msgstr "Scartare le modifiche?" +msgid "Discard queued message" +msgstr "Elimina messaggio in coda" + msgid "Discard recording" msgstr "Scarta la registrazione" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "Caricamento" +msgid "Loading accounts…" +msgstr "Caricamento degli account…" + msgid "Loading agent settings..." msgstr "Caricamento delle impostazioni degli agenti..." @@ -11111,6 +11162,9 @@ msgstr "Nessun autore trovato." msgid "No automations match" msgstr "Nessuna automazione corrisponde" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Nessun account con abbonamento disponibile. Aggiungi un account o accedi in Utilizzo, poi aggiorna." + msgid "No branches found" msgstr "Nessun branch trovato" @@ -14431,6 +14485,12 @@ msgstr "Riapri la scheda chiusa" msgid "Reopen PR" msgstr "Riapri la PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Riapri la conversazione salvata nello stesso spazio di lavoro. Nessun messaggio viene inviato. Le attività in background non vengono trasferite." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Riapri esattamente questa conversazione salvata con un altro account. Le altre chat restano attive. Non viene inviato alcun messaggio." + msgid "Reopen thread" msgstr "Riapri il thread" @@ -14787,6 +14847,12 @@ msgstr "Argomenti di ripresa" msgid "Resume automation" msgstr "Riprendi l'automazione" +msgid "Resume conversation" +msgstr "Riprendi conversazione" + +msgid "Resume with another account" +msgstr "Riprendi con un altro account" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Ripresa di {0}…" @@ -16719,12 +16785,18 @@ msgstr "Avvia una conversazione per vedere i messaggi qui" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Avvia una nuova sessione dell'agente con il contesto recente di questo terminale. I file dello spazio di lavoro restano la fonte di verità." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Avvia una chat nativa usando un accesso esistente. Il ripristino mantiene questo account e la cartella di lavoro." + msgid "Start a new agent session each run" msgstr "Avvia una nuova sessione di agente a ogni esecuzione" msgid "Start a new chat" msgstr "Avvia una nuova chat" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Avvia un nuovo terminale con un accesso esistente. Le altre chat e il tuo account predefinito rimangono invariati." + msgid "Start a session" msgstr "Avvia una sessione" @@ -16746,6 +16818,9 @@ msgstr "Inizia a navigare" msgid "Start building in two." msgstr "Inizia a costruire in due." +msgid "Start chat" +msgstr "Avvia chat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Avvia gli agenti di coding, seguili in tempo reale e rivedi il diff dal tuo iPhone o iPad. Disponibile sull'App Store; Android arriverà presto." @@ -16773,6 +16848,9 @@ msgstr "Avviane una con + nella barra delle schede." msgid "Start or stop the workspace run command" msgstr "Avvia o arresta il comando di esecuzione del workspace" +msgid "Start terminal" +msgstr "Avvia terminale" + msgid "Start voice mode" msgstr "Avvia la modalità vocale" @@ -16884,6 +16962,12 @@ msgstr "Interrompi {label}" msgid "Stop {name}" msgstr "Interrompi {name}" +msgid "Stop agent" +msgstr "Arresta agente" + +msgid "Stop agent and background work" +msgstr "Arresta agente e attività in background" + msgid "Stop dictation" msgstr "Interrompi la dettatura" @@ -16903,6 +16987,9 @@ msgstr "Ferma l'agente e invia ora" msgid "Stop the agent before you edit a message" msgstr "Arresta l'agente prima di modificare un messaggio" +msgid "Stop this agent and its background work?" +msgstr "Arrestare questo agente e le sue attività in background?" + msgid "Stop watching" msgstr "Smetti di osservare" @@ -17044,6 +17131,9 @@ msgstr "Costanza" msgid "Sustain · active days in 30" msgstr "Costanza · giorni attivi su 30" +msgid "Switch account" +msgstr "Cambia account" + msgid "Switch agents. Keep your workflow" msgstr "Cambia agente. Mantieni il tuo flusso di lavoro" @@ -17792,6 +17882,12 @@ msgstr "La stessa app funziona in modo nativo su iPad, in verticale e in orizzon msgid "The scorecard" msgstr "La scheda di valutazione" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Non è stato possibile verificare la chat dell’account selezionato nei dati del layout salvati. Questo tentativo non ha avviato nulla. Se lo spazio di archiviazione è esaurito, libera spazio, poi rinomina questa scheda per salvarne il layout prima di riprovare. Tieni aperta questa scheda se il problema persiste." + +msgid "The selected login changed. Choose an account again." +msgstr "L’accesso selezionato è cambiato. Scegli di nuovo un account." + msgid "The self-driving software factory" msgstr "La fabbrica di software a guida autonoma" @@ -17870,6 +17966,9 @@ msgstr "Questi comandi vengono eseguiti automaticamente quando viene creato un w msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Queste cartelle contengono ancora i tuoi file, ma non sono state trasferite da sole nel nuovo Paradev." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Questi messaggi non sono stati inviati. Copia ciò che ti serve, poi svuota la coda prima di riprendere." + msgid "These ports are still in use" msgstr "Queste porte sono ancora in uso" @@ -17903,6 +18002,9 @@ msgstr "Questo agente non può diramare una conversazione" msgid "This agent can't run in a cloud workspace" msgstr "Questo agente non può essere eseguito in un workspace cloud" +msgid "This agent configuration does not support account selection." +msgstr "Questa configurazione dell’agente non supporta la selezione dell’account." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Questo agente non esiste più sul dispositivo selezionato (i suoi agenti potrebbero essere stati reimpostati). Le esecuzioni falliranno finché non ne scegli uno nuovo." @@ -17931,6 +18033,9 @@ msgstr "Questa automazione si trova in un'altra organizzazione" msgid "This cannot be undone." msgstr "L'operazione non può essere annullata." +msgid "This chat could not be opened with its saved account." +msgstr "Impossibile aprire questa chat con l’account salvato." + msgid "This chat has ended." msgstr "Questa chat è terminata." @@ -17958,6 +18063,12 @@ msgstr "Impossibile avviare questo workspace cloud" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Questo workspace cloud si sta riattivando: dopo un periodo di inattività possono volerci fino a 30 secondi." +msgid "This conversation cannot be resumed with another account." +msgstr "Questa conversazione non può essere ripresa con un altro account." + +msgid "This conversation is no longer available to resume." +msgstr "Questa conversazione non è più disponibile per la ripresa." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Questo elimina lo scrollback salvato usato per il ripristino dopo riavvio o crash." @@ -18000,6 +18111,9 @@ msgstr "Questa installazione GitHub è già collegata a un'altra organizzazione msgid "This host" msgstr "Questo host" +msgid "This host does not support account selection for native chats." +msgstr "Questo host non supporta la selezione dell’account per le chat native." + msgid "This host has not reported a version yet." msgstr "Questo host non ha ancora riportato una versione." @@ -18162,6 +18276,9 @@ msgstr "Questo slug è già in uso" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Questo ferma tutti i trigger di Teams nella tua organizzazione e rimuove le sottoscrizioni alle notifiche dal tuo tenant. Puoi ricollegarti in qualsiasi momento." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Questa azione arresta il processo dell’agente e tutte le sue attività in background. La conversazione salvata resta disponibile. Prima controlla ed elimina i messaggi in coda. Poi puoi scegliere Riprendi." + msgid "This subagent can't move to the background now" msgstr "Questo sottoagente non può essere spostato in background ora" @@ -18943,6 +19060,9 @@ msgstr "Aggiorna Superset su questo host per modificare la configurazione del wo msgid "update the branch prefix" msgstr "aggiornare il prefisso dei branch" +msgid "Update this host to choose an account for a new terminal." +msgstr "Aggiorna questo host per scegliere un account per un nuovo terminale." + msgid "Update this host to message subagents" msgstr "Aggiorna questo host per inviare messaggi ai sottoagenti" @@ -19034,6 +19154,9 @@ msgstr "I dati di utilizzo non sono aggiornati" msgid "Usage sections" msgstr "Sezioni di utilizzo" +msgid "Usage unavailable" +msgstr "Utilizzo non disponibile" + msgid "Usage unavailable." msgstr "Utilizzo non disponibile." diff --git a/packages/i18n/locales/ja/messages.po b/packages/i18n/locales/ja/messages.po index f9abfe53cc3..dfffebdfc27 100644 --- a/packages/i18n/locales/ja/messages.po +++ b/packages/i18n/locales/ja/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received}/{total}" +msgid "{remainingPercent} remaining" +msgstr "残り{remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} は、この組織の GitHub App がインストールされている {installedAccountLogin} にありません。" @@ -2064,6 +2067,12 @@ msgstr "エージェントセッションを開始しました" msgid "agent settings" msgstr "エージェント設定" +msgid "Agent terminal with account" +msgstr "アカウントを指定してエージェントターミナルを起動" + +msgid "Agent terminal with account…" +msgstr "アカウントを指定してエージェントターミナルを起動…" + msgid "Agent usage rankings" msgstr "エージェント使用量ランキング" @@ -3715,6 +3724,9 @@ msgstr "チャットセッションが見つかりません" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "チャットの構成要素: メッセージ、推論、提案" +msgid "Chat with account" +msgstr "アカウントを指定してチャット" + msgid "Check again" msgstr "再確認" @@ -4116,6 +4128,9 @@ msgstr "モーダルを閉じる" msgid "Close modal backdrop" msgstr "モーダルの背景を閉じる" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "この待機中のエージェントだけを終了してアカウントを切り替えます。先にバックグラウンド作業を完了し、未送信の下書きを保存してください。" + msgid "Close or delete the current workspace" msgstr "現在のワークスペースを閉じるか削除する" @@ -4522,6 +4537,9 @@ msgstr "終了前に確認" msgid "Confirm switch" msgstr "変更を確定" +msgid "Confirm that this agent can close safely before switching." +msgstr "切り替える前に、このエージェントを安全に終了できることを確認してください。" + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "{0} とコンフリクトしています" @@ -5089,6 +5107,9 @@ msgstr "ファイルを削除できませんでした" msgid "Could not delete this page" msgstr "このページを削除できませんでした" +msgid "Could not discard the queued message." +msgstr "キュー内のメッセージを破棄できませんでした。" + msgid "Could not disconnect." msgstr "接続を解除できませんでした。" @@ -5104,6 +5125,9 @@ msgstr "キューから抜けられませんでした" msgid "Could not list directory" msgstr "ディレクトリを一覧表示できませんでした" +msgid "Could not load accounts" +msgstr "アカウントを読み込めませんでした" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "{0}からエージェントを読み込めませんでした" @@ -5189,6 +5213,9 @@ msgstr "再有効化できませんでした" msgid "Could not read MCP servers." msgstr "MCPサーバーを読み込めませんでした。" +msgid "Could not read queued messages." +msgstr "キュー内のメッセージを読み取れませんでした。" + msgid "Could not read selected file" msgstr "選択したファイルを読み取れませんでした" @@ -5204,6 +5231,9 @@ msgstr "クラウドワークスペースを記録できませんでした" msgid "Could not record environment" msgstr "環境を保存できませんでした" +msgid "Could not refresh usage" +msgstr "使用量を更新できませんでした" + msgid "Could not remove access" msgstr "アクセスを削除できませんでした" @@ -5234,6 +5264,9 @@ msgstr "再開できませんでした" msgid "Could not resume the chat" msgstr "チャットを再開できませんでした" +msgid "Could not resume this conversation" +msgstr "この会話を再開できませんでした" + msgid "Could not send" msgstr "送信できませんでした" @@ -5249,6 +5282,12 @@ msgstr "共有できませんでした" msgid "Could not start agent" msgstr "エージェントを起動できませんでした" +msgid "Could not start agent terminal" +msgstr "エージェントターミナルを起動できませんでした" + +msgid "Could not start chat" +msgstr "チャットを開始できませんでした" + msgid "Could not start checkout. Please try again." msgstr "チェックアウトを開始できませんでした。もう一度お試しください。" @@ -5270,12 +5309,18 @@ msgstr "停止できませんでした" msgid "Could not stop the agent" msgstr "エージェントを停止できませんでした" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "エージェントを停止できませんでした。キュー内のメッセージを確認するか、このホストを更新してから再試行してください。" + msgid "Could not stop watching" msgstr "監視を停止できませんでした" msgid "Could not submit prompt. Try again." msgstr "プロンプトを送信できませんでした。もう一度お試しください。" +msgid "Could not switch account" +msgstr "アカウントを切り替えられませんでした" + msgid "Could not take a screenshot" msgstr "スクリーンショットを撮れませんでした" @@ -6442,6 +6487,9 @@ msgstr "「{discardBasename}」への変更を破棄しますか?" msgid "Discard changes?" msgstr "変更を破棄しますか?" +msgid "Discard queued message" +msgstr "キュー内のメッセージを破棄" + msgid "Discard recording" msgstr "録音を破棄" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "読み込み中" +msgid "Loading accounts…" +msgstr "アカウントを読み込み中…" + msgid "Loading agent settings..." msgstr "エージェント設定を読み込み中..." @@ -11111,6 +11162,9 @@ msgstr "作成者が見つかりません。" msgid "No automations match" msgstr "一致するオートメーションがありません" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "利用可能なサブスクリプションアカウントがありません。「使用量」でアカウントを追加するかログインしてから、更新してください。" + msgid "No branches found" msgstr "ブランチが見つかりません" @@ -14431,6 +14485,12 @@ msgstr "閉じたタブを再度開く" msgid "Reopen PR" msgstr "PRを再オープン" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "同じワークスペースで保存済みの会話を再度開きます。メッセージは送信されません。バックグラウンドの作業は引き継がれません。" + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "保存されたこの会話を別のアカウントで再度開きます。他のチャットは実行を継続します。メッセージは送信されません。" + msgid "Reopen thread" msgstr "スレッドを再開" @@ -14787,6 +14847,12 @@ msgstr "再開時の引数" msgid "Resume automation" msgstr "オートメーションを再開" +msgid "Resume conversation" +msgstr "会話を再開" + +msgid "Resume with another account" +msgstr "別のアカウントで再開" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "{0}を再開中…" @@ -16719,12 +16785,18 @@ msgstr "会話を始めるとここにメッセージが表示されます" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "このターミナルの直近のコンテキストを引き継いで、新しいエージェントセッションを開始します。ワークスペースのファイルが引き続き信頼できる情報源です。" +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "既存のログインを使ってネイティブチャットを開始します。復旧時もこのアカウントと作業フォルダを維持します。" + msgid "Start a new agent session each run" msgstr "実行ごとに新しいエージェントセッションを開始" msgid "Start a new chat" msgstr "新しいチャットを開始" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "既存のログインを使って新しいターミナルを起動します。他のチャットと既定のアカウントは変更されません。" + msgid "Start a session" msgstr "セッションを開始" @@ -16746,6 +16818,9 @@ msgstr "ブラウジングを開始" msgid "Start building in two." msgstr "ツーステップで開発を始めよう。" +msgid "Start chat" +msgstr "チャットを開始" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "iPhone や iPad からコーディングエージェントを起動し、ライブで見守り、差分をレビュー。App Store で配信中。Android 版は近日公開。" @@ -16773,6 +16848,9 @@ msgstr "タブバーの+から開始できます。" msgid "Start or stop the workspace run command" msgstr "ワークスペースの実行コマンドを開始または停止する" +msgid "Start terminal" +msgstr "ターミナルを起動" + msgid "Start voice mode" msgstr "音声モードを開始" @@ -16884,6 +16962,12 @@ msgstr "{label} を停止" msgid "Stop {name}" msgstr "{name} を停止" +msgid "Stop agent" +msgstr "エージェントを停止" + +msgid "Stop agent and background work" +msgstr "エージェントとバックグラウンド作業を停止" + msgid "Stop dictation" msgstr "音声入力を停止" @@ -16903,6 +16987,9 @@ msgstr "エージェントを停止して今すぐ送信" msgid "Stop the agent before you edit a message" msgstr "メッセージを編集する前にエージェントを停止してください" +msgid "Stop this agent and its background work?" +msgstr "このエージェントとバックグラウンド作業を停止しますか?" + msgid "Stop watching" msgstr "監視を停止" @@ -17044,6 +17131,9 @@ msgstr "継続" msgid "Sustain · active days in 30" msgstr "継続 · 30日間のアクティブ日数" +msgid "Switch account" +msgstr "アカウントを切り替え" + msgid "Switch agents. Keep your workflow" msgstr "エージェントは替える。ワークフローはそのまま" @@ -17792,6 +17882,12 @@ msgstr "同じアプリが iPad でネイティブに動作し、縦向きにも msgid "The scorecard" msgstr "スコアカード" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "選択したアカウントのチャットを、保存済みのレイアウトデータで確認できませんでした。今回の試行では何も起動していません。ストレージがいっぱいの場合は空き容量を確保し、このタブの名前を変更してレイアウトを保存してから再試行してください。それでも失敗する場合は、このタブを開いたままにしてください。" + +msgid "The selected login changed. Choose an account again." +msgstr "選択したログインが変更されました。アカウントを選び直してください。" + msgid "The self-driving software factory" msgstr "自動運転するソフトウェア工場" @@ -17870,6 +17966,9 @@ msgstr "これらのコマンドはワークスペース作成時に自動的に msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "これらのフォルダにはファイルが残っていますが、新しい Paradev に自動では移行されませんでした。" +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "これらのメッセージは送信されていません。必要な内容をコピーし、再開する前にキューを破棄してください。" + msgid "These ports are still in use" msgstr "これらのポートはまだ使用中です" @@ -17903,6 +18002,9 @@ msgstr "このエージェントは会話を分岐できません" msgid "This agent can't run in a cloud workspace" msgstr "このエージェントはクラウドワークスペースで実行できません" +msgid "This agent configuration does not support account selection." +msgstr "このエージェント設定ではアカウントを選択できません。" + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "選択したデバイスにこのエージェントは存在しません(エージェントがリセットされた可能性があります)。新しいエージェントを選ぶまで実行は失敗します。" @@ -17931,6 +18033,9 @@ msgstr "このオートメーションは別の組織にあります" msgid "This cannot be undone." msgstr "この操作は元に戻せません。" +msgid "This chat could not be opened with its saved account." +msgstr "保存されたアカウントでこのチャットを開けませんでした。" + msgid "This chat has ended." msgstr "このチャットは終了しました。" @@ -17958,6 +18063,12 @@ msgstr "このクラウドワークスペースを起動できません" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "このクラウドワークスペースを起動しています。しばらく使われていなかった場合は、最大30秒かかることがあります。" +msgid "This conversation cannot be resumed with another account." +msgstr "この会話は別のアカウントでは再開できません。" + +msgid "This conversation is no longer available to resume." +msgstr "この会話は再開できなくなりました。" + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "再起動やクラッシュからの復旧に使う保存済みスクロールバックを削除します。" @@ -18000,6 +18111,9 @@ msgstr "このGitHubインストールは別のParadev組織にすでに接続 msgid "This host" msgstr "このホスト" +msgid "This host does not support account selection for native chats." +msgstr "このホストはネイティブチャットのアカウント選択に対応していません。" + msgid "This host has not reported a version yet." msgstr "このホストはまだバージョンを報告していません。" @@ -18162,6 +18276,9 @@ msgstr "このスラッグは使用済みです" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "組織内のすべてのTeamsトリガーが停止し、テナントから通知サブスクリプションが削除されます。いつでも再接続できます。" +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "エージェントのプロセスと、そのプロセスが管理するバックグラウンド作業を停止します。保存済みの会話は引き続き利用できます。まずキュー内のメッセージを確認して破棄してください。その後で「再開」を選択できます。" + msgid "This subagent can't move to the background now" msgstr "このサブエージェントは今はバックグラウンドに移動できません" @@ -18943,6 +19060,9 @@ msgstr "ワークスペースの設定を編集するには、このホストの msgid "update the branch prefix" msgstr "ブランチのプレフィックスを更新する" +msgid "Update this host to choose an account for a new terminal." +msgstr "新しいターミナルのアカウントを選択するには、このホストを更新してください。" + msgid "Update this host to message subagents" msgstr "サブエージェントにメッセージを送るには、このホストを更新してください" @@ -19034,6 +19154,9 @@ msgstr "使用状況が古くなっています" msgid "Usage sections" msgstr "使用量セクション" +msgid "Usage unavailable" +msgstr "使用状況を取得できません" + msgid "Usage unavailable." msgstr "使用量を取得できません。" diff --git a/packages/i18n/locales/ko/messages.po b/packages/i18n/locales/ko/messages.po index 67ba9ad484c..1af22f47c3b 100644 --- a/packages/i18n/locales/ko/messages.po +++ b/packages/i18n/locales/ko/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{total} 중 {received}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} 남음" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName}은(는) 이 조직의 GitHub App이 설치된 {installedAccountLogin}에 없습니다." @@ -2064,6 +2067,12 @@ msgstr "에이전트 세션을 시작했습니다" msgid "agent settings" msgstr "에이전트 설정" +msgid "Agent terminal with account" +msgstr "계정을 선택해 에이전트 터미널 시작" + +msgid "Agent terminal with account…" +msgstr "계정을 선택해 에이전트 터미널 시작…" + msgid "Agent usage rankings" msgstr "에이전트 사용량 순위" @@ -3715,6 +3724,9 @@ msgstr "채팅 세션을 찾을 수 없습니다" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "채팅 화면: 메시지, 추론, 제안" +msgid "Chat with account" +msgstr "계정을 선택해 채팅" + msgid "Check again" msgstr "다시 확인" @@ -4116,6 +4128,9 @@ msgstr "모달 닫기" msgid "Close modal backdrop" msgstr "모달 배경 닫기" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "대기 중인 이 에이전트만 종료하고 계정을 전환합니다. 먼저 백그라운드 작업을 마치고 보내지 않은 초안을 저장하세요." + msgid "Close or delete the current workspace" msgstr "현재 워크스페이스를 닫거나 삭제합니다" @@ -4522,6 +4537,9 @@ msgstr "종료 전 확인" msgid "Confirm switch" msgstr "변경 확인" +msgid "Confirm that this agent can close safely before switching." +msgstr "전환하기 전에 이 에이전트를 안전하게 종료할 수 있는지 확인하세요." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "{0}과(와) 충돌" @@ -5089,6 +5107,9 @@ msgstr "파일을 삭제할 수 없습니다" msgid "Could not delete this page" msgstr "이 페이지를 삭제할 수 없습니다" +msgid "Could not discard the queued message." +msgstr "대기 중인 메시지를 삭제하지 못했습니다." + msgid "Could not disconnect." msgstr "연결을 해제하지 못했습니다." @@ -5104,6 +5125,9 @@ msgstr "대기열에서 나갈 수 없습니다" msgid "Could not list directory" msgstr "디렉터리를 나열할 수 없습니다" +msgid "Could not load accounts" +msgstr "계정을 불러오지 못했습니다" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "{0}에서 에이전트를 불러오지 못했습니다" @@ -5189,6 +5213,9 @@ msgstr "다시 활성화하지 못했습니다" msgid "Could not read MCP servers." msgstr "MCP 서버를 읽을 수 없습니다." +msgid "Could not read queued messages." +msgstr "대기 중인 메시지를 읽지 못했습니다." + msgid "Could not read selected file" msgstr "선택한 파일을 읽을 수 없습니다" @@ -5204,6 +5231,9 @@ msgstr "클라우드 워크스페이스를 기록할 수 없습니다" msgid "Could not record environment" msgstr "환경을 저장할 수 없습니다" +msgid "Could not refresh usage" +msgstr "사용량을 새로고침하지 못했습니다" + msgid "Could not remove access" msgstr "접근 권한을 제거할 수 없습니다" @@ -5234,6 +5264,9 @@ msgstr "재개할 수 없습니다" msgid "Could not resume the chat" msgstr "채팅을 재개할 수 없습니다" +msgid "Could not resume this conversation" +msgstr "이 대화를 재개할 수 없습니다" + msgid "Could not send" msgstr "보낼 수 없습니다" @@ -5249,6 +5282,12 @@ msgstr "공유할 수 없습니다" msgid "Could not start agent" msgstr "에이전트를 시작하지 못했습니다" +msgid "Could not start agent terminal" +msgstr "에이전트 터미널을 시작하지 못했습니다" + +msgid "Could not start chat" +msgstr "채팅을 시작하지 못했습니다" + msgid "Could not start checkout. Please try again." msgstr "결제를 시작할 수 없습니다. 다시 시도해 주세요." @@ -5270,12 +5309,18 @@ msgstr "중지할 수 없습니다" msgid "Could not stop the agent" msgstr "에이전트를 중지할 수 없습니다" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "에이전트를 중지하지 못했습니다. 대기 중인 메시지를 확인하거나 이 호스트를 업데이트한 후 다시 시도하세요." + msgid "Could not stop watching" msgstr "감시를 중지할 수 없습니다" msgid "Could not submit prompt. Try again." msgstr "프롬프트를 제출할 수 없습니다. 다시 시도하세요." +msgid "Could not switch account" +msgstr "계정을 전환하지 못했습니다" + msgid "Could not take a screenshot" msgstr "스크린샷을 찍을 수 없습니다" @@ -6442,6 +6487,9 @@ msgstr "\"{discardBasename}\"의 변경 사항을 버릴까요?" msgid "Discard changes?" msgstr "변경 사항을 버릴까요?" +msgid "Discard queued message" +msgstr "대기 중인 메시지 삭제" + msgid "Discard recording" msgstr "녹음 버리기" @@ -9998,6 +10046,9 @@ msgstr "로더 · 브라유 스피너" msgid "Loading" msgstr "불러오는 중" +msgid "Loading accounts…" +msgstr "계정 불러오는 중…" + msgid "Loading agent settings..." msgstr "에이전트 설정을 불러오는 중..." @@ -11111,6 +11162,9 @@ msgstr "작성자를 찾을 수 없습니다." msgid "No automations match" msgstr "일치하는 자동화가 없습니다" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "사용 가능한 구독 계정이 없습니다. 사용량에서 계정을 추가하거나 로그인한 후 새로고침하세요." + msgid "No branches found" msgstr "브랜치를 찾을 수 없습니다" @@ -14431,6 +14485,12 @@ msgstr "닫은 탭 다시 열기" msgid "Reopen PR" msgstr "PR 다시 열기" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "같은 워크스페이스에서 저장된 대화를 다시 엽니다. 메시지는 전송되지 않습니다. 백그라운드 작업은 이전되지 않습니다." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "저장된 이 대화를 다른 계정으로 다시 엽니다. 다른 채팅은 계속 실행됩니다. 메시지는 전송되지 않습니다." + msgid "Reopen thread" msgstr "스레드 다시 열기" @@ -14787,6 +14847,12 @@ msgstr "재개 인수" msgid "Resume automation" msgstr "자동화 재개" +msgid "Resume conversation" +msgstr "대화 재개" + +msgid "Resume with another account" +msgstr "다른 계정으로 재개" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "{0}을(를) 재개하는 중…" @@ -16719,12 +16785,18 @@ msgstr "대화를 시작하면 메시지가 여기에 표시됩니다" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "이 터미널의 최근 컨텍스트를 넘겨받아 새 에이전트 세션을 시작합니다. 워크스페이스의 파일이 여전히 기준입니다." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "기존 로그인을 사용해 네이티브 채팅을 시작합니다. 복구 시 이 계정과 작업 폴더가 유지됩니다." + msgid "Start a new agent session each run" msgstr "실행할 때마다 새 에이전트 세션 시작" msgid "Start a new chat" msgstr "새 채팅 시작" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "기존 로그인으로 새 터미널을 시작합니다. 다른 채팅과 기본 계정은 변경되지 않습니다." + msgid "Start a session" msgstr "세션 시작" @@ -16746,6 +16818,9 @@ msgstr "탐색 시작" msgid "Start building in two." msgstr "두 단계로 빌드를 시작하세요." +msgid "Start chat" +msgstr "채팅 시작" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "iPhone이나 iPad에서 코딩 에이전트를 시작하고, 실시간으로 따라가고, diff를 리뷰하세요. App Store에서 이용할 수 있으며 Android는 곧 출시됩니다." @@ -16773,6 +16848,9 @@ msgstr "탭 막대의 +로 시작하세요." msgid "Start or stop the workspace run command" msgstr "워크스페이스 실행 명령을 시작하거나 중지합니다" +msgid "Start terminal" +msgstr "터미널 시작" + msgid "Start voice mode" msgstr "음성 모드 시작" @@ -16884,6 +16962,12 @@ msgstr "{label} 중지" msgid "Stop {name}" msgstr "{name} 중지" +msgid "Stop agent" +msgstr "에이전트 중지" + +msgid "Stop agent and background work" +msgstr "에이전트 및 백그라운드 작업 중지" + msgid "Stop dictation" msgstr "받아쓰기 중지" @@ -16903,6 +16987,9 @@ msgstr "에이전트를 중지하고 지금 보내기" msgid "Stop the agent before you edit a message" msgstr "메시지를 편집하기 전에 에이전트를 중지하세요" +msgid "Stop this agent and its background work?" +msgstr "이 에이전트와 백그라운드 작업을 중지할까요?" + msgid "Stop watching" msgstr "감시 중지" @@ -17044,6 +17131,9 @@ msgstr "지속" msgid "Sustain · active days in 30" msgstr "지속성 · 30일 중 활동 일수" +msgid "Switch account" +msgstr "계정 전환" + msgid "Switch agents. Keep your workflow" msgstr "에이전트는 바꾸고, 워크플로는 그대로" @@ -17792,6 +17882,12 @@ msgstr "같은 앱이 iPad에서 네이티브로 실행되며 세로와 가로 msgid "The scorecard" msgstr "성적표" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "저장된 레이아웃 데이터에서 선택한 계정의 채팅을 확인하지 못했습니다. 이번 시도에서는 아무것도 실행되지 않았습니다. 저장 공간이 가득 찼다면 공간을 확보한 다음 이 탭의 이름을 바꿔 레이아웃을 저장하고 다시 시도하세요. 계속 실패하면 이 탭을 열어 두세요." + +msgid "The selected login changed. Choose an account again." +msgstr "선택한 로그인이 변경되었습니다. 계정을 다시 선택하세요." + msgid "The self-driving software factory" msgstr "자율 주행 소프트웨어 공장" @@ -17870,6 +17966,9 @@ msgstr "워크스페이스를 만들 때 이 명령이 자동으로 실행됩니 msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "이 폴더들에는 아직 파일이 있지만 새 Paradev로 자동으로 옮겨지지 않았습니다." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "이 메시지들은 전송되지 않았습니다. 필요한 내용을 복사한 다음 재개하기 전에 대기열을 비우세요." + msgid "These ports are still in use" msgstr "이 포트들은 아직 사용 중입니다" @@ -17903,6 +18002,9 @@ msgstr "이 에이전트는 대화를 분기할 수 없습니다" msgid "This agent can't run in a cloud workspace" msgstr "이 에이전트는 클라우드 워크스페이스에서 실행할 수 없습니다" +msgid "This agent configuration does not support account selection." +msgstr "이 에이전트 구성은 계정 선택을 지원하지 않습니다." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "이 에이전트는 선택한 기기에 더 이상 존재하지 않습니다 (에이전트가 초기화되었을 수 있습니다). 새 에이전트를 선택할 때까지 실행이 실패합니다." @@ -17931,6 +18033,9 @@ msgstr "이 자동화는 다른 조직에 있습니다" msgid "This cannot be undone." msgstr "되돌릴 수 없습니다." +msgid "This chat could not be opened with its saved account." +msgstr "저장된 계정으로 이 채팅을 열지 못했습니다." + msgid "This chat has ended." msgstr "이 채팅은 종료되었습니다." @@ -17958,6 +18063,12 @@ msgstr "이 클라우드 워크스페이스를 시작할 수 없습니다" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "이 클라우드 워크스페이스를 깨우는 중입니다. 한동안 사용하지 않았다면 최대 30초가 걸릴 수 있습니다." +msgid "This conversation cannot be resumed with another account." +msgstr "이 대화는 다른 계정으로 재개할 수 없습니다." + +msgid "This conversation is no longer available to resume." +msgstr "이 대화는 더 이상 재개할 수 없습니다." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "재부팅/충돌 복구에 사용하는 저장된 스크롤백을 삭제합니다." @@ -18000,6 +18111,9 @@ msgstr "이 GitHub 설치는 이미 다른 Paradev 조직에 연결되어 있습 msgid "This host" msgstr "이 호스트" +msgid "This host does not support account selection for native chats." +msgstr "이 호스트는 네이티브 채팅의 계정 선택을 지원하지 않습니다." + msgid "This host has not reported a version yet." msgstr "이 호스트는 아직 버전을 보고하지 않았습니다." @@ -18162,6 +18276,9 @@ msgstr "이미 사용 중인 슬러그입니다" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "조직의 모든 Teams 트리거가 중지되고 테넌트에서 알림 구독이 제거됩니다. 언제든지 다시 연결할 수 있습니다." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "에이전트 프로세스와 해당 프로세스가 관리하는 모든 백그라운드 작업이 중지됩니다. 저장된 대화는 계속 사용할 수 있습니다. 먼저 대기 중인 메시지를 검토하고 삭제하세요. 그런 다음 재개를 선택할 수 있습니다." + msgid "This subagent can't move to the background now" msgstr "이 서브 에이전트는 지금 백그라운드로 옮길 수 없습니다" @@ -18943,6 +19060,9 @@ msgstr "워크스페이스 설정을 편집하려면 이 호스트의 Superset msgid "update the branch prefix" msgstr "브랜치 접두사를 업데이트할" +msgid "Update this host to choose an account for a new terminal." +msgstr "새 터미널의 계정을 선택하려면 이 호스트를 업데이트하세요." + msgid "Update this host to message subagents" msgstr "서브 에이전트에게 메시지를 보내려면 이 호스트를 업데이트하세요" @@ -19034,6 +19154,9 @@ msgstr "사용량 정보가 오래되었습니다" msgid "Usage sections" msgstr "사용량 섹션" +msgid "Usage unavailable" +msgstr "사용량을 확인할 수 없음" + msgid "Usage unavailable." msgstr "사용량을 볼 수 없습니다." diff --git a/packages/i18n/locales/nl/messages.po b/packages/i18n/locales/nl/messages.po index ffbfa2641df..4e976dcd7f6 100644 --- a/packages/i18n/locales/nl/messages.po +++ b/packages/i18n/locales/nl/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} van {total}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} resterend" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} staat niet op {installedAccountLogin}, waar de GitHub App van deze organisatie is geïnstalleerd." @@ -2064,6 +2067,12 @@ msgstr "Agentsessie gestart" msgid "agent settings" msgstr "agentinstellingen" +msgid "Agent terminal with account" +msgstr "Agentterminal met account" + +msgid "Agent terminal with account…" +msgstr "Agentterminal met account…" + msgid "Agent usage rankings" msgstr "Ranglijst van agentgebruik" @@ -3715,6 +3724,9 @@ msgstr "Chatsessie niet gevonden" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Chatoppervlakken: berichten, redeneren, suggesties" +msgid "Chat with account" +msgstr "Chat met account" + msgid "Check again" msgstr "Opnieuw controleren" @@ -4116,6 +4128,9 @@ msgstr "Venster sluiten" msgid "Close modal backdrop" msgstr "Achtergrond van venster sluiten" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Sluit alleen deze inactieve agent en wissel van account. Rond eerst achtergrondwerk af en sla niet-verzonden concepten op." + msgid "Close or delete the current workspace" msgstr "De huidige werkruimte sluiten of verwijderen" @@ -4522,6 +4537,9 @@ msgstr "Bevestigen voor afsluiten" msgid "Confirm switch" msgstr "Wissel bevestigen" +msgid "Confirm that this agent can close safely before switching." +msgstr "Bevestig vóór het wisselen dat deze agent veilig kan worden afgesloten." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Conflicten met {0}" @@ -5089,6 +5107,9 @@ msgstr "Kan bestand niet verwijderen" msgid "Could not delete this page" msgstr "Kan deze pagina niet verwijderen" +msgid "Could not discard the queued message." +msgstr "Het bericht in de wachtrij kon niet worden verwijderd." + msgid "Could not disconnect." msgstr "Loskoppelen is mislukt." @@ -5104,6 +5125,9 @@ msgstr "Kan de wachtrij niet verlaten" msgid "Could not list directory" msgstr "Kan map niet uitlezen" +msgid "Could not load accounts" +msgstr "Accounts konden niet worden geladen" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Kan agents van {0} niet laden" @@ -5189,6 +5213,9 @@ msgstr "Reactiveren mislukt" msgid "Could not read MCP servers." msgstr "Kan MCP-servers niet lezen." +msgid "Could not read queued messages." +msgstr "Berichten in de wachtrij konden niet worden gelezen." + msgid "Could not read selected file" msgstr "Kan het gekozen bestand niet lezen" @@ -5204,6 +5231,9 @@ msgstr "Kan cloudwerkruimte niet vastleggen" msgid "Could not record environment" msgstr "Omgeving kon niet worden opgeslagen" +msgid "Could not refresh usage" +msgstr "Gebruik kon niet worden vernieuwd" + msgid "Could not remove access" msgstr "Kan toegang niet verwijderen" @@ -5234,6 +5264,9 @@ msgstr "Kan niet hervatten" msgid "Could not resume the chat" msgstr "Kan de chat niet hervatten" +msgid "Could not resume this conversation" +msgstr "Dit gesprek kon niet worden hervat" + msgid "Could not send" msgstr "Versturen mislukt" @@ -5249,6 +5282,12 @@ msgstr "Delen mislukt" msgid "Could not start agent" msgstr "Kan agent niet starten" +msgid "Could not start agent terminal" +msgstr "Agentterminal kon niet worden gestart" + +msgid "Could not start chat" +msgstr "Chat kon niet worden gestart" + msgid "Could not start checkout. Please try again." msgstr "Kon het afrekenen niet starten. Probeer het opnieuw." @@ -5270,12 +5309,18 @@ msgstr "Kon niet worden gestopt" msgid "Could not stop the agent" msgstr "Kan de agent niet stoppen" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "De agent kon niet worden gestopt. Controleer de berichten in de wachtrij of werk deze host bij en probeer het opnieuw." + msgid "Could not stop watching" msgstr "Kon niet stoppen met volgen" msgid "Could not submit prompt. Try again." msgstr "Kan prompt niet insturen. Probeer het opnieuw." +msgid "Could not switch account" +msgstr "Account kon niet worden gewisseld" + msgid "Could not take a screenshot" msgstr "Kan geen screenshot maken" @@ -6442,6 +6487,9 @@ msgstr "Wijzigingen in \"{discardBasename}\" verwerpen?" msgid "Discard changes?" msgstr "Wijzigingen verwerpen?" +msgid "Discard queued message" +msgstr "Bericht uit wachtrij verwijderen" + msgid "Discard recording" msgstr "Opname verwerpen" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille-spinner" msgid "Loading" msgstr "Laden" +msgid "Loading accounts…" +msgstr "Accounts laden…" + msgid "Loading agent settings..." msgstr "Agentinstellingen laden..." @@ -11111,6 +11162,9 @@ msgstr "Geen auteurs gevonden." msgid "No automations match" msgstr "Geen overeenkomende automatiseringen" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Geen beschikbare accounts met een abonnement. Voeg een account toe of meld je via Gebruik aan bij een account, en vernieuw daarna." + msgid "No branches found" msgstr "Geen branches gevonden" @@ -14431,6 +14485,12 @@ msgstr "Gesloten tabblad heropenen" msgid "Reopen PR" msgstr "PR heropenen" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Open het opgeslagen gesprek opnieuw in dezelfde werkruimte. Er wordt geen bericht verstuurd. Achtergrondtaken worden niet overgedragen." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Open precies dit opgeslagen gesprek opnieuw met een ander account. Andere chats blijven actief. Er wordt geen bericht verzonden." + msgid "Reopen thread" msgstr "Thread heropenen" @@ -14787,6 +14847,12 @@ msgstr "Resume-argumenten" msgid "Resume automation" msgstr "Automatisering hervatten" +msgid "Resume conversation" +msgstr "Gesprek hervatten" + +msgid "Resume with another account" +msgstr "Hervatten met een ander account" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "{0} hervatten…" @@ -16719,12 +16785,18 @@ msgstr "Begin een gesprek om hier berichten te zien" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Start een nieuwe agentsessie met de recente context van deze terminal. De bestanden in de workspace blijven de bron van waarheid." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Start een native chat met een bestaande aanmelding. Bij herstel blijven dit account en deze werkmap behouden." + msgid "Start a new agent session each run" msgstr "Start bij elke run een nieuwe agentsessie" msgid "Start a new chat" msgstr "Nieuwe chat starten" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Start een nieuwe terminal met een bestaande aanmelding. Andere chats en je standaardaccount blijven ongewijzigd." + msgid "Start a session" msgstr "Sessie starten" @@ -16746,6 +16818,9 @@ msgstr "Begin met browsen" msgid "Start building in two." msgstr "Begin met bouwen in twee." +msgid "Start chat" +msgstr "Chat starten" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Start coding agents, volg ze live en review de diff vanaf je iPhone of iPad. Beschikbaar in de App Store; Android komt binnenkort." @@ -16773,6 +16848,9 @@ msgstr "Start er een met + in de tabbladbalk." msgid "Start or stop the workspace run command" msgstr "Het run-commando van de werkruimte starten of stoppen" +msgid "Start terminal" +msgstr "Terminal starten" + msgid "Start voice mode" msgstr "Spraakmodus starten" @@ -16884,6 +16962,12 @@ msgstr "{label} stoppen" msgid "Stop {name}" msgstr "{name} stoppen" +msgid "Stop agent" +msgstr "Agent stoppen" + +msgid "Stop agent and background work" +msgstr "Agent en achtergrondtaken stoppen" + msgid "Stop dictation" msgstr "Dicteren stoppen" @@ -16903,6 +16987,9 @@ msgstr "Agent stoppen en nu verzenden" msgid "Stop the agent before you edit a message" msgstr "Stop de agent voordat je een bericht bewerkt" +msgid "Stop this agent and its background work?" +msgstr "Deze agent en zijn achtergrondtaken stoppen?" + msgid "Stop watching" msgstr "Stoppen met volgen" @@ -17044,6 +17131,9 @@ msgstr "Volhouden" msgid "Sustain · active days in 30" msgstr "Continuïteit · actieve dagen van 30" +msgid "Switch account" +msgstr "Account wisselen" + msgid "Switch agents. Keep your workflow" msgstr "Wissel van agent. Houd je workflow" @@ -17792,6 +17882,12 @@ msgstr "Dezelfde app draait native op iPad, staand en liggend." msgid "The scorecard" msgstr "De scorekaart" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "De chat van het geselecteerde account kon niet worden bevestigd in de opgeslagen indelingsgegevens. Deze poging heeft niets gestart. Als de opslag vol is, maak dan ruimte vrij en hernoem dit tabblad om de indeling op te slaan voordat je het opnieuw probeert. Houd dit tabblad open als het nog steeds mislukt." + +msgid "The selected login changed. Choose an account again." +msgstr "De geselecteerde aanmelding is gewijzigd. Kies opnieuw een account." + msgid "The self-driving software factory" msgstr "De zelfrijdende softwarefabriek" @@ -17870,6 +17966,9 @@ msgstr "Deze commando's draaien automatisch wanneer een werkruimte wordt aangema msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Deze mappen bevatten nog je bestanden, maar zijn niet vanzelf naar het nieuwe Paradev overgezet." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Deze berichten zijn niet verzonden. Kopieer wat je nodig hebt en maak de wachtrij leeg voordat je hervat." + msgid "These ports are still in use" msgstr "Deze poorten zijn nog in gebruik" @@ -17903,6 +18002,9 @@ msgstr "Deze agent kan een gesprek niet afsplitsen" msgid "This agent can't run in a cloud workspace" msgstr "Deze agent kan niet in een cloudwerkruimte draaien" +msgid "This agent configuration does not support account selection." +msgstr "Deze agentconfiguratie ondersteunt geen accountselectie." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Deze agent bestaat niet meer op het gekozen apparaat (de agents zijn mogelijk gereset). Runs mislukken totdat je een nieuwe kiest." @@ -17931,6 +18033,9 @@ msgstr "Deze automatisering staat in een andere organisatie" msgid "This cannot be undone." msgstr "Dit kan niet ongedaan worden gemaakt." +msgid "This chat could not be opened with its saved account." +msgstr "Deze chat kon niet worden geopend met het opgeslagen account." + msgid "This chat has ended." msgstr "Deze chat is beëindigd." @@ -17958,6 +18063,12 @@ msgstr "Deze cloudwerkruimte kan niet starten" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Deze cloudwerkruimte wordt gewekt. Na inactiviteit kan dat tot 30 seconden duren." +msgid "This conversation cannot be resumed with another account." +msgstr "Dit gesprek kan niet met een ander account worden hervat." + +msgid "This conversation is no longer available to resume." +msgstr "Dit gesprek is niet meer beschikbaar om te hervatten." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Hiermee wordt de opgeslagen scrollback voor herstel na herstart of crash verwijderd." @@ -18000,6 +18111,9 @@ msgstr "Deze GitHub-installatie is al gekoppeld aan een andere Paradev-organisat msgid "This host" msgstr "Deze host" +msgid "This host does not support account selection for native chats." +msgstr "Deze host ondersteunt geen accountselectie voor native chats." + msgid "This host has not reported a version yet." msgstr "Deze host heeft nog geen versie gemeld." @@ -18162,6 +18276,9 @@ msgstr "Deze slug is al bezet" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Hiermee stoppen alle Teams-triggers in je organisatie en worden de meldingsabonnementen uit je tenant verwijderd. Je kunt op elk moment opnieuw verbinden." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Dit stopt het agentproces en alle bijbehorende achtergrondtaken. Je opgeslagen gesprek blijft beschikbaar. Controleer en verwijder eerst de berichten in de wachtrij. Daarna kun je Hervatten kiezen." + msgid "This subagent can't move to the background now" msgstr "Deze subagent kan nu niet naar de achtergrond" @@ -18943,6 +19060,9 @@ msgstr "Werk Superset op deze host bij om de werkruimteconfiguratie te bewerken. msgid "update the branch prefix" msgstr "de branchprefix bijwerken" +msgid "Update this host to choose an account for a new terminal." +msgstr "Werk deze host bij om een account voor een nieuwe terminal te kiezen." + msgid "Update this host to message subagents" msgstr "Werk deze host bij om subagents berichten te sturen" @@ -19034,6 +19154,9 @@ msgstr "De gebruiksgegevens zijn verouderd" msgid "Usage sections" msgstr "Onderdelen van gebruik" +msgid "Usage unavailable" +msgstr "Gebruik niet beschikbaar" + msgid "Usage unavailable." msgstr "Gebruik niet beschikbaar." diff --git a/packages/i18n/locales/pl/messages.po b/packages/i18n/locales/pl/messages.po index 261b8b48857..8b17b287399 100644 --- a/packages/i18n/locales/pl/messages.po +++ b/packages/i18n/locales/pl/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} z {total}" +msgid "{remainingPercent} remaining" +msgstr "Pozostało {remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} nie należy do {installedAccountLogin}, gdzie zainstalowana jest GitHub App tej organizacji." @@ -2064,6 +2067,12 @@ msgstr "Sesja agenta uruchomiona" msgid "agent settings" msgstr "ustawienia agenta" +msgid "Agent terminal with account" +msgstr "Terminal agenta z wyborem konta" + +msgid "Agent terminal with account…" +msgstr "Terminal agenta z wyborem konta…" + msgid "Agent usage rankings" msgstr "Rankingi użycia agentów" @@ -3715,6 +3724,9 @@ msgstr "Nie znaleziono sesji czatu" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Powierzchnie czatu: wiadomości, rozumowanie, sugestie" +msgid "Chat with account" +msgstr "Czat z kontem" + msgid "Check again" msgstr "Sprawdź ponownie" @@ -4116,6 +4128,9 @@ msgstr "Zamknij okno" msgid "Close modal backdrop" msgstr "Zamknij tło okna" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Zamknij tylko tego bezczynnego agenta i zmień konto. Najpierw zakończ pracę w tle i zapisz niewysłane wersje robocze." + msgid "Close or delete the current workspace" msgstr "Zamknij lub usuń bieżący obszar roboczy" @@ -4522,6 +4537,9 @@ msgstr "Potwierdzaj przed zamknięciem" msgid "Confirm switch" msgstr "Potwierdź zmianę" +msgid "Confirm that this agent can close safely before switching." +msgstr "Przed zmianą konta potwierdź, że można bezpiecznie zamknąć tego agenta." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Konflikty z {0}" @@ -5089,6 +5107,9 @@ msgstr "Nie udało się usunąć pliku" msgid "Could not delete this page" msgstr "Nie udało się usunąć tej strony" +msgid "Could not discard the queued message." +msgstr "Nie udało się usunąć wiadomości z kolejki." + msgid "Could not disconnect." msgstr "Nie udało się odłączyć." @@ -5104,6 +5125,9 @@ msgstr "Nie udało się opuścić kolejki" msgid "Could not list directory" msgstr "Nie udało się wylistować katalogu" +msgid "Could not load accounts" +msgstr "Nie udało się wczytać kont" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Nie udało się wczytać agentów z {0}" @@ -5189,6 +5213,9 @@ msgstr "Nie udało się reaktywować" msgid "Could not read MCP servers." msgstr "Nie udało się odczytać serwerów MCP." +msgid "Could not read queued messages." +msgstr "Nie udało się odczytać wiadomości w kolejce." + msgid "Could not read selected file" msgstr "Nie udało się odczytać wybranego pliku" @@ -5204,6 +5231,9 @@ msgstr "Nie udało się zapisać obszaru roboczego w chmurze" msgid "Could not record environment" msgstr "Nie udało się zapisać środowiska" +msgid "Could not refresh usage" +msgstr "Nie udało się odświeżyć wykorzystania" + msgid "Could not remove access" msgstr "Nie udało się usunąć dostępu" @@ -5234,6 +5264,9 @@ msgstr "Nie udało się wznowić" msgid "Could not resume the chat" msgstr "Nie udało się wznowić czatu" +msgid "Could not resume this conversation" +msgstr "Nie udało się wznowić tej rozmowy" + msgid "Could not send" msgstr "Nie udało się wysłać" @@ -5249,6 +5282,12 @@ msgstr "Nie udało się udostępnić" msgid "Could not start agent" msgstr "Nie udało się uruchomić agenta" +msgid "Could not start agent terminal" +msgstr "Nie udało się uruchomić terminala agenta" + +msgid "Could not start chat" +msgstr "Nie udało się rozpocząć czatu" + msgid "Could not start checkout. Please try again." msgstr "Nie udało się rozpocząć płatności. Spróbuj ponownie." @@ -5270,12 +5309,18 @@ msgstr "Nie udało się zatrzymać" msgid "Could not stop the agent" msgstr "Nie udało się zatrzymać agenta" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Nie udało się zatrzymać agenta. Sprawdź wiadomości w kolejce lub zaktualizuj ten host, a następnie spróbuj ponownie." + msgid "Could not stop watching" msgstr "Nie udało się przestać obserwować" msgid "Could not submit prompt. Try again." msgstr "Nie udało się wysłać promptu. Spróbuj ponownie." +msgid "Could not switch account" +msgstr "Nie udało się zmienić konta" + msgid "Could not take a screenshot" msgstr "Nie udało się zrobić zrzutu ekranu" @@ -6442,6 +6487,9 @@ msgstr "Odrzucić zmiany w „{discardBasename}”?" msgid "Discard changes?" msgstr "Odrzucić zmiany?" +msgid "Discard queued message" +msgstr "Usuń wiadomość z kolejki" + msgid "Discard recording" msgstr "Odrzuć nagranie" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "Wczytywanie" +msgid "Loading accounts…" +msgstr "Wczytywanie kont…" + msgid "Loading agent settings..." msgstr "Wczytywanie ustawień agenta..." @@ -11111,6 +11162,9 @@ msgstr "Nie znaleziono autorów." msgid "No automations match" msgstr "Brak pasujących automatyzacji" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Brak dostępnych kont z subskrypcją. Dodaj konto lub zaloguj się w sekcji Użycie, a następnie odśwież." + msgid "No branches found" msgstr "Nie znaleziono gałęzi" @@ -14431,6 +14485,12 @@ msgstr "Otwórz ponownie zamkniętą kartę" msgid "Reopen PR" msgstr "Otwórz PR ponownie" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Otwórz ponownie zapisaną rozmowę w tym samym obszarze roboczym. Żadna wiadomość nie zostanie wysłana. Zadania w tle nie zostaną przeniesione." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Otwórz ponownie dokładnie tę zapisaną rozmowę na innym koncie. Pozostałe czaty nadal działają. Żadna wiadomość nie zostanie wysłana." + msgid "Reopen thread" msgstr "Otwórz wątek ponownie" @@ -14787,6 +14847,12 @@ msgstr "Argumenty wznawiania" msgid "Resume automation" msgstr "Wznów automatyzację" +msgid "Resume conversation" +msgstr "Wznów rozmowę" + +msgid "Resume with another account" +msgstr "Wznów z innym kontem" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Wznawianie {0}…" @@ -16719,12 +16785,18 @@ msgstr "Rozpocznij rozmowę, aby zobaczyć tu wiadomości" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Uruchamia nową sesję agenta z ostatnim kontekstem tego terminala. Źródłem prawdy pozostają pliki w przestrzeni roboczej." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Rozpocznij czat natywny z istniejącym logowaniem. Odzyskiwanie zachowuje to konto i folder roboczy." + msgid "Start a new agent session each run" msgstr "Rozpocznij nową sesję agenta przy każdym uruchomieniu" msgid "Start a new chat" msgstr "Rozpocznij nowy czat" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Uruchom nowy terminal, korzystając z istniejącego logowania. Inne czaty i konto domyślne pozostaną bez zmian." + msgid "Start a session" msgstr "Uruchom sesję" @@ -16746,6 +16818,9 @@ msgstr "Zacznij przeglądać" msgid "Start building in two." msgstr "Zacznij budować w dwóch." +msgid "Start chat" +msgstr "Rozpocznij czat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Uruchamiaj agentów kodujących, śledź ich na żywo i przeglądaj diff na iPhonie lub iPadzie. Dostępne w App Store; Android wkrótce." @@ -16773,6 +16848,9 @@ msgstr "Uruchom ją przyciskiem + na pasku kart." msgid "Start or stop the workspace run command" msgstr "Uruchom lub zatrzymaj polecenie obszaru roboczego" +msgid "Start terminal" +msgstr "Uruchom terminal" + msgid "Start voice mode" msgstr "Uruchom tryb głosowy" @@ -16884,6 +16962,12 @@ msgstr "Zatrzymaj {label}" msgid "Stop {name}" msgstr "Zatrzymaj {name}" +msgid "Stop agent" +msgstr "Zatrzymaj agenta" + +msgid "Stop agent and background work" +msgstr "Zatrzymaj agenta i zadania w tle" + msgid "Stop dictation" msgstr "Zatrzymaj dyktowanie" @@ -16903,6 +16987,9 @@ msgstr "Zatrzymaj agenta i wyślij teraz" msgid "Stop the agent before you edit a message" msgstr "Zatrzymaj agenta przed edycją wiadomości" +msgid "Stop this agent and its background work?" +msgstr "Zatrzymać tego agenta i jego zadania w tle?" + msgid "Stop watching" msgstr "Przestań obserwować" @@ -17044,6 +17131,9 @@ msgstr "Regularność" msgid "Sustain · active days in 30" msgstr "Regularność · aktywne dni z 30" +msgid "Switch account" +msgstr "Zmień konto" + msgid "Switch agents. Keep your workflow" msgstr "Zmieniaj agentów. Zachowaj swój workflow" @@ -17792,6 +17882,12 @@ msgstr "Ta sama aplikacja działa natywnie na iPadzie, w pionie i w poziomie." msgid "The scorecard" msgstr "Karta wyników" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Nie udało się potwierdzić czatu wybranego konta w zapisanych danych układu. Ta próba niczego nie uruchomiła. Jeśli pamięć jest pełna, zwolnij miejsce, a następnie zmień nazwę tej karty, aby zapisać jej układ przed ponowną próbą. Pozostaw kartę otwartą, jeśli problem się powtarza." + +msgid "The selected login changed. Choose an account again." +msgstr "Wybrane dane logowania uległy zmianie. Wybierz konto ponownie." + msgid "The self-driving software factory" msgstr "Samojezdna fabryka oprogramowania" @@ -17870,6 +17966,9 @@ msgstr "Te polecenia uruchamiają się automatycznie przy tworzeniu obszaru robo msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Te foldery nadal zawierają Twoje pliki, ale nie zostały same przeniesione do nowego Paradev." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Te wiadomości nie zostały wysłane. Skopiuj potrzebne treści, a następnie opróżnij kolejkę przed wznowieniem." + msgid "These ports are still in use" msgstr "Te porty są nadal używane" @@ -17903,6 +18002,9 @@ msgstr "Ten agent nie może rozgałęzić rozmowy" msgid "This agent can't run in a cloud workspace" msgstr "Ten agent nie może działać w obszarze roboczym w chmurze" +msgid "This agent configuration does not support account selection." +msgstr "Ta konfiguracja agenta nie obsługuje wyboru konta." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Ten agent już nie istnieje na wybranym urządzeniu (jego agenci mogli zostać zresetowani). Uruchomienia będą kończyć się błędem, dopóki nie wybierzesz nowego." @@ -17931,6 +18033,9 @@ msgstr "Ta automatyzacja znajduje się w innej organizacji" msgid "This cannot be undone." msgstr "Tej operacji nie można cofnąć." +msgid "This chat could not be opened with its saved account." +msgstr "Nie udało się otworzyć tego czatu przy użyciu zapisanego konta." + msgid "This chat has ended." msgstr "Ten czat się zakończył." @@ -17958,6 +18063,12 @@ msgstr "Nie można uruchomić tego obszaru roboczego w chmurze" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Ten obszar roboczy w chmurze jest wybudzany. Po okresie bezczynności może to potrwać do 30 sekund." +msgid "This conversation cannot be resumed with another account." +msgstr "Nie można wznowić tej rozmowy z innym kontem." + +msgid "This conversation is no longer available to resume." +msgstr "Ta rozmowa nie jest już dostępna do wznowienia." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Usuwa to zapisany bufor przewijania używany do odzyskiwania po restarcie lub awarii." @@ -18000,6 +18111,9 @@ msgstr "Ta instalacja GitHub jest już połączona z inną organizacją Paradev. msgid "This host" msgstr "Ten host" +msgid "This host does not support account selection for native chats." +msgstr "Ten host nie obsługuje wyboru konta dla czatów natywnych." + msgid "This host has not reported a version yet." msgstr "Ten host nie zgłosił jeszcze wersji." @@ -18162,6 +18276,9 @@ msgstr "Ten slug jest już zajęty" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Zatrzyma to wszystkie wyzwalacze Teams w Twojej organizacji i usunie subskrypcje powiadomień z tenanta. Możesz połączyć ponownie w dowolnej chwili." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Spowoduje to zatrzymanie procesu agenta oraz wszystkich jego zadań w tle. Zapisana rozmowa pozostanie dostępna. Najpierw przejrzyj i usuń wiadomości z kolejki. Następnie możesz wybrać Wznów." + msgid "This subagent can't move to the background now" msgstr "Tego subagenta nie można teraz przenieść w tło" @@ -18943,6 +19060,9 @@ msgstr "Zaktualizuj Superset na tym hoście, aby edytować konfigurację obszaru msgid "update the branch prefix" msgstr "zaktualizować prefiksu gałęzi" +msgid "Update this host to choose an account for a new terminal." +msgstr "Zaktualizuj tego hosta, aby wybrać konto dla nowego terminala." + msgid "Update this host to message subagents" msgstr "Zaktualizuj tego hosta, aby wysyłać wiadomości do subagentów" @@ -19034,6 +19154,9 @@ msgstr "Dane o wykorzystaniu są nieaktualne" msgid "Usage sections" msgstr "Sekcje zużycia" +msgid "Usage unavailable" +msgstr "Dane użycia niedostępne" + msgid "Usage unavailable." msgstr "Zużycie niedostępne." diff --git a/packages/i18n/locales/pt-BR/messages.po b/packages/i18n/locales/pt-BR/messages.po index 133c44c3f9b..094cd5ef82c 100644 --- a/packages/i18n/locales/pt-BR/messages.po +++ b/packages/i18n/locales/pt-BR/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} de {total}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} restante" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} não está em {installedAccountLogin}, onde a GitHub App desta organização está instalada." @@ -2064,6 +2067,12 @@ msgstr "Sessão de agente iniciada" msgid "agent settings" msgstr "configurações do agente" +msgid "Agent terminal with account" +msgstr "Terminal de agente com conta" + +msgid "Agent terminal with account…" +msgstr "Terminal de agente com conta…" + msgid "Agent usage rankings" msgstr "Rankings de uso de agentes" @@ -3715,6 +3724,9 @@ msgstr "Sessão de chat não encontrada" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Superfícies de chat: mensagens, raciocínio, sugestões" +msgid "Chat with account" +msgstr "Conversa com conta" + msgid "Check again" msgstr "Verificar novamente" @@ -4116,6 +4128,9 @@ msgstr "Fechar modal" msgid "Close modal backdrop" msgstr "Fechar o fundo do modal" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Feche apenas este agente inativo e troque de conta. Primeiro conclua as tarefas em segundo plano e salve os rascunhos não enviados." + msgid "Close or delete the current workspace" msgstr "Fechar ou excluir a área de trabalho atual" @@ -4522,6 +4537,9 @@ msgstr "Confirmar antes de encerrar" msgid "Confirm switch" msgstr "Confirmar troca" +msgid "Confirm that this agent can close safely before switching." +msgstr "Confirme que este agente pode ser fechado com segurança antes de trocar de conta." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Conflitos com {0}" @@ -5089,6 +5107,9 @@ msgstr "Não foi possível excluir o arquivo" msgid "Could not delete this page" msgstr "Não foi possível excluir esta página" +msgid "Could not discard the queued message." +msgstr "Não foi possível descartar a mensagem na fila." + msgid "Could not disconnect." msgstr "Não foi possível desconectar." @@ -5104,6 +5125,9 @@ msgstr "Não foi possível sair da fila" msgid "Could not list directory" msgstr "Não foi possível listar o diretório" +msgid "Could not load accounts" +msgstr "Não foi possível carregar as contas" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Não foi possível carregar os agentes de {0}" @@ -5189,6 +5213,9 @@ msgstr "Não foi possível reativar" msgid "Could not read MCP servers." msgstr "Não foi possível ler os servidores MCP." +msgid "Could not read queued messages." +msgstr "Não foi possível ler as mensagens na fila." + msgid "Could not read selected file" msgstr "Não foi possível ler o arquivo selecionado" @@ -5204,6 +5231,9 @@ msgstr "Não foi possível registrar a área de trabalho na nuvem" msgid "Could not record environment" msgstr "Não foi possível salvar o ambiente" +msgid "Could not refresh usage" +msgstr "Não foi possível atualizar o uso" + msgid "Could not remove access" msgstr "Não foi possível remover o acesso" @@ -5234,6 +5264,9 @@ msgstr "Não foi possível retomar" msgid "Could not resume the chat" msgstr "Não foi possível retomar o chat" +msgid "Could not resume this conversation" +msgstr "Não foi possível retomar esta conversa" + msgid "Could not send" msgstr "Não foi possível enviar" @@ -5249,6 +5282,12 @@ msgstr "Não foi possível compartilhar" msgid "Could not start agent" msgstr "Não foi possível iniciar o agente" +msgid "Could not start agent terminal" +msgstr "Não foi possível iniciar o terminal do agente" + +msgid "Could not start chat" +msgstr "Não foi possível iniciar o chat" + msgid "Could not start checkout. Please try again." msgstr "Não foi possível iniciar o checkout. Tente novamente." @@ -5270,12 +5309,18 @@ msgstr "Não foi possível parar" msgid "Could not stop the agent" msgstr "Não foi possível parar o agente" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Não foi possível parar o agente. Revise as mensagens na fila ou atualize este host e tente novamente." + msgid "Could not stop watching" msgstr "Não foi possível parar de observar" msgid "Could not submit prompt. Try again." msgstr "Não foi possível enviar o prompt. Tente novamente." +msgid "Could not switch account" +msgstr "Não foi possível trocar de conta" + msgid "Could not take a screenshot" msgstr "Não foi possível fazer a captura de tela" @@ -6442,6 +6487,9 @@ msgstr "Descartar as alterações em \"{discardBasename}\"?" msgid "Discard changes?" msgstr "Descartar as alterações?" +msgid "Discard queued message" +msgstr "Descartar mensagem na fila" + msgid "Discard recording" msgstr "Descartar gravação" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "Carregando" +msgid "Loading accounts…" +msgstr "Carregando contas…" + msgid "Loading agent settings..." msgstr "Carregando as configurações do agente..." @@ -11111,6 +11162,9 @@ msgstr "Nenhum autor encontrado." msgid "No automations match" msgstr "Nenhuma automação corresponde" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Nenhuma conta de assinatura disponível. Adicione uma conta ou faça login em uma conta na seção Uso; depois, atualize a lista." + msgid "No branches found" msgstr "Nenhuma branch encontrada" @@ -14431,6 +14485,12 @@ msgstr "Reabrir aba fechada" msgid "Reopen PR" msgstr "Reabrir PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Reabra a conversa salva no mesmo espaço de trabalho. Nenhuma mensagem é enviada. As tarefas em segundo plano não são transferidas." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Reabra exatamente esta conversa salva com outra conta. Os outros chats continuam em execução. Nenhuma mensagem é enviada." + msgid "Reopen thread" msgstr "Reabrir thread" @@ -14787,6 +14847,12 @@ msgstr "Argumentos de retomada" msgid "Resume automation" msgstr "Retomar automação" +msgid "Resume conversation" +msgstr "Retomar conversa" + +msgid "Resume with another account" +msgstr "Retomar com outra conta" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Retomando {0}…" @@ -16719,12 +16785,18 @@ msgstr "Comece uma conversa para ver as mensagens aqui" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Inicia uma nova sessão de agente com o contexto recente deste terminal. Os arquivos do espaço de trabalho continuam sendo a fonte da verdade." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Inicie uma conversa nativa usando um login existente. A recuperação mantém esta conta e pasta de trabalho." + msgid "Start a new agent session each run" msgstr "Iniciar uma nova sessão de agente a cada execução" msgid "Start a new chat" msgstr "Iniciar um novo chat" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Inicie um novo terminal com um login existente. Os outros chats e sua conta padrão permanecerão inalterados." + msgid "Start a session" msgstr "Iniciar uma sessão" @@ -16746,6 +16818,9 @@ msgstr "Comece a navegar" msgid "Start building in two." msgstr "Comece a construir em dois." +msgid "Start chat" +msgstr "Iniciar chat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Inicie agentes de código, acompanhe-os ao vivo e revise o diff no seu iPhone ou iPad. Disponível na App Store; Android chega em breve." @@ -16773,6 +16848,9 @@ msgstr "Comece uma com o + na barra de abas." msgid "Start or stop the workspace run command" msgstr "Iniciar ou parar o comando de execução da área de trabalho" +msgid "Start terminal" +msgstr "Iniciar terminal" + msgid "Start voice mode" msgstr "Iniciar o modo de voz" @@ -16884,6 +16962,12 @@ msgstr "Parar {label}" msgid "Stop {name}" msgstr "Parar {name}" +msgid "Stop agent" +msgstr "Parar agente" + +msgid "Stop agent and background work" +msgstr "Parar agente e tarefas em segundo plano" + msgid "Stop dictation" msgstr "Parar ditado" @@ -16903,6 +16987,9 @@ msgstr "Parar o agente e enviar agora" msgid "Stop the agent before you edit a message" msgstr "Pare o agente antes de editar uma mensagem" +msgid "Stop this agent and its background work?" +msgstr "Parar este agente e suas tarefas em segundo plano?" + msgid "Stop watching" msgstr "Parar de observar" @@ -17044,6 +17131,9 @@ msgstr "Constância" msgid "Sustain · active days in 30" msgstr "Constância · dias ativos em 30" +msgid "Switch account" +msgstr "Trocar conta" + msgid "Switch agents. Keep your workflow" msgstr "Troque de agente. Mantenha seu fluxo" @@ -17792,6 +17882,12 @@ msgstr "O mesmo app roda nativamente no iPad, na vertical e na horizontal." msgid "The scorecard" msgstr "O placar" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Não foi possível verificar a conversa da conta selecionada nos dados de layout salvos. Nada foi iniciado nesta tentativa. Se o armazenamento estiver cheio, libere espaço e renomeie esta aba para salvar o layout antes de tentar novamente. Mantenha esta aba aberta se o problema persistir." + +msgid "The selected login changed. Choose an account again." +msgstr "O login selecionado mudou. Escolha uma conta novamente." + msgid "The self-driving software factory" msgstr "A fábrica de software autônoma" @@ -17870,6 +17966,9 @@ msgstr "Esses comandos rodam automaticamente quando uma área de trabalho é cri msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Estas pastas ainda têm seus arquivos, mas não foram transferidas automaticamente para o novo Paradev." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Estas mensagens não foram enviadas. Copie o que precisar e descarte a fila antes de retomar." + msgid "These ports are still in use" msgstr "Estas portas ainda estão em uso" @@ -17903,6 +18002,9 @@ msgstr "Este agente não pode ramificar uma conversa" msgid "This agent can't run in a cloud workspace" msgstr "Este agente não pode ser executado em uma área de trabalho na nuvem" +msgid "This agent configuration does not support account selection." +msgstr "Esta configuração de agente não permite selecionar uma conta." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Este agente não existe mais no dispositivo selecionado (os agentes podem ter sido redefinidos). As execuções vão falhar até você escolher outro." @@ -17931,6 +18033,9 @@ msgstr "Esta automação está em outra organização" msgid "This cannot be undone." msgstr "Não dá para desfazer." +msgid "This chat could not be opened with its saved account." +msgstr "Não foi possível abrir esta conversa com a conta salva." + msgid "This chat has ended." msgstr "Este chat terminou." @@ -17958,6 +18063,12 @@ msgstr "Não é possível iniciar esta área de trabalho na nuvem" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Este workspace na nuvem está sendo ativado, o que pode levar até 30 segundos depois de um período inativo." +msgid "This conversation cannot be resumed with another account." +msgstr "Esta conversa não pode ser retomada com outra conta." + +msgid "This conversation is no longer available to resume." +msgstr "Esta conversa não está mais disponível para retomada." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Isso apaga o scrollback salvo usado para recuperação após reinício ou travamento." @@ -18000,6 +18111,9 @@ msgstr "Esta instalação do GitHub já está conectada a outra organização do msgid "This host" msgstr "Este host" +msgid "This host does not support account selection for native chats." +msgstr "Este host não oferece seleção de conta para conversas nativas." + msgid "This host has not reported a version yet." msgstr "Este host ainda não informou uma versão." @@ -18162,6 +18276,9 @@ msgstr "Este slug já está em uso" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Isso para todos os gatilhos do Teams na sua organização e remove as assinaturas de notificação do seu tenant. Você pode reconectar quando quiser." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Isso para o processo do agente e todas as tarefas em segundo plano que ele controla. Sua conversa salva continua disponível. Primeiro, revise e descarte as mensagens na fila. Depois, você pode escolher Retomar." + msgid "This subagent can't move to the background now" msgstr "Este subagente não pode ir para segundo plano agora" @@ -18943,6 +19060,9 @@ msgstr "Atualize o Superset neste host para editar a configuração da área de msgid "update the branch prefix" msgstr "atualizar o prefixo da branch" +msgid "Update this host to choose an account for a new terminal." +msgstr "Atualize este host para escolher uma conta para um novo terminal." + msgid "Update this host to message subagents" msgstr "Atualize este host para enviar mensagens aos subagentes" @@ -19034,6 +19154,9 @@ msgstr "Os dados de uso estão desatualizados" msgid "Usage sections" msgstr "Seções de uso" +msgid "Usage unavailable" +msgstr "Uso indisponível" + msgid "Usage unavailable." msgstr "Uso indisponível." diff --git a/packages/i18n/locales/ru/messages.po b/packages/i18n/locales/ru/messages.po index bb88cfa5ea8..cc79fcaf4c2 100644 --- a/packages/i18n/locales/ru/messages.po +++ b/packages/i18n/locales/ru/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} из {total}" +msgid "{remainingPercent} remaining" +msgstr "Осталось {remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} не находится в {installedAccountLogin}, где установлено GitHub App этой организации." @@ -2064,6 +2067,12 @@ msgstr "Сессия агента запущена" msgid "agent settings" msgstr "настройки агента" +msgid "Agent terminal with account" +msgstr "Терминал агента с выбором аккаунта" + +msgid "Agent terminal with account…" +msgstr "Терминал агента с выбором аккаунта…" + msgid "Agent usage rankings" msgstr "Рейтинги использования агентов" @@ -3715,6 +3724,9 @@ msgstr "Сессия чата не найдена" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Поверхности чата: сообщения, рассуждения, подсказки" +msgid "Chat with account" +msgstr "Чат с выбранным аккаунтом" + msgid "Check again" msgstr "Проверить снова" @@ -4116,6 +4128,9 @@ msgstr "Закрыть окно" msgid "Close modal backdrop" msgstr "Закрыть фон окна" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Закрыть только этого неактивного агента и сменить аккаунт. Сначала завершите фоновые задачи и сохраните неотправленные черновики." + msgid "Close or delete the current workspace" msgstr "Закрыть или удалить текущую рабочую область" @@ -4522,6 +4537,9 @@ msgstr "Подтверждать выход" msgid "Confirm switch" msgstr "Подтвердить переход" +msgid "Confirm that this agent can close safely before switching." +msgstr "Перед переключением подтвердите, что этого агента можно безопасно закрыть." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Конфликты с {0}" @@ -5089,6 +5107,9 @@ msgstr "Не удалось удалить файл" msgid "Could not delete this page" msgstr "Не удалось удалить эту страницу" +msgid "Could not discard the queued message." +msgstr "Не удалось удалить сообщение из очереди." + msgid "Could not disconnect." msgstr "Не удалось отключить." @@ -5104,6 +5125,9 @@ msgstr "Не удалось выйти из очереди" msgid "Could not list directory" msgstr "Не удалось прочитать содержимое папки" +msgid "Could not load accounts" +msgstr "Не удалось загрузить аккаунты" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Не удалось загрузить агентов с {0}" @@ -5189,6 +5213,9 @@ msgstr "Не удалось активировать заново" msgid "Could not read MCP servers." msgstr "Не удалось прочитать серверы MCP." +msgid "Could not read queued messages." +msgstr "Не удалось прочитать сообщения в очереди." + msgid "Could not read selected file" msgstr "Не удалось прочитать выбранный файл" @@ -5204,6 +5231,9 @@ msgstr "Не удалось записать облачную рабочую о msgid "Could not record environment" msgstr "Не удалось сохранить окружение" +msgid "Could not refresh usage" +msgstr "Не удалось обновить данные об использовании" + msgid "Could not remove access" msgstr "Не удалось закрыть доступ" @@ -5234,6 +5264,9 @@ msgstr "Не удалось возобновить" msgid "Could not resume the chat" msgstr "Не удалось продолжить чат" +msgid "Could not resume this conversation" +msgstr "Не удалось возобновить этот разговор" + msgid "Could not send" msgstr "Не удалось отправить" @@ -5249,6 +5282,12 @@ msgstr "Не удалось поделиться" msgid "Could not start agent" msgstr "Не удалось запустить агента" +msgid "Could not start agent terminal" +msgstr "Не удалось запустить терминал агента" + +msgid "Could not start chat" +msgstr "Не удалось начать чат" + msgid "Could not start checkout. Please try again." msgstr "Не удалось начать оформление. Попробуйте ещё раз." @@ -5270,12 +5309,18 @@ msgstr "Не удалось остановить" msgid "Could not stop the agent" msgstr "Не удалось остановить агента" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Не удалось остановить агента. Проверьте сообщения в очереди или обновите этот хост, затем повторите попытку." + msgid "Could not stop watching" msgstr "Не удалось прекратить отслеживание" msgid "Could not submit prompt. Try again." msgstr "Не удалось отправить промпт. Повторите." +msgid "Could not switch account" +msgstr "Не удалось сменить аккаунт" + msgid "Could not take a screenshot" msgstr "Не удалось сделать скриншот" @@ -6442,6 +6487,9 @@ msgstr "Отменить изменения в «{discardBasename}»?" msgid "Discard changes?" msgstr "Отменить изменения?" +msgid "Discard queued message" +msgstr "Удалить сообщение из очереди" + msgid "Discard recording" msgstr "Удалить запись" @@ -9998,6 +10046,9 @@ msgstr "Загрузчик · брайлевский спиннер" msgid "Loading" msgstr "Загрузка" +msgid "Loading accounts…" +msgstr "Загрузка аккаунтов…" + msgid "Loading agent settings..." msgstr "Загрузка настроек агента..." @@ -11111,6 +11162,9 @@ msgstr "Авторы не найдены." msgid "No automations match" msgstr "Нет подходящих автоматизаций" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Нет доступных аккаунтов с подпиской. Добавьте аккаунт или войдите в разделе «Использование», затем обновите список." + msgid "No branches found" msgstr "Ветки не найдены" @@ -14431,6 +14485,12 @@ msgstr "Открыть заново закрытую вкладку" msgid "Reopen PR" msgstr "Открыть PR заново" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Открыть сохранённый разговор в той же рабочей области. Сообщение не отправляется. Фоновые задачи не переносятся." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Открыть именно этот сохранённый разговор с другим аккаунтом. Остальные чаты продолжат работу. Сообщение не отправляется." + msgid "Reopen thread" msgstr "Снова открыть ветку" @@ -14787,6 +14847,12 @@ msgstr "Аргументы возобновления" msgid "Resume automation" msgstr "Возобновить автоматизацию" +msgid "Resume conversation" +msgstr "Возобновить разговор" + +msgid "Resume with another account" +msgstr "Возобновить с другой учётной записью" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Возобновление {0}…" @@ -16719,12 +16785,18 @@ msgstr "Начните диалог, чтобы сообщения появил msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Запускает новую сессию агента с недавним контекстом этого терминала. Источником истины остаются файлы рабочего пространства." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Начните встроенный чат с существующим входом в аккаунт. При восстановлении сохраняются этот аккаунт и рабочая папка." + msgid "Start a new agent session each run" msgstr "Запускать новую сессию агента при каждом запуске" msgid "Start a new chat" msgstr "Начать новый чат" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Запустите новый терминал с существующим входом. Другие чаты и аккаунт по умолчанию останутся без изменений." + msgid "Start a session" msgstr "Запустить сессию" @@ -16746,6 +16818,9 @@ msgstr "Начните просмотр" msgid "Start building in two." msgstr "Начните разработку за два." +msgid "Start chat" +msgstr "Начать чат" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Запускайте агентов для кода, следите за ними в реальном времени и проверяйте diff с iPhone или iPad. Доступно в App Store; Android скоро." @@ -16773,6 +16848,9 @@ msgstr "Запустите сессию кнопкой + в полосе вкл msgid "Start or stop the workspace run command" msgstr "Запустить или остановить команду запуска рабочей области" +msgid "Start terminal" +msgstr "Запустить терминал" + msgid "Start voice mode" msgstr "Запустить голосовой режим" @@ -16884,6 +16962,12 @@ msgstr "Остановить {label}" msgid "Stop {name}" msgstr "Остановить {name}" +msgid "Stop agent" +msgstr "Остановить агента" + +msgid "Stop agent and background work" +msgstr "Остановить агента и фоновые задачи" + msgid "Stop dictation" msgstr "Остановить диктовку" @@ -16903,6 +16987,9 @@ msgstr "Остановить агента и отправить сейчас" msgid "Stop the agent before you edit a message" msgstr "Остановите агента, прежде чем изменять сообщение" +msgid "Stop this agent and its background work?" +msgstr "Остановить этого агента и его фоновые задачи?" + msgid "Stop watching" msgstr "Прекратить отслеживание" @@ -17044,6 +17131,9 @@ msgstr "Регулярность" msgid "Sustain · active days in 30" msgstr "Регулярность · активных дней из 30" +msgid "Switch account" +msgstr "Сменить аккаунт" + msgid "Switch agents. Keep your workflow" msgstr "Меняйте агентов. Процесс остаётся" @@ -17792,6 +17882,12 @@ msgstr "То же приложение работает на iPad нативно msgid "The scorecard" msgstr "Таблица оценок" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Не удалось подтвердить чат выбранного аккаунта в сохранённых данных расположения вкладок. Эта попытка ничего не запустила. Если хранилище заполнено, освободите место, затем переименуйте эту вкладку, чтобы сохранить её расположение перед повторной попыткой. Если ошибка повторится, оставьте вкладку открытой." + +msgid "The selected login changed. Choose an account again." +msgstr "Выбранный аккаунт изменился. Выберите аккаунт заново." + msgid "The self-driving software factory" msgstr "Самоуправляемая софтверная фабрика" @@ -17870,6 +17966,9 @@ msgstr "Эти команды выполняются автоматически msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "В этих папках всё ещё есть ваши файлы, но они не перенеслись в новый Paradev автоматически." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Эти сообщения не были отправлены. Скопируйте всё нужное, затем очистите очередь перед возобновлением." + msgid "These ports are still in use" msgstr "Эти порты ещё используются" @@ -17903,6 +18002,9 @@ msgstr "Этот агент не может ответвить разговор" msgid "This agent can't run in a cloud workspace" msgstr "Этот агент не может работать в облачной рабочей области" +msgid "This agent configuration does not support account selection." +msgstr "Эта конфигурация агента не поддерживает выбор аккаунта." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Этого агента больше нет на выбранном устройстве (возможно, его агенты были сброшены). Запуски будут падать, пока не выберете нового." @@ -17931,6 +18033,9 @@ msgstr "Эта автоматизация находится в другой о msgid "This cannot be undone." msgstr "Это нельзя отменить." +msgid "This chat could not be opened with its saved account." +msgstr "Не удалось открыть этот чат с сохранённым аккаунтом." + msgid "This chat has ended." msgstr "Этот чат завершён." @@ -17958,6 +18063,12 @@ msgstr "Не удаётся запустить эту облачную рабо msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Облачное рабочее пространство запускается. После простоя это может занять до 30 секунд." +msgid "This conversation cannot be resumed with another account." +msgstr "Этот разговор нельзя возобновить с другой учётной записью." + +msgid "This conversation is no longer available to resume." +msgstr "Этот разговор больше недоступен для возобновления." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Это удалит сохранённую прокрутку, используемую для восстановления после перезагрузки или сбоя." @@ -18000,6 +18111,9 @@ msgstr "Эта установка GitHub уже подключена к друг msgid "This host" msgstr "Этот хост" +msgid "This host does not support account selection for native chats." +msgstr "Этот хост не поддерживает выбор аккаунта для встроенных чатов." + msgid "This host has not reported a version yet." msgstr "Этот хост ещё не сообщил версию." @@ -18162,6 +18276,9 @@ msgstr "Этот slug уже занят" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Это остановит все триггеры Teams в вашей организации и удалит подписки на уведомления из вашего тенанта. Переподключиться можно в любой момент." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Это остановит процесс агента и все принадлежащие ему фоновые задачи. Сохранённый разговор останется доступным. Сначала проверьте и удалите сообщения в очереди. Затем можно выбрать «Возобновить»." + msgid "This subagent can't move to the background now" msgstr "Этого субагента сейчас нельзя перевести в фон" @@ -18943,6 +19060,9 @@ msgstr "Обновите Superset на этом хосте, чтобы изме msgid "update the branch prefix" msgstr "обновить префикс ветки" +msgid "Update this host to choose an account for a new terminal." +msgstr "Обновите этот хост, чтобы выбрать аккаунт для нового терминала." + msgid "Update this host to message subagents" msgstr "Обновите этот хост, чтобы писать субагентам" @@ -19034,6 +19154,9 @@ msgstr "Данные об использовании устарели" msgid "Usage sections" msgstr "Разделы использования" +msgid "Usage unavailable" +msgstr "Данные об использовании недоступны" + msgid "Usage unavailable." msgstr "Данные об использовании недоступны." diff --git a/packages/i18n/locales/tr/messages.po b/packages/i18n/locales/tr/messages.po index a20869e47b0..c84d6919a65 100644 --- a/packages/i18n/locales/tr/messages.po +++ b/packages/i18n/locales/tr/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{total} içinden {received}" +msgid "{remainingPercent} remaining" +msgstr "{remainingPercent} kaldı" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName}, bu organizasyonun GitHub App'inin kurulu olduğu {installedAccountLogin} hesabında değil." @@ -2064,6 +2067,12 @@ msgstr "Ajan oturumu başladı" msgid "agent settings" msgstr "ajan ayarları" +msgid "Agent terminal with account" +msgstr "Hesap seçerek ajan terminali aç" + +msgid "Agent terminal with account…" +msgstr "Hesap seçerek ajan terminali aç…" + msgid "Agent usage rankings" msgstr "Ajan kullanım sıralamaları" @@ -3715,6 +3724,9 @@ msgstr "Sohbet oturumu bulunamadı" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Sohbet yüzeyleri: mesajlar, akıl yürütme, öneriler" +msgid "Chat with account" +msgstr "Hesap seçerek sohbet et" + msgid "Check again" msgstr "Yeniden denetle" @@ -4116,6 +4128,9 @@ msgstr "Pencereyi kapat" msgid "Close modal backdrop" msgstr "Pencere arka planını kapat" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Yalnızca bu boşta olan ajanı kapatıp hesap değiştirin. Önce arka plan işlerini bitirin ve gönderilmemiş taslakları kaydedin." + msgid "Close or delete the current workspace" msgstr "Geçerli çalışma alanını kapat veya sil" @@ -4522,6 +4537,9 @@ msgstr "Çıkmadan önce onay iste" msgid "Confirm switch" msgstr "Geçişi onayla" +msgid "Confirm that this agent can close safely before switching." +msgstr "Geçiş yapmadan önce bu ajanın güvenle kapatılabileceğini onaylayın." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "{0} ile çakışıyor" @@ -5089,6 +5107,9 @@ msgstr "Dosya silinemedi" msgid "Could not delete this page" msgstr "Bu sayfa silinemedi" +msgid "Could not discard the queued message." +msgstr "Kuyruktaki mesaj silinemedi." + msgid "Could not disconnect." msgstr "Bağlantı kesilemedi." @@ -5104,6 +5125,9 @@ msgstr "Kuyruktan çıkılamadı" msgid "Could not list directory" msgstr "Dizin listelenemedi" +msgid "Could not load accounts" +msgstr "Hesaplar yüklenemedi" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "{0} üzerinden ajanlar yüklenemedi" @@ -5189,6 +5213,9 @@ msgstr "Yeniden etkinleştirilemedi" msgid "Could not read MCP servers." msgstr "MCP sunucuları okunamadı." +msgid "Could not read queued messages." +msgstr "Kuyruktaki mesajlar okunamadı." + msgid "Could not read selected file" msgstr "Seçilen dosya okunamadı" @@ -5204,6 +5231,9 @@ msgstr "Bulut çalışma alanı kaydedilemedi" msgid "Could not record environment" msgstr "Ortam kaydedilemedi" +msgid "Could not refresh usage" +msgstr "Kullanım yenilenemedi" + msgid "Could not remove access" msgstr "Erişim kaldırılamadı" @@ -5234,6 +5264,9 @@ msgstr "Devam ettirilemedi" msgid "Could not resume the chat" msgstr "Sohbete devam edilemedi" +msgid "Could not resume this conversation" +msgstr "Bu konuşma sürdürülemedi" + msgid "Could not send" msgstr "Gönderilemedi" @@ -5249,6 +5282,12 @@ msgstr "Paylaşılamadı" msgid "Could not start agent" msgstr "Ajan başlatılamadı" +msgid "Could not start agent terminal" +msgstr "Ajan terminali başlatılamadı" + +msgid "Could not start chat" +msgstr "Sohbet başlatılamadı" + msgid "Could not start checkout. Please try again." msgstr "Ödeme başlatılamadı. Lütfen tekrar deneyin." @@ -5270,12 +5309,18 @@ msgstr "Durdurulamadı" msgid "Could not stop the agent" msgstr "Ajan durdurulamadı" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Ajan durdurulamadı. Kuyruktaki mesajları gözden geçirin veya bu ana makineyi güncelleyin, ardından tekrar deneyin." + msgid "Could not stop watching" msgstr "İzleme durdurulamadı" msgid "Could not submit prompt. Try again." msgstr "İstem gönderilemedi. Yeniden deneyin." +msgid "Could not switch account" +msgstr "Hesap değiştirilemedi" + msgid "Could not take a screenshot" msgstr "Ekran görüntüsü alınamadı" @@ -6442,6 +6487,9 @@ msgstr "\"{discardBasename}\" dosyasındaki değişiklikler atılsın mı?" msgid "Discard changes?" msgstr "Değişiklikler atılsın mı?" +msgid "Discard queued message" +msgstr "Kuyruktaki mesajı sil" + msgid "Discard recording" msgstr "Kaydı at" @@ -9998,6 +10046,9 @@ msgstr "Yükleyici · Braille spinner" msgid "Loading" msgstr "Yükleniyor" +msgid "Loading accounts…" +msgstr "Hesaplar yükleniyor…" + msgid "Loading agent settings..." msgstr "Ajan ayarları yükleniyor..." @@ -11111,6 +11162,9 @@ msgstr "Yazar bulunamadı." msgid "No automations match" msgstr "Eşleşen otomasyon yok" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Kullanılabilir abonelik hesabı yok. Kullanım bölümünde hesap ekleyin veya oturum açın, ardından yenileyin." + msgid "No branches found" msgstr "Dal bulunamadı" @@ -14431,6 +14485,12 @@ msgstr "Kapatılan sekmeyi yeniden aç" msgid "Reopen PR" msgstr "PR'ı yeniden aç" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Kaydedilen konuşmayı aynı çalışma alanında yeniden açın. Mesaj gönderilmez. Arka plan görevleri aktarılmaz." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Kaydedilmiş bu konuşmayı başka bir hesapla yeniden açın. Diğer sohbetler çalışmaya devam eder. Mesaj gönderilmez." + msgid "Reopen thread" msgstr "Konuyu yeniden aç" @@ -14787,6 +14847,12 @@ msgstr "Sürdürme argümanları" msgid "Resume automation" msgstr "Otomasyonu sürdür" +msgid "Resume conversation" +msgstr "Konuşmayı sürdür" + +msgid "Resume with another account" +msgstr "Başka bir hesapla sürdür" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "{0} sürdürülüyor…" @@ -16719,12 +16785,18 @@ msgstr "Mesajları burada görmek için bir konuşma başlatın" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Bu terminalin son bağlamıyla yeni bir ajan oturumu başlatır. Çalışma alanındaki dosyalar doğruluğun kaynağı olmayı sürdürür." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Mevcut bir oturum açma bilgisiyle yerel sohbet başlatın. Kurtarma sırasında bu hesap ve çalışma klasörü korunur." + msgid "Start a new agent session each run" msgstr "Her çalıştırmada yeni bir aracı oturumu başlat" msgid "Start a new chat" msgstr "Yeni sohbet başlat" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Mevcut bir hesapla yeni terminal başlatın. Diğer sohbetler ve varsayılan hesabınız değişmez." + msgid "Start a session" msgstr "Bir oturum başlat" @@ -16746,6 +16818,9 @@ msgstr "Taramaya başlayın" msgid "Start building in two." msgstr "İki adımda geliştirmeye başlayın." +msgid "Start chat" +msgstr "Sohbet başlat" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "iPhone veya iPad'inizden kodlama ajanlarını başlatın, canlı takip edin ve diff'i inceleyin. App Store'da mevcut; Android yakında geliyor." @@ -16773,6 +16848,9 @@ msgstr "Sekme şeridindeki + ile bir tane başlatın." msgid "Start or stop the workspace run command" msgstr "Çalışma alanı çalıştırma komutunu başlat veya durdur" +msgid "Start terminal" +msgstr "Terminali başlat" + msgid "Start voice mode" msgstr "Sesli modu başlat" @@ -16884,6 +16962,12 @@ msgstr "{label} öğesini durdur" msgid "Stop {name}" msgstr "{name} öğesini durdur" +msgid "Stop agent" +msgstr "Ajanı durdur" + +msgid "Stop agent and background work" +msgstr "Ajanı ve arka plan görevlerini durdur" + msgid "Stop dictation" msgstr "Sesle yazmayı durdur" @@ -16903,6 +16987,9 @@ msgstr "Ajanı durdur ve şimdi gönder" msgid "Stop the agent before you edit a message" msgstr "Bir mesajı düzenlemeden önce ajanı durdurun" +msgid "Stop this agent and its background work?" +msgstr "Bu ajan ve arka plan görevleri durdurulsun mu?" + msgid "Stop watching" msgstr "İzlemeyi durdur" @@ -17044,6 +17131,9 @@ msgstr "Süreklilik" msgid "Sustain · active days in 30" msgstr "Süreklilik · 30 günde etkin gün" +msgid "Switch account" +msgstr "Hesap değiştir" + msgid "Switch agents. Keep your workflow" msgstr "Ajan değiştirin. İş akışınızı koruyun" @@ -17792,6 +17882,12 @@ msgstr "Aynı uygulama iPad'de yerel olarak, dikey ve yatay modda çalışır." msgid "The scorecard" msgstr "Puan tablosu" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Seçilen hesabın sohbeti kayıtlı yerleşim verilerinde doğrulanamadı. Bu denemede hiçbir şey başlatılmadı. Depolama alanı doluysa yer açın, ardından yeniden denemeden önce yerleşimini kaydetmek için bu sekmeyi yeniden adlandırın. Sorun devam ederse bu sekmeyi açık tutun." + +msgid "The selected login changed. Choose an account again." +msgstr "Seçilen hesap değişti. Yeniden bir hesap seçin." + msgid "The self-driving software factory" msgstr "Kendi kendini süren yazılım fabrikası" @@ -17870,6 +17966,9 @@ msgstr "Bu komutlar bir çalışma alanı oluşturulduğunda otomatik olarak ça msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Bu klasörlerde hâlâ dosyalarınız var, ancak yeni Paradev'e kendiliğinden aktarılmadılar." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Bu mesajlar gönderilmedi. Gerekenleri kopyalayın, ardından devam etmeden önce kuyruğu temizleyin." + msgid "These ports are still in use" msgstr "Bu portlar hâlâ kullanımda" @@ -17903,6 +18002,9 @@ msgstr "Bu aracı bir konuşmayı çatallayamaz" msgid "This agent can't run in a cloud workspace" msgstr "Bu ajan bir bulut çalışma alanında çalışamaz" +msgid "This agent configuration does not support account selection." +msgstr "Bu ajan yapılandırması hesap seçimini desteklemiyor." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Bu ajan seçili cihazda artık yok (ajanları sıfırlanmış olabilir). Yeni bir tane seçene kadar çalıştırmalar başarısız olacak." @@ -17931,6 +18033,9 @@ msgstr "Bu otomasyon başka bir kuruluşta" msgid "This cannot be undone." msgstr "Bu geri alınamaz." +msgid "This chat could not be opened with its saved account." +msgstr "Bu sohbet kayıtlı hesabıyla açılamadı." + msgid "This chat has ended." msgstr "Bu sohbet sona erdi." @@ -17958,6 +18063,12 @@ msgstr "Bu bulut çalışma alanı başlatılamıyor" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Bu bulut çalışma alanı uyandırılıyor; bir süre kullanılmadıysa bu işlem 30 saniyeye kadar sürebilir." +msgid "This conversation cannot be resumed with another account." +msgstr "Bu konuşma başka bir hesapla sürdürülemez." + +msgid "This conversation is no longer available to resume." +msgstr "Bu konuşma artık sürdürülemiyor." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Bu işlem, yeniden başlatma/çökme kurtarma için saklanan kaydırma geçmişini siler." @@ -18000,6 +18111,9 @@ msgstr "Bu GitHub kurulumu zaten başka bir Paradev kuruluşuna bağlı. Oradaki msgid "This host" msgstr "Bu host" +msgid "This host does not support account selection for native chats." +msgstr "Bu ana makine yerel sohbetler için hesap seçimini desteklemiyor." + msgid "This host has not reported a version yet." msgstr "Bu ana makine henüz bir sürüm bildirmedi." @@ -18162,6 +18276,9 @@ msgstr "Bu slug zaten alınmış" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Bu işlem kuruluşunuzdaki tüm Teams tetikleyicilerini durdurur ve bildirim aboneliklerini kiracınızdan kaldırır. İstediğiniz zaman yeniden bağlanabilirsiniz." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Bu işlem ajan sürecini ve yönettiği tüm arka plan görevlerini durdurur. Kayıtlı konuşmanız kullanılabilir durumda kalır. Önce kuyruktaki mesajları gözden geçirip silin. Ardından Sürdür seçeneğini seçebilirsiniz." + msgid "This subagent can't move to the background now" msgstr "Bu alt ajan şu anda arka plana taşınamıyor" @@ -18943,6 +19060,9 @@ msgstr "Çalışma alanı yapılandırmasını düzenlemek için bu ana bilgisay msgid "update the branch prefix" msgstr "dal ön ekini güncelleme" +msgid "Update this host to choose an account for a new terminal." +msgstr "Yeni bir terminal için hesap seçmek üzere bu sunucuyu güncelleyin." + msgid "Update this host to message subagents" msgstr "Alt ajanlara mesaj göndermek için bu ana makineyi güncelleyin" @@ -19034,6 +19154,9 @@ msgstr "Kullanım verileri güncel değil" msgid "Usage sections" msgstr "Kullanım bölümleri" +msgid "Usage unavailable" +msgstr "Kullanım bilgisi mevcut değil" + msgid "Usage unavailable." msgstr "Kullanım bilgisi yok." diff --git a/packages/i18n/locales/vi/messages.po b/packages/i18n/locales/vi/messages.po index 1da36c6e413..42b92e28163 100644 --- a/packages/i18n/locales/vi/messages.po +++ b/packages/i18n/locales/vi/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received} trên {total}" +msgid "{remainingPercent} remaining" +msgstr "Còn lại {remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} không nằm trong {installedAccountLogin}, nơi GitHub App của tổ chức này được cài đặt." @@ -2064,6 +2067,12 @@ msgstr "Phiên agent đã bắt đầu" msgid "agent settings" msgstr "cài đặt agent" +msgid "Agent terminal with account" +msgstr "Terminal của tác nhân với tài khoản" + +msgid "Agent terminal with account…" +msgstr "Terminal của tác nhân với tài khoản…" + msgid "Agent usage rankings" msgstr "Xếp hạng mức dùng agent" @@ -3715,6 +3724,9 @@ msgstr "Không tìm thấy phiên chat" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "Các bề mặt chat: tin nhắn, suy luận, gợi ý" +msgid "Chat with account" +msgstr "Trò chuyện bằng tài khoản" + msgid "Check again" msgstr "Kiểm tra lại" @@ -4116,6 +4128,9 @@ msgstr "Đóng hộp thoại" msgid "Close modal backdrop" msgstr "Đóng nền hộp thoại" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "Chỉ đóng tác nhân đang rảnh này rồi chuyển tài khoản. Hãy hoàn tất công việc nền và lưu bản nháp chưa gửi trước." + msgid "Close or delete the current workspace" msgstr "Đóng hoặc xóa workspace hiện tại" @@ -4522,6 +4537,9 @@ msgstr "Xác nhận trước khi thoát" msgid "Confirm switch" msgstr "Xác nhận chuyển" +msgid "Confirm that this agent can close safely before switching." +msgstr "Xác nhận có thể đóng tác nhân này an toàn trước khi chuyển tài khoản." + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "Xung đột với {0}" @@ -5089,6 +5107,9 @@ msgstr "Không thể xóa tệp" msgid "Could not delete this page" msgstr "Không thể xóa trang này" +msgid "Could not discard the queued message." +msgstr "Không thể xóa tin nhắn đang chờ." + msgid "Could not disconnect." msgstr "Không thể ngắt kết nối." @@ -5104,6 +5125,9 @@ msgstr "Không thể rời hàng đợi" msgid "Could not list directory" msgstr "Không thể liệt kê thư mục" +msgid "Could not load accounts" +msgstr "Không thể tải tài khoản" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "Không thể tải agent từ {0}" @@ -5189,6 +5213,9 @@ msgstr "Không thể kích hoạt lại" msgid "Could not read MCP servers." msgstr "Không đọc được các server MCP." +msgid "Could not read queued messages." +msgstr "Không thể đọc các tin nhắn đang chờ." + msgid "Could not read selected file" msgstr "Không thể đọc tệp đã chọn" @@ -5204,6 +5231,9 @@ msgstr "Không thể ghi nhận workspace trên cloud" msgid "Could not record environment" msgstr "Không thể lưu environment" +msgid "Could not refresh usage" +msgstr "Không thể làm mới mức sử dụng" + msgid "Could not remove access" msgstr "Không thể gỡ quyền truy cập" @@ -5234,6 +5264,9 @@ msgstr "Không thể tiếp tục" msgid "Could not resume the chat" msgstr "Không thể tiếp tục cuộc trò chuyện" +msgid "Could not resume this conversation" +msgstr "Không thể tiếp tục cuộc trò chuyện này" + msgid "Could not send" msgstr "Không thể gửi" @@ -5249,6 +5282,12 @@ msgstr "Không thể chia sẻ" msgid "Could not start agent" msgstr "Không thể khởi động agent" +msgid "Could not start agent terminal" +msgstr "Không thể khởi động terminal của tác nhân" + +msgid "Could not start chat" +msgstr "Không thể bắt đầu cuộc trò chuyện" + msgid "Could not start checkout. Please try again." msgstr "Không thể bắt đầu thanh toán. Vui lòng thử lại." @@ -5270,12 +5309,18 @@ msgstr "Không thể dừng" msgid "Could not stop the agent" msgstr "Không thể dừng agent" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "Không thể dừng tác nhân. Hãy xem lại các tin nhắn đang chờ hoặc cập nhật máy chủ này rồi thử lại." + msgid "Could not stop watching" msgstr "Không thể ngừng theo dõi" msgid "Could not submit prompt. Try again." msgstr "Không thể gửi prompt. Hãy thử lại." +msgid "Could not switch account" +msgstr "Không thể chuyển tài khoản" + msgid "Could not take a screenshot" msgstr "Không thể chụp màn hình" @@ -6442,6 +6487,9 @@ msgstr "Bỏ thay đổi với \"{discardBasename}\"?" msgid "Discard changes?" msgstr "Bỏ thay đổi?" +msgid "Discard queued message" +msgstr "Xóa tin nhắn đang chờ" + msgid "Discard recording" msgstr "Bỏ bản ghi" @@ -9998,6 +10046,9 @@ msgstr "Loader · Braille Spinner" msgid "Loading" msgstr "Đang tải" +msgid "Loading accounts…" +msgstr "Đang tải tài khoản…" + msgid "Loading agent settings..." msgstr "Đang tải cài đặt agent..." @@ -11111,6 +11162,9 @@ msgstr "Không tìm thấy tác giả nào." msgid "No automations match" msgstr "Không có tự động hóa nào khớp" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "Không có tài khoản nào có gói đăng ký khả dụng. Thêm tài khoản hoặc đăng nhập vào một tài khoản trong mục Mức sử dụng, rồi làm mới." + msgid "No branches found" msgstr "Không tìm thấy nhánh nào" @@ -14431,6 +14485,12 @@ msgstr "Mở lại tab vừa đóng" msgid "Reopen PR" msgstr "Mở lại PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "Mở lại cuộc trò chuyện đã lưu trong cùng không gian làm việc. Không gửi tin nhắn. Công việc chạy nền không được chuyển sang." + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "Mở lại đúng cuộc trò chuyện đã lưu này bằng tài khoản khác. Các cuộc trò chuyện khác vẫn chạy. Không có tin nhắn nào được gửi." + msgid "Reopen thread" msgstr "Mở lại luồng" @@ -14787,6 +14847,12 @@ msgstr "Tham số resume" msgid "Resume automation" msgstr "Tiếp tục tự động hóa" +msgid "Resume conversation" +msgstr "Tiếp tục cuộc trò chuyện" + +msgid "Resume with another account" +msgstr "Tiếp tục bằng tài khoản khác" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "Đang resume {0}…" @@ -16719,12 +16785,18 @@ msgstr "Bắt đầu một cuộc trò chuyện để thấy tin nhắn ở đâ msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "Bắt đầu một phiên agent mới với ngữ cảnh gần đây của terminal này. Tệp trong workspace vẫn là nguồn đáng tin cậy." +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "Bắt đầu trò chuyện tích hợp bằng phiên đăng nhập hiện có. Khi khôi phục, tài khoản và thư mục làm việc này được giữ nguyên." + msgid "Start a new agent session each run" msgstr "Bắt đầu một phiên agent mới mỗi lần chạy" msgid "Start a new chat" msgstr "Bắt đầu trò chuyện mới" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "Khởi động terminal mới bằng thông tin đăng nhập hiện có. Các cuộc trò chuyện khác và tài khoản mặc định không thay đổi." + msgid "Start a session" msgstr "Bắt đầu một phiên" @@ -16746,6 +16818,9 @@ msgstr "Bắt đầu duyệt web" msgid "Start building in two." msgstr "Bắt đầu xây dựng trong hai bước." +msgid "Start chat" +msgstr "Bắt đầu trò chuyện" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "Khởi chạy agent lập trình, theo dõi trực tiếp và xem xét diff từ iPhone hoặc iPad. Có trên App Store; Android sắp ra mắt." @@ -16773,6 +16848,9 @@ msgstr "Bắt đầu một phiên bằng dấu + trên thanh tab." msgid "Start or stop the workspace run command" msgstr "Bắt đầu hoặc dừng lệnh chạy của workspace" +msgid "Start terminal" +msgstr "Khởi động terminal" + msgid "Start voice mode" msgstr "Bắt đầu chế độ giọng nói" @@ -16884,6 +16962,12 @@ msgstr "Dừng {label}" msgid "Stop {name}" msgstr "Dừng {name}" +msgid "Stop agent" +msgstr "Dừng tác nhân" + +msgid "Stop agent and background work" +msgstr "Dừng tác nhân và tác vụ nền" + msgid "Stop dictation" msgstr "Dừng đọc chính tả" @@ -16903,6 +16987,9 @@ msgstr "Dừng tác tử và gửi ngay" msgid "Stop the agent before you edit a message" msgstr "Hãy dừng tác tử trước khi chỉnh sửa tin nhắn" +msgid "Stop this agent and its background work?" +msgstr "Dừng tác nhân này và các tác vụ nền của nó?" + msgid "Stop watching" msgstr "Ngừng theo dõi" @@ -17044,6 +17131,9 @@ msgstr "Bền bỉ" msgid "Sustain · active days in 30" msgstr "Duy trì · số ngày hoạt động trong 30 ngày" +msgid "Switch account" +msgstr "Đổi tài khoản" + msgid "Switch agents. Keep your workflow" msgstr "Đổi agent. Giữ nguyên quy trình" @@ -17792,6 +17882,12 @@ msgstr "Cùng một ứng dụng chạy native trên iPad, ở cả chế độ msgid "The scorecard" msgstr "Bảng điểm" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "Không thể xác minh cuộc trò chuyện của tài khoản đã chọn trong dữ liệu bố cục đã lưu. Lần thử này chưa khởi chạy gì. Nếu bộ nhớ đã đầy, hãy giải phóng dung lượng, rồi đổi tên thẻ này để lưu bố cục trước khi thử lại. Giữ thẻ này mở nếu vẫn không thành công." + +msgid "The selected login changed. Choose an account again." +msgstr "Thông tin đăng nhập đã chọn đã thay đổi. Hãy chọn lại tài khoản." + msgid "The self-driving software factory" msgstr "Nhà máy phần mềm tự vận hành" @@ -17870,6 +17966,9 @@ msgstr "Các lệnh này chạy tự động khi một workspace được tạo. msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "Các thư mục này vẫn còn tệp của bạn, nhưng chưa tự chuyển sang Paradev mới." +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "Các tin nhắn này chưa được gửi. Sao chép nội dung bạn cần, rồi xóa hàng đợi trước khi tiếp tục." + msgid "These ports are still in use" msgstr "Các cổng này vẫn đang được dùng" @@ -17903,6 +18002,9 @@ msgstr "Tác nhân này không thể tạo nhánh hội thoại" msgid "This agent can't run in a cloud workspace" msgstr "Agent này không thể chạy trong workspace cloud" +msgid "This agent configuration does not support account selection." +msgstr "Cấu hình tác nhân này không hỗ trợ chọn tài khoản." + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "Agent này không còn tồn tại trên thiết bị đã chọn (agent trên đó có thể đã bị đặt lại). Các lần chạy sẽ thất bại cho đến khi bạn chọn agent khác." @@ -17931,6 +18033,9 @@ msgstr "Tự động hóa này nằm trong một tổ chức khác" msgid "This cannot be undone." msgstr "Không thể hoàn tác." +msgid "This chat could not be opened with its saved account." +msgstr "Không thể mở cuộc trò chuyện này bằng tài khoản đã lưu." + msgid "This chat has ended." msgstr "Chat này đã kết thúc." @@ -17958,6 +18063,12 @@ msgstr "Không thể khởi động workspace cloud này" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "Không gian làm việc đám mây này đang được đánh thức, có thể mất tới 30 giây sau một thời gian không hoạt động." +msgid "This conversation cannot be resumed with another account." +msgstr "Không thể tiếp tục cuộc trò chuyện này bằng tài khoản khác." + +msgid "This conversation is no longer available to resume." +msgstr "Cuộc trò chuyện này không còn khả dụng để tiếp tục." + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "Thao tác này xóa phần scrollback đã lưu dùng để khôi phục sau khi khởi động lại hoặc crash." @@ -18000,6 +18111,9 @@ msgstr "Bản cài đặt GitHub này đã kết nối với một tổ chức P msgid "This host" msgstr "Host này" +msgid "This host does not support account selection for native chats." +msgstr "Máy chủ này không hỗ trợ chọn tài khoản cho trò chuyện tích hợp." + msgid "This host has not reported a version yet." msgstr "Máy chủ này chưa báo cáo phiên bản." @@ -18162,6 +18276,9 @@ msgstr "Slug này đã có người dùng" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "Thao tác này dừng mọi trigger Teams trong tổ chức của bạn và gỡ các đăng ký thông báo khỏi tenant. Bạn có thể kết nối lại bất cứ lúc nào." +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "Thao tác này dừng tiến trình tác nhân và mọi tác vụ nền do tiến trình đó quản lý. Cuộc hội thoại đã lưu vẫn còn. Trước tiên, hãy xem lại và xóa các tin nhắn đang chờ. Sau đó bạn có thể chọn Tiếp tục." + msgid "This subagent can't move to the background now" msgstr "Không thể chuyển agent con này sang chạy nền lúc này" @@ -18943,6 +19060,9 @@ msgstr "Hãy cập nhật Superset trên máy chủ này để chỉnh sửa c msgid "update the branch prefix" msgstr "cập nhật tiền tố nhánh" +msgid "Update this host to choose an account for a new terminal." +msgstr "Cập nhật máy chủ này để chọn tài khoản cho terminal mới." + msgid "Update this host to message subagents" msgstr "Cập nhật máy chủ này để nhắn tin cho agent con" @@ -19034,6 +19154,9 @@ msgstr "Dữ liệu sử dụng đã cũ" msgid "Usage sections" msgstr "Các mục mức sử dụng" +msgid "Usage unavailable" +msgstr "Không có dữ liệu sử dụng" + msgid "Usage unavailable." msgstr "Không có dữ liệu sử dụng." diff --git a/packages/i18n/locales/zh-CN/messages.po b/packages/i18n/locales/zh-CN/messages.po index 0ca7e66cdb2..4531efc4dd4 100644 --- a/packages/i18n/locales/zh-CN/messages.po +++ b/packages/i18n/locales/zh-CN/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received}/{total}" +msgid "{remainingPercent} remaining" +msgstr "剩余 {remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} 不在 {installedAccountLogin} 上,而本组织的 GitHub App 安装在那里。" @@ -2064,6 +2067,12 @@ msgstr "智能体会话已开始" msgid "agent settings" msgstr "智能体设置" +msgid "Agent terminal with account" +msgstr "使用指定账户启动智能体终端" + +msgid "Agent terminal with account…" +msgstr "使用指定账户启动智能体终端…" + msgid "Agent usage rankings" msgstr "智能体使用量排行" @@ -3715,6 +3724,9 @@ msgstr "未找到聊天会话" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "聊天界面:消息、推理、建议" +msgid "Chat with account" +msgstr "使用指定账户聊天" + msgid "Check again" msgstr "重新检查" @@ -4116,6 +4128,9 @@ msgstr "关闭弹窗" msgid "Close modal backdrop" msgstr "关闭弹窗背景" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "仅关闭此空闲智能体并切换账户。请先完成后台工作并保存尚未发送的草稿。" + msgid "Close or delete the current workspace" msgstr "关闭或删除当前工作区" @@ -4522,6 +4537,9 @@ msgstr "退出前确认" msgid "Confirm switch" msgstr "确认切换" +msgid "Confirm that this agent can close safely before switching." +msgstr "切换前,请确认可以安全关闭此智能体。" + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "与 {0} 冲突" @@ -5089,6 +5107,9 @@ msgstr "无法删除文件" msgid "Could not delete this page" msgstr "无法删除这个页面" +msgid "Could not discard the queued message." +msgstr "无法丢弃队列中的消息。" + msgid "Could not disconnect." msgstr "无法断开连接。" @@ -5104,6 +5125,9 @@ msgstr "无法移出队列" msgid "Could not list directory" msgstr "无法列出目录" +msgid "Could not load accounts" +msgstr "无法加载账户" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "无法从{0}加载智能体" @@ -5189,6 +5213,9 @@ msgstr "无法重新激活" msgid "Could not read MCP servers." msgstr "无法读取MCP服务器。" +msgid "Could not read queued messages." +msgstr "无法读取队列中的消息。" + msgid "Could not read selected file" msgstr "无法读取所选文件" @@ -5204,6 +5231,9 @@ msgstr "无法记录云端工作区" msgid "Could not record environment" msgstr "无法保存环境" +msgid "Could not refresh usage" +msgstr "无法刷新使用量" + msgid "Could not remove access" msgstr "无法移除访问权限" @@ -5234,6 +5264,9 @@ msgstr "无法继续" msgid "Could not resume the chat" msgstr "无法继续聊天" +msgid "Could not resume this conversation" +msgstr "无法继续此对话" + msgid "Could not send" msgstr "无法发送" @@ -5249,6 +5282,12 @@ msgstr "无法分享" msgid "Could not start agent" msgstr "无法启动智能体" +msgid "Could not start agent terminal" +msgstr "无法启动智能体终端" + +msgid "Could not start chat" +msgstr "无法开始聊天" + msgid "Could not start checkout. Please try again." msgstr "无法开始结账,请重试。" @@ -5270,12 +5309,18 @@ msgstr "无法停止" msgid "Could not stop the agent" msgstr "无法停止智能体" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "无法停止智能体。请检查队列中的消息或更新此主机,然后重试。" + msgid "Could not stop watching" msgstr "无法停止关注" msgid "Could not submit prompt. Try again." msgstr "无法提交提示词。请重试。" +msgid "Could not switch account" +msgstr "无法切换账户" + msgid "Could not take a screenshot" msgstr "无法截图" @@ -6442,6 +6487,9 @@ msgstr "放弃对“{discardBasename}”的更改?" msgid "Discard changes?" msgstr "放弃更改?" +msgid "Discard queued message" +msgstr "丢弃队列中的消息" + msgid "Discard recording" msgstr "放弃录音" @@ -9998,6 +10046,9 @@ msgstr "加载器 · 盲文加载动画" msgid "Loading" msgstr "加载中" +msgid "Loading accounts…" +msgstr "正在加载账户…" + msgid "Loading agent settings..." msgstr "正在加载智能体设置..." @@ -11111,6 +11162,9 @@ msgstr "未找到作者。" msgid "No automations match" msgstr "没有匹配的自动化" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "没有可用的订阅账户。请在“用量”中添加账户或登录,然后刷新。" + msgid "No branches found" msgstr "未找到分支" @@ -14431,6 +14485,12 @@ msgstr "重新打开已关闭的标签页" msgid "Reopen PR" msgstr "重新打开PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "在同一工作区中重新打开已保存的对话。不会发送消息,也不会转移后台任务。" + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "使用其他账户重新打开这段已保存的会话。其他聊天将继续运行。不会发送任何消息。" + msgid "Reopen thread" msgstr "重新打开讨论串" @@ -14787,6 +14847,12 @@ msgstr "恢复参数" msgid "Resume automation" msgstr "恢复自动化" +msgid "Resume conversation" +msgstr "继续对话" + +msgid "Resume with another account" +msgstr "使用其他账户继续" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "正在恢复{0}…" @@ -16719,12 +16785,18 @@ msgstr "开始一段对话,消息会显示在这里" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "以该终端最近的上下文启动一个新的智能体会话。工作区中的文件仍是准确来源。" +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "使用现有登录启动原生聊天。恢复时将保留此账户和工作文件夹。" + msgid "Start a new agent session each run" msgstr "每次运行都启动新的智能体会话" msgid "Start a new chat" msgstr "开始新的聊天" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "使用现有登录启动新终端。其他聊天和默认账户保持不变。" + msgid "Start a session" msgstr "开始一个会话" @@ -16746,6 +16818,9 @@ msgstr "开始浏览" msgid "Start building in two." msgstr "两步开始构建。" +msgid "Start chat" +msgstr "开始聊天" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "在 iPhone 或 iPad 上启动编程智能体、实时跟进并审查差异。已在 App Store 上架;Android 版即将推出。" @@ -16773,6 +16848,9 @@ msgstr "用标签栏中的+新建一个。" msgid "Start or stop the workspace run command" msgstr "启动或停止工作区运行命令" +msgid "Start terminal" +msgstr "启动终端" + msgid "Start voice mode" msgstr "开始语音模式" @@ -16884,6 +16962,12 @@ msgstr "停止 {label}" msgid "Stop {name}" msgstr "停止 {name}" +msgid "Stop agent" +msgstr "停止智能体" + +msgid "Stop agent and background work" +msgstr "停止智能体及后台任务" + msgid "Stop dictation" msgstr "停止语音输入" @@ -16903,6 +16987,9 @@ msgstr "停止智能体并立即发送" msgid "Stop the agent before you edit a message" msgstr "编辑消息前请先停止智能体" +msgid "Stop this agent and its background work?" +msgstr "停止此智能体及其后台任务?" + msgid "Stop watching" msgstr "停止关注" @@ -17044,6 +17131,9 @@ msgstr "持续" msgid "Sustain · active days in 30" msgstr "持续性 · 30 天内的活跃天数" +msgid "Switch account" +msgstr "切换账户" + msgid "Switch agents. Keep your workflow" msgstr "换智能体,不换工作流" @@ -17792,6 +17882,12 @@ msgstr "同一个应用在 iPad 上原生运行,支持竖屏和横屏。" msgid "The scorecard" msgstr "评分表" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "无法在已保存的布局数据中验证所选账户的聊天。本次尝试未启动任何内容。如果存储空间已满,请释放空间,然后重命名此标签页以保存布局,再重试。如果仍然失败,请保持此标签页打开。" + +msgid "The selected login changed. Choose an account again." +msgstr "所选登录已更改。请重新选择账户。" + msgid "The self-driving software factory" msgstr "自动驾驶的软件工厂" @@ -17870,6 +17966,9 @@ msgstr "创建工作区时会自动运行这些命令。<0>阅读文档<1/>" msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "这些文件夹中仍有你的文件,但没有自动迁移到新版 Paradev。" +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "这些消息尚未发送。请复制需要的内容,然后在恢复前清空队列。" + msgid "These ports are still in use" msgstr "这些端口仍在使用中" @@ -17903,6 +18002,9 @@ msgstr "该智能体无法分叉对话" msgid "This agent can't run in a cloud workspace" msgstr "此智能体无法在云端工作区中运行" +msgid "This agent configuration does not support account selection." +msgstr "此智能体配置不支持选择账户。" + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "所选设备上已不存在这个智能体(它的智能体可能被重置过)。在你选择新的智能体之前,运行都会失败。" @@ -17931,6 +18033,9 @@ msgstr "此自动化位于其他组织" msgid "This cannot be undone." msgstr "此操作无法撤销。" +msgid "This chat could not be opened with its saved account." +msgstr "无法使用已保存的账户打开此聊天。" + msgid "This chat has ended." msgstr "此聊天已结束。" @@ -17958,6 +18063,12 @@ msgstr "无法启动此云端工作区" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "正在唤醒此云工作区。如果它已闲置一段时间,可能需要最多 30 秒。" +msgid "This conversation cannot be resumed with another account." +msgstr "无法使用其他账户继续此对话。" + +msgid "This conversation is no longer available to resume." +msgstr "此对话已无法继续。" + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "这将删除用于重启/崩溃恢复的已保存回滚缓冲。" @@ -18000,6 +18111,9 @@ msgstr "这个GitHub安装已连接到另一个Paradev组织。请先在那里 msgid "This host" msgstr "此主机" +msgid "This host does not support account selection for native chats." +msgstr "此主机不支持为原生聊天选择账户。" + msgid "This host has not reported a version yet." msgstr "此主机尚未报告版本。" @@ -18162,6 +18276,9 @@ msgstr "此slug已被占用" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "这会停止你组织中所有的Teams触发器,并从你的租户中移除通知订阅。你可以随时重新连接。" +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "这将停止智能体进程及其管理的所有后台任务。已保存的对话仍然可用。请先检查并丢弃队列中的消息,然后选择“恢复”。" + msgid "This subagent can't move to the background now" msgstr "此子智能体现在无法移到后台" @@ -18943,6 +19060,9 @@ msgstr "请更新此主机上的 Superset,以编辑其工作区配置。" msgid "update the branch prefix" msgstr "更新分支前缀" +msgid "Update this host to choose an account for a new terminal." +msgstr "请更新此主机,以便为新终端选择账户。" + msgid "Update this host to message subagents" msgstr "请更新此主机以向子智能体发送消息" @@ -19034,6 +19154,9 @@ msgstr "用量数据已过时" msgid "Usage sections" msgstr "用量分区" +msgid "Usage unavailable" +msgstr "使用量不可用" + msgid "Usage unavailable." msgstr "无法获取用量。" diff --git a/packages/i18n/locales/zh-TW/messages.po b/packages/i18n/locales/zh-TW/messages.po index 5416d74da50..57e1e369f62 100644 --- a/packages/i18n/locales/zh-TW/messages.po +++ b/packages/i18n/locales/zh-TW/messages.po @@ -1177,6 +1177,9 @@ msgstr "{reason}" msgid "{received} of {total}" msgstr "{received}/{total}" +msgid "{remainingPercent} remaining" +msgstr "剩餘 {remainingPercent}" + msgid "{repositoryFullName} isn't on {installedAccountLogin}, where this organization's GitHub App is installed." msgstr "{repositoryFullName} 不在 {installedAccountLogin} 上,而本組織的 GitHub App 安裝在那裡。" @@ -2064,6 +2067,12 @@ msgstr "代理程式會話已開始" msgid "agent settings" msgstr "代理程式設定" +msgid "Agent terminal with account" +msgstr "使用指定帳戶啟動代理終端機" + +msgid "Agent terminal with account…" +msgstr "使用指定帳戶啟動代理終端機…" + msgid "Agent usage rankings" msgstr "代理程式使用量排行" @@ -3715,6 +3724,9 @@ msgstr "未找到聊天會話" msgid "Chat surfaces: messages, reasoning, suggestions" msgstr "聊天介面:訊息、推理、建議" +msgid "Chat with account" +msgstr "使用指定帳戶聊天" + msgid "Check again" msgstr "重新檢查" @@ -4116,6 +4128,9 @@ msgstr "關閉彈窗" msgid "Close modal backdrop" msgstr "關閉彈窗背景" +msgid "Close only this idle agent and switch. Finish background work and save any unsent draft first." +msgstr "僅關閉此閒置代理並切換帳戶。請先完成背景工作並儲存尚未傳送的草稿。" + msgid "Close or delete the current workspace" msgstr "關閉或刪除目前工作區" @@ -4522,6 +4537,9 @@ msgstr "退出前確認" msgid "Confirm switch" msgstr "確認切換" +msgid "Confirm that this agent can close safely before switching." +msgstr "切換前,請確認可以安全關閉此代理。" + #. placeholder {0}: status.baseBranch msgid "Conflicts with {0}" msgstr "與 {0} 衝突" @@ -5089,6 +5107,9 @@ msgstr "無法刪除檔案" msgid "Could not delete this page" msgstr "無法刪除這個頁面" +msgid "Could not discard the queued message." +msgstr "無法捨棄佇列中的訊息。" + msgid "Could not disconnect." msgstr "無法中斷連線。" @@ -5104,6 +5125,9 @@ msgstr "無法移出佇列" msgid "Could not list directory" msgstr "無法列出目錄" +msgid "Could not load accounts" +msgstr "無法載入帳戶" + #. placeholder {0}: host.name msgid "Could not load agents from {0}" msgstr "無法從{0}載入代理程式" @@ -5189,6 +5213,9 @@ msgstr "無法重新啟用" msgid "Could not read MCP servers." msgstr "無法讀取MCP伺服器。" +msgid "Could not read queued messages." +msgstr "無法讀取佇列中的訊息。" + msgid "Could not read selected file" msgstr "無法讀取所選檔案" @@ -5204,6 +5231,9 @@ msgstr "無法記錄雲端工作區" msgid "Could not record environment" msgstr "無法儲存環境" +msgid "Could not refresh usage" +msgstr "無法重新整理用量" + msgid "Could not remove access" msgstr "無法移除存取權限" @@ -5234,6 +5264,9 @@ msgstr "無法繼續" msgid "Could not resume the chat" msgstr "無法繼續聊天" +msgid "Could not resume this conversation" +msgstr "無法繼續此對話" + msgid "Could not send" msgstr "無法傳送" @@ -5249,6 +5282,12 @@ msgstr "無法分享" msgid "Could not start agent" msgstr "無法啟動代理程式" +msgid "Could not start agent terminal" +msgstr "無法啟動代理終端機" + +msgid "Could not start chat" +msgstr "無法開始聊天" + msgid "Could not start checkout. Please try again." msgstr "無法開始結帳,請再試一次。" @@ -5270,12 +5309,18 @@ msgstr "無法停止" msgid "Could not stop the agent" msgstr "無法停止代理程式" +msgid "Could not stop the agent. Review queued messages or update this host, then try again." +msgstr "無法停止代理程式。請檢查佇列中的訊息或更新此主機,然後重試。" + msgid "Could not stop watching" msgstr "無法停止關注" msgid "Could not submit prompt. Try again." msgstr "無法提交提示詞。請重試。" +msgid "Could not switch account" +msgstr "無法切換帳戶" + msgid "Could not take a screenshot" msgstr "無法截圖" @@ -6442,6 +6487,9 @@ msgstr "放棄對「{discardBasename}」的更改?" msgid "Discard changes?" msgstr "放棄更改?" +msgid "Discard queued message" +msgstr "捨棄佇列中的訊息" + msgid "Discard recording" msgstr "放棄錄音" @@ -9998,6 +10046,9 @@ msgstr "載入器 · 點字載入動畫" msgid "Loading" msgstr "載入中" +msgid "Loading accounts…" +msgstr "正在載入帳戶…" + msgid "Loading agent settings..." msgstr "正在載入代理程式設定..." @@ -11111,6 +11162,9 @@ msgstr "未找到作者。" msgid "No automations match" msgstr "沒有匹配的自動化" +msgid "No available subscription accounts. Add or sign in to an account in Usage, then refresh." +msgstr "沒有可用的訂閱帳戶。請在「用量」中新增帳戶或登入,然後重新整理。" + msgid "No branches found" msgstr "未找到分支" @@ -14431,6 +14485,12 @@ msgstr "重新開啟已關閉的分頁" msgid "Reopen PR" msgstr "重新開啟PR" +msgid "Reopen the saved conversation in the same workspace. No message is sent. Background work is not transferred." +msgstr "在同一工作區中重新開啟已儲存的對話。不會傳送訊息,也不會轉移背景工作。" + +msgid "Reopen this exact saved conversation with another account. Other chats stay running. No message is sent." +msgstr "使用其他帳戶重新開啟這段已儲存的對話。其他聊天將繼續執行。不會傳送任何訊息。" + msgid "Reopen thread" msgstr "重新開啟討論串" @@ -14787,6 +14847,12 @@ msgstr "恢復引數" msgid "Resume automation" msgstr "恢復自動化" +msgid "Resume conversation" +msgstr "繼續對話" + +msgid "Resume with another account" +msgstr "使用其他帳戶繼續" + #. placeholder {0}: candidate.agentLabel msgid "Resuming {0}…" msgstr "正在恢復{0}…" @@ -16719,12 +16785,18 @@ msgstr "開始一段對話,訊息會顯示在這裡" msgid "Start a fresh agent session seeded with this terminal's recent context. Workspace files remain the source of truth." msgstr "以這個終端最近的上下文啟動新的代理程式會話。工作區中的檔案仍是準確來源。" +msgid "Start a native chat using an existing login. Recovery keeps this account and working folder." +msgstr "使用現有登入啟動原生聊天。復原時會保留此帳戶和工作資料夾。" + msgid "Start a new agent session each run" msgstr "每次執行都啟動新的代理程式工作階段" msgid "Start a new chat" msgstr "開始新的聊天" +msgid "Start a new terminal using an existing login. Other chats and your default account stay unchanged." +msgstr "使用現有登入啟動新的終端機。其他聊天和預設帳戶保持不變。" + msgid "Start a session" msgstr "開始一個會話" @@ -16746,6 +16818,9 @@ msgstr "開始瀏覽" msgid "Start building in two." msgstr "兩步開始建置。" +msgid "Start chat" +msgstr "開始聊天" + msgid "Start coding agents, follow them live, and review the diff from your iPhone or iPad. Available on the App Store; Android is coming soon." msgstr "在 iPhone 或 iPad 上啟動程式設計 agent、即時追蹤並審查差異。已在 App Store 上架;Android 版即將推出。" @@ -16773,6 +16848,9 @@ msgstr "用分頁列中的+新建一個。" msgid "Start or stop the workspace run command" msgstr "啟動或停止工作區執行命令" +msgid "Start terminal" +msgstr "啟動終端機" + msgid "Start voice mode" msgstr "開始語音模式" @@ -16884,6 +16962,12 @@ msgstr "停止 {label}" msgid "Stop {name}" msgstr "停止 {name}" +msgid "Stop agent" +msgstr "停止代理程式" + +msgid "Stop agent and background work" +msgstr "停止代理程式及背景工作" + msgid "Stop dictation" msgstr "停止語音輸入" @@ -16903,6 +16987,9 @@ msgstr "停止代理並立即傳送" msgid "Stop the agent before you edit a message" msgstr "編輯訊息前請先停止代理程式" +msgid "Stop this agent and its background work?" +msgstr "停止此代理程式及其背景工作?" + msgid "Stop watching" msgstr "停止關注" @@ -17044,6 +17131,9 @@ msgstr "持續" msgid "Sustain · active days in 30" msgstr "持續性 · 30 天內的活躍天數" +msgid "Switch account" +msgstr "切換帳戶" + msgid "Switch agents. Keep your workflow" msgstr "換代理程式,不換工作流" @@ -17792,6 +17882,12 @@ msgstr "同一個應用程式在 iPad 上原生執行,支援直向和橫向。 msgid "The scorecard" msgstr "評分表" +msgid "The selected account chat could not be verified in saved layout data. Nothing was launched by this attempt. If storage is full, free space, then rename this tab to save its layout before retrying. Keep this tab open if it still fails." +msgstr "無法在已儲存的版面配置資料中驗證所選帳戶的聊天。本次嘗試未啟動任何內容。如果儲存空間已滿,請釋出空間,然後重新命名此分頁以儲存版面配置,再重試。如果仍然失敗,請保持此分頁開啟。" + +msgid "The selected login changed. Choose an account again." +msgstr "所選登入已變更。請重新選擇帳戶。" + msgid "The self-driving software factory" msgstr "自動駕駛的軟體工廠" @@ -17870,6 +17966,9 @@ msgstr "建立工作區時會自動執行這些命令。<0>閱讀文件<1/>" msgid "These folders still have your files, but they did not come over to the new Paradev on their own." msgstr "這些資料夾中仍有你的檔案,但沒有自動移轉到新版 Paradev。" +msgid "These messages were not sent. Copy anything you need, then discard the queue before resuming." +msgstr "這些訊息尚未傳送。請複製需要的內容,然後在繼續前清空佇列。" + msgid "These ports are still in use" msgstr "這些埠仍在使用中" @@ -17903,6 +18002,9 @@ msgstr "此代理無法分叉對話" msgid "This agent can't run in a cloud workspace" msgstr "此代理程式無法在雲端工作區中執行" +msgid "This agent configuration does not support account selection." +msgstr "此代理設定不支援選擇帳戶。" + msgid "This agent no longer exists on the selected device (its agents may have been reset). Runs will fail until you pick a new one." msgstr "所選裝置上已不存在這個代理程式(它的代理程式可能被重置過)。在你選擇新的代理程式之前,執行都會失敗。" @@ -17931,6 +18033,9 @@ msgstr "此自動化位於其他組織" msgid "This cannot be undone." msgstr "此操作無法復原。" +msgid "This chat could not be opened with its saved account." +msgstr "無法使用已儲存的帳戶開啟此聊天。" + msgid "This chat has ended." msgstr "此聊天已結束。" @@ -17958,6 +18063,12 @@ msgstr "無法啟動此雲端工作區" msgid "This cloud workspace is waking up, which can take up to 30 seconds after it has been idle." msgstr "正在喚醒此雲端工作區。如果它已閒置一段時間,可能需要最多 30 秒。" +msgid "This conversation cannot be resumed with another account." +msgstr "無法使用其他帳戶繼續此對話。" + +msgid "This conversation is no longer available to resume." +msgstr "此對話已無法繼續。" + msgid "This deletes the saved scrollback used for reboot/crash recovery." msgstr "這將刪除用於重啟/崩潰恢復的已儲存回滾緩衝。" @@ -18000,6 +18111,9 @@ msgstr "這個GitHub安裝已連線到另一個Paradev組織。請先在那裡 msgid "This host" msgstr "此主機" +msgid "This host does not support account selection for native chats." +msgstr "此主機不支援為原生聊天選取帳戶。" + msgid "This host has not reported a version yet." msgstr "此主機尚未回報版本。" @@ -18162,6 +18276,9 @@ msgstr "此slug已被佔用" msgid "This stops every Teams trigger in your organization and removes the notification subscriptions from your tenant. You can reconnect at any time." msgstr "這會停止你組織中所有的Teams觸發器,並從你的租戶中移除通知訂閱。你可以隨時重新連線。" +msgid "This stops the agent process and any background work it owns. Your saved conversation stays available. Review and discard any queued messages first. You can then choose Resume." +msgstr "這會停止代理程式的處理程序及其管理的所有背景工作。已儲存的對話仍可使用。請先檢查並捨棄佇列中的訊息,然後選擇「恢復」。" + msgid "This subagent can't move to the background now" msgstr "此子代理程式目前無法移到背景" @@ -18943,6 +19060,9 @@ msgstr "請更新此主機上的 Superset,以編輯其工作區設定。" msgid "update the branch prefix" msgstr "更新分支字首" +msgid "Update this host to choose an account for a new terminal." +msgstr "請更新此主機,以便為新的終端機選擇帳戶。" + msgid "Update this host to message subagents" msgstr "請更新此主機以傳送訊息給子代理程式" @@ -19034,6 +19154,9 @@ msgstr "用量資料已過期" msgid "Usage sections" msgstr "用量分區" +msgid "Usage unavailable" +msgstr "無法取得使用量" + msgid "Usage unavailable." msgstr "無法獲取用量。" diff --git a/packages/macos-process-metrics/executable-path.node-test.ts b/packages/macos-process-metrics/executable-path.node-test.ts new file mode 100644 index 00000000000..64d006ee734 --- /dev/null +++ b/packages/macos-process-metrics/executable-path.node-test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import { realpathSync } from "node:fs"; +import { createRequire } from "node:module"; +import test from "node:test"; + +const require = createRequire(import.meta.url); +const { getExecutablePath } = require("./index.js") as { + getExecutablePath(pid: number): string | null; +}; + +test( + "macOS returns this process's kernel executable rather than a launcher alias", + { skip: process.platform !== "darwin" }, + () => { + assert.equal( + getExecutablePath(process.pid), + realpathSync(process.execPath), + ); + assert.equal(getExecutablePath(2_147_483_647), null); + for (const pid of [ + 0, + -1, + 1.5, + Number.NaN, + Number.POSITIVE_INFINITY, + 2_147_483_648, + ]) { + assert.throws(() => getExecutablePath(pid), TypeError); + } + }, +); + +test( + "other platforms report unavailable executable authority", + { skip: process.platform === "darwin" }, + () => { + assert.equal(getExecutablePath(process.pid), null); + }, +); diff --git a/packages/macos-process-metrics/index.d.ts b/packages/macos-process-metrics/index.d.ts index 9c8340c418b..7c9df1c8543 100644 --- a/packages/macos-process-metrics/index.d.ts +++ b/packages/macos-process-metrics/index.d.ts @@ -10,3 +10,6 @@ * PIDs are silently omitted. */ export function getPhysFootprints(pids: number[]): Record; + +/** macOS process text-vnode path, or null on unsupported/unavailable observations. */ +export function getExecutablePath(pid: number): string | null; diff --git a/packages/macos-process-metrics/index.js b/packages/macos-process-metrics/index.js index f5cf6810a63..909f94174c2 100644 --- a/packages/macos-process-metrics/index.js +++ b/packages/macos-process-metrics/index.js @@ -25,4 +25,10 @@ function getPhysFootprints(pids) { return native.getPhysFootprints(pids); } -module.exports = { getPhysFootprints }; +/** Kernel main executable path; null when unavailable. No ps/launcher fallback. */ +function getExecutablePath(pid) { + if (!native || typeof native.getExecutablePath !== "function") return null; + return native.getExecutablePath(pid); +} + +module.exports = { getPhysFootprints, getExecutablePath }; diff --git a/packages/macos-process-metrics/package.json b/packages/macos-process-metrics/package.json index 46a9468b42c..6dc467fbc49 100644 --- a/packages/macos-process-metrics/package.json +++ b/packages/macos-process-metrics/package.json @@ -5,7 +5,8 @@ "main": "index.js", "types": "index.d.ts", "scripts": { - "install": "node-gyp rebuild || echo 'Native build skipped (non-macOS or missing toolchain)'" + "install": "node-gyp rebuild || echo 'Native build skipped (non-macOS or missing toolchain)'", + "test:integration": "node --experimental-strip-types --test executable-path.node-test.ts" }, "dependencies": { "node-addon-api": "7.1.1" diff --git a/packages/macos-process-metrics/src/addon.cc b/packages/macos-process-metrics/src/addon.cc index 31a3233c338..e363a2cb78c 100644 --- a/packages/macos-process-metrics/src/addon.cc +++ b/packages/macos-process-metrics/src/addon.cc @@ -1,4 +1,6 @@ #include +#include +#include #ifdef __APPLE__ #include @@ -47,7 +49,31 @@ Napi::Value GetPhysFootprints(const Napi::CallbackInfo& info) { return result; } +// proc_pidpath is derived from the process text vnode, independent of launcher updates. +Napi::Value GetExecutablePath(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + if (info.Length() != 1 || !info[0].IsNumber()) { + Napi::TypeError::New(env, "Expected one positive PID").ThrowAsJavaScriptException(); + return env.Null(); + } + const double value = info[0].As().DoubleValue(); + if (!std::isfinite(value) || value != std::floor(value) || value <= 0 || + value > std::numeric_limits::max()) { + Napi::TypeError::New(env, "Expected one positive PID").ThrowAsJavaScriptException(); + return env.Null(); + } +#ifdef __APPLE__ + char path[PROC_PIDPATHINFO_MAXSIZE] = {}; + const int length = proc_pidpath(static_cast(value), path, sizeof(path)); + if (length > 0 && static_cast(length) < sizeof(path)) { + return Napi::String::New(env, path, static_cast(length)); + } +#endif + return env.Null(); +} + Napi::Object Init(Napi::Env env, Napi::Object exports) { + exports.Set("getExecutablePath", Napi::Function::New(env, GetExecutablePath)); exports.Set("getPhysFootprints", Napi::Function::New(env, GetPhysFootprints)); return exports;