The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(restore): retry sandbox copy-back before holding the task for repair (#15920)
Devin Foley4611d6e95a68
diff --git a/doc/workspace-restore-locks.md b/doc/workspace-restore-locks.mdindex 62acf88b79..d5e882f580 100644--- a/doc/workspace-restore-locks.md+++ b/doc/workspace-restore-locks.md@@ -57,6 +57,15 @@ that an earlier failed collection discarded.## Required remote restore failures+The copy-back first repairs itself. While the run still holds its merge+baseline, a workspace copy-back that fails before writing any host file is+retried up to three times in total, with a short backoff. This covers dropped+transfers, provider errors, and a merge lock held by another restore. An unsafe+archive, a permission failure, or any failure after the merge started writing+host files is never retried. Only a copy-back that still fails reaches the+repair hold below. Adapter environment Tests restore into a throwaway temp+workspace, so they opt out of these retries and report a failure at once.+When a legacy sandbox run cannot copy required workspace files back, the serverkeeps the original allocation for repair. It writes the failed run, the exactlease retention intent, and a board-owned repair hold in one transaction. Thediff --git a/packages/adapter-utils/src/command-managed-runtime.ts b/packages/adapter-utils/src/command-managed-runtime.tsindex 30d09ab72f..027f8489f0 100644--- a/packages/adapter-utils/src/command-managed-runtime.ts+++ b/packages/adapter-utils/src/command-managed-runtime.ts@@ -565,6 +565,8 @@ export async function prepareCommandManagedRuntime(input: {// prepareSandboxManagedRuntime so the host pack time rides one `pack` span// under the `stage.sync` step. The default is a no-op.runtimeSpan?: RuntimeSpanRunner;+ /** Copy-back retry delays; pass `[]` for throwaway workspaces that must not wait on retries. */+ workspaceRestoreRetryDelaysMs?: readonly number[];}): Promise<PreparedSandboxManagedRuntime> {const timeoutMs = input.spec.timeoutMs && input.spec.timeoutMs > 0 ? input.spec.timeoutMs : 300_000;const workspaceRemoteDir = input.workspaceRemoteDir ?? input.spec.remoteCwd;@@ -623,6 +625,7 @@ export async function prepareCommandManagedRuntime(input: {onProgress: input.onProgress,onRuntimeProgress: input.onRuntimeProgress,runtimeSpan: input.runtimeSpan,+ workspaceRestoreRetryDelaysMs: input.workspaceRestoreRetryDelaysMs,});}}@@ -668,5 +671,6 @@ export async function prepareCommandManagedRuntime(input: {onProgress: input.onProgress,onRuntimeProgress: input.onRuntimeProgress,runtimeSpan: input.runtimeSpan,+ workspaceRestoreRetryDelaysMs: input.workspaceRestoreRetryDelaysMs,});}diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.tsindex df93ac848f..5e99328fa0 100644--- a/packages/adapter-utils/src/execution-target.ts+++ b/packages/adapter-utils/src/execution-target.ts@@ -1461,6 +1461,11 @@ export async function prepareAdapterExecutionTargetRuntime(input: {// so the host pack time rides one `pack` span under the `stage.sync` step. The// SSH and local lanes ignore it. The default is a no-op.runtimeSpan?: RuntimeSpanRunner;+ /**+ * Sandbox copy-back retry delays. Environment probes restore into a throwaway+ * temp workspace and pass `[]` so a failed restore does not stall the Test.+ */+ workspaceRestoreRetryDelaysMs?: readonly number[];}): Promise<PreparedAdapterExecutionTargetRuntime> {const target = input.target ?? { kind: "local" as const };if (target.kind === "local") {@@ -1535,6 +1540,7 @@ export async function prepareAdapterExecutionTargetRuntime(input: {onProgress: input.onProgress,onRuntimeProgress: input.onRuntimeProgress,runtimeSpan: input.runtimeSpan,+ workspaceRestoreRetryDelaysMs: input.workspaceRestoreRetryDelaysMs,});return {target,diff --git a/packages/adapter-utils/src/sandbox-managed-runtime.test.ts b/packages/adapter-utils/src/sandbox-managed-runtime.test.tsindex bf5ab10e4d..0f479a0121 100644--- a/packages/adapter-utils/src/sandbox-managed-runtime.test.ts+++ b/packages/adapter-utils/src/sandbox-managed-runtime.test.ts@@ -4456,12 +4456,14 @@ describe("sandbox git-bundle export transport", () => {const client = makeTransportClient(step !== "workspace_extract", { syncOutOperations: [], readFilePaths: [] });const prepared = await prepareSandboxManagedRuntime({spec: gitSpec(remoteWorkspaceDir), adapterKey: "test-adapter", client, workspaceLocalDir: localWorkspaceDir,+ workspaceRestoreRetryDelaysMs: [0, 0],});await commitInSandbox(remoteWorkspaceDir);const failure = Object.assign(new Error("private-restore-command /private-restore-path"), { code: 7, stderr: "private-restore-stderr" });+ // Failures before the first host write are retried, so they must persist.if (step === "git_export") client.run = async () => { throw failure; };- if (step === "git_import") vi.spyOn(gitSync, "fetchGitBundleIntoLocalRef").mockRejectedValueOnce(failure);- if (step === "directory_merge") vi.spyOn(restoreMerge, "mergeDirectoryWithBaseline").mockRejectedValueOnce(failure);+ if (step === "git_import") vi.spyOn(gitSync, "fetchGitBundleIntoLocalRef").mockRejectedValue(failure);+ if (step === "directory_merge") vi.spyOn(restoreMerge, "mergeDirectoryWithBaseline").mockRejectedValue(failure);if (step === "git_integration") vi.spyOn(gitSync, "integrateImportedGitHead").mockRejectedValueOnce(failure);if (step === "index_reset") vi.spyOn(gitSync, "resetLocalGitIndexToHead").mockRejectedValueOnce(failure);if (step === "git_ref_cleanup") vi.spyOn(gitSync, "deleteLocalGitRef").mockRejectedValueOnce(failure);@@ -4490,6 +4492,111 @@ describe("sandbox git-bundle export transport", () => {} finally { vi.restoreAllMocks(); }});+ it.each([+ ["a dropped transfer", Object.assign(new Error("transfer reset"), { code: "ECONNRESET" })],+ ["a busy merge lock", Object.assign(new Error("lock busy"), { code: restoreMerge.WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE })],+ ])("retries the copy-back after %s before any host write", async (_label, failure) => {+ const { localWorkspaceDir, remoteWorkspaceDir } = await setupGitBackedWorkspace("paperclip-restore-retry-");+ const client = makeTransportClient(true, { syncOutOperations: [], readFilePaths: [] });+ const prepared = await prepareSandboxManagedRuntime({+ spec: gitSpec(remoteWorkspaceDir), adapterKey: "test-adapter", client, workspaceLocalDir: localWorkspaceDir,+ workspaceRestoreRetryDelaysMs: [0, 0],+ });+ await commitInSandbox(remoteWorkspaceDir);+ let directoryTransfers = 0;+ const syncOut = client.syncOut!;+ client.syncOut = async (operations) => {+ const directory = operations.some((operation) => operation.files.some((file) => file.kind === "directory"));+ if (directory && ++directoryTransfers === 1 && failure.code === "ECONNRESET") throw failure;+ return syncOut(operations);+ };+ if (failure.code !== "ECONNRESET") vi.spyOn(restoreMerge, "mergeDirectoryWithBaseline").mockRejectedValueOnce(failure);+ try {+ await prepared.restoreWorkspace();+ expect(directoryTransfers).toBe(2);+ expect(await git(localWorkspaceDir, ["log", "-1", "--pretty=%s"])).toBe("sandbox update");+ await expect(readFile(path.join(localWorkspaceDir, "remote-only.txt"), "utf8")).resolves.toBe("from sandbox\n");+ } finally { vi.restoreAllMocks(); }+ });++ it("gives up after three copy-back attempts", async () => {+ const { localWorkspaceDir, remoteWorkspaceDir } = await setupGitBackedWorkspace("paperclip-restore-retry-limit-");+ const client = makeTransportClient(true, { syncOutOperations: [], readFilePaths: [] });+ const prepared = await prepareSandboxManagedRuntime({+ spec: gitSpec(remoteWorkspaceDir), adapterKey: "test-adapter", client, workspaceLocalDir: localWorkspaceDir,+ workspaceRestoreRetryDelaysMs: [0, 0],+ });+ await commitInSandbox(remoteWorkspaceDir);+ const failure = new Error("sandbox unreachable");+ let directoryTransfers = 0;+ const syncOut = client.syncOut!;+ client.syncOut = async (operations) => {+ if (!operations.some((operation) => operation.files.some((file) => file.kind === "directory"))) return syncOut(operations);+ directoryTransfers++;+ throw failure;+ };+ await expect(prepared.restoreWorkspace()).rejects.toBe(failure);+ expect(directoryTransfers).toBe(3);+ });++ it.each([+ ["an unsafe archive", Object.assign(new Error("unsafe"), { code: "WORKSPACE_RESTORE_UNSAFE_ARCHIVE" }), "directory_merge"],+ ["a permission failure", Object.assign(new Error("denied"), { code: "EACCES" }), "directory_merge"],+ ["a failure after the merge started writing", new Error("integration failed"), "git_integration"],+ ] as const)("does not retry %s", async (_label, failure, step) => {+ const { localWorkspaceDir, remoteWorkspaceDir } = await setupGitBackedWorkspace("paperclip-restore-no-retry-");+ const client = makeTransportClient(true, { syncOutOperations: [], readFilePaths: [] });+ const prepared = await prepareSandboxManagedRuntime({+ spec: gitSpec(remoteWorkspaceDir), adapterKey: "test-adapter", client, workspaceLocalDir: localWorkspaceDir,+ workspaceRestoreRetryDelaysMs: [0, 0],+ });+ await commitInSandbox(remoteWorkspaceDir);+ const spy = step === "directory_merge"+ ? vi.spyOn(restoreMerge, "mergeDirectoryWithBaseline").mockRejectedValue(failure)+ : vi.spyOn(gitSync, "integrateImportedGitHead").mockRejectedValue(failure);+ try {+ await expect(prepared.restoreWorkspace()).rejects.toBe(failure);+ expect(spy).toHaveBeenCalledTimes(1);+ } finally { vi.restoreAllMocks(); }+ });++ it("does not retry a non-Git copy-back that failed after writing a host file", async () => {+ const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-restore-partial-"));+ cleanupDirs.push(rootDir);+ const localWorkspaceDir = path.join(rootDir, "local-workspace");+ const remoteWorkspaceDir = path.join(rootDir, "remote-workspace");+ await mkdir(localWorkspaceDir, { recursive: true });+ await writeFile(path.join(localWorkspaceDir, "base.txt"), "base\n", "utf8");+ const client = makeTransportClient(true, { syncOutOperations: [], readFilePaths: [] });+ const prepared = await prepareSandboxManagedRuntime({+ spec: gitSpec(remoteWorkspaceDir), adapterKey: "test-adapter", client, workspaceLocalDir: localWorkspaceDir,+ workspaceRestoreRetryDelaysMs: [0, 0],+ });+ await writeFile(path.join(remoteWorkspaceDir, "a-first.txt"), "first\n", "utf8");+ await writeFile(path.join(remoteWorkspaceDir, "z-later.txt"), "later\n", "utf8");+ let directoryTransfers = 0;+ const syncOut = client.syncOut!;+ client.syncOut = async (operations) => {+ if (operations.some((operation) => operation.files.some((file) => file.kind === "directory"))) directoryTransfers++;+ return syncOut(operations);+ };+ // The merge copies entries in path order, so the first file lands before the+ // later copy fails with an otherwise retryable I/O error.+ const failure = Object.assign(new Error("i/o error"), { code: "EIO" });+ const copyFile = fsPromises.copyFile.bind(fsPromises);+ vi.spyOn(fsPromises, "copyFile").mockImplementation(async (source, target, mode) => {+ if (path.basename(String(source)) === "z-later.txt") throw failure;+ return copyFile(source, target, mode);+ });+ const merge = vi.spyOn(restoreMerge, "mergeDirectoryWithBaseline");+ try {+ await expect(prepared.restoreWorkspace()).rejects.toBe(failure);+ await expect(readFile(path.join(localWorkspaceDir, "a-first.txt"), "utf8")).resolves.toBe("first\n");+ expect(directoryTransfers).toBe(1);+ expect(merge).toHaveBeenCalledTimes(1);+ } finally { vi.restoreAllMocks(); }+ });+it("moves the bundle through one native syncOut file mapping, never through readFile", async () => {const capture: TransportCapture = { syncOutOperations: [], readFilePaths: [] };const { localWorkspaceDir, remoteWorkspaceDir } = await setupGitBackedWorkspace("paperclip-bundle-native-");diff --git a/packages/adapter-utils/src/sandbox-managed-runtime.ts b/packages/adapter-utils/src/sandbox-managed-runtime.tsindex c059b4535b..0a72797300 100644--- a/packages/adapter-utils/src/sandbox-managed-runtime.ts+++ b/packages/adapter-utils/src/sandbox-managed-runtime.ts@@ -29,6 +29,7 @@ import {} from "./git-workspace-sync.js";import {captureDirectorySnapshot,+ classifyWorkspaceRestoreFailure,disposeDirectorySnapshot,selectDirectorySnapshot,mergeDirectoryWithBaseline,@@ -314,6 +315,37 @@ async function delay(ms: number): Promise<void> {await new Promise<void>((resolve) => setTimeout(resolve, ms));}+/**+ * Backoff before each automatic retry of a workspace copy-back: three total+ * attempts. A failed copy-back otherwise retains the sandbox for board repair,+ * so a dropped transfer or a busy merge lock must not end the run's restore.+ */+const WORKSPACE_RESTORE_RETRY_DELAYS_MS = [2_000, 5_000] as const;++/**+ * Retry a copy-back attempt only while it has written nothing into the host+ * workspace. The baseline stays valid until then, so a fresh attempt is the+ * same merge. Never retry an unsafe archive or a permission failure, and never+ * retry once the merge has started writing host files.+ */+async function retryWorkspaceRestoreBeforeHostWrite(+ delaysMs: readonly number[],+ attempt: (markHostWriteStarted: () => void) => Promise<void>,+): Promise<void> {+ for (let retry = 0; ; retry++) {+ let hostWriteStarted = false;+ try {+ await attempt(() => { hostWriteStarted = true; });+ return;+ } catch (error) {+ const code = classifyWorkspaceRestoreFailure(error);+ const retryable = code === "restore_failed" || code === "restore_lock_timeout";+ if (hostWriteStarted || !retryable || retry >= delaysMs.length) throw error;+ await delay(delaysMs[retry]!);+ }+ }+}+/*** True only when `error` carries the workspace Git scan scheduler's typed* saturation code on its `code` property. Matches the code alone, never@@ -1128,6 +1160,8 @@ export async function prepareSandboxManagedRuntime(input: {// no-op that keeps the current behavior and control flow. A throwing runner// never changes control flow (see `createRuntimeSpanRunner`).runtimeSpan?: RuntimeSpanRunner;+ /** Backoff before each automatic workspace copy-back retry. Tests shorten it. */+ workspaceRestoreRetryDelaysMs?: readonly number[];}): Promise<PreparedSandboxManagedRuntime> {const workspaceRemoteDir = input.workspaceRemoteDir ?? input.spec.remoteCwd;const runtimeRootDir = input.runtimeRootDir ?? path.posix.join(workspaceRemoteDir, ".paperclip-runtime", input.adapterKey);@@ -1772,10 +1806,13 @@ export async function prepareSandboxManagedRuntime(input: {ignoredPaths: repository.snapshot.ignoredPaths,}),onRuntimeProgress: input.onRuntimeProgress,+ workspaceRestoreRetryDelaysMs: input.workspaceRestoreRetryDelaysMs,});await nested.restoreWorkspace(restoreSink);}- await withTempDir("paperclip-sandbox-restore-", async (tempDir) => {+ await retryWorkspaceRestoreBeforeHostWrite(+ input.workspaceRestoreRetryDelaysMs ?? WORKSPACE_RESTORE_RETRY_DELAYS_MS,+ (markHostWriteStarted) => withTempDir("paperclip-sandbox-restore-", async (tempDir) => {let importedRef: string | null = null;let importedHead: string | null = null;let remoteWorkspaceStatus = "dirty";@@ -1942,15 +1979,16 @@ export async function prepareSandboxManagedRuntime(input: {baseline: mergeBaseline,sourceDir: extractedDir,targetDir: input.workspaceLocalDir,- beforeApply: gitHeadToIntegrate- ? async () => {- await withWorkspaceRestoreStep("git_integration", () => integrateImportedGitHead({- localDir: input.workspaceLocalDir,- importedHead: gitHeadToIntegrate,- baseline: gitSnapshot ?? undefined,- }));- }- : undefined,+ // Runs under the merge lock, before the first host write.+ beforeApply: async () => {+ markHostWriteStarted();+ if (!gitHeadToIntegrate) return;+ await withWorkspaceRestoreStep("git_integration", () => integrateImportedGitHead({+ localDir: input.workspaceLocalDir,+ importedHead: gitHeadToIntegrate,+ baseline: gitSnapshot ?? undefined,+ }));+ },afterApply: gitSnapshot? async () => {await withWorkspaceRestoreStep("index_reset", () => resetLocalGitIndexToHead({@@ -1968,7 +2006,7 @@ export async function prepareSandboxManagedRuntime(input: {await withWorkspaceRestoreStep("git_ref_cleanup", () => deleteLocalGitRef({ localDir: input.workspaceLocalDir, ref: importedRef! }));}}- });+ }));}), restoreSink, (diagnostic) => { outboundDiagnostics[0] = diagnostic; }),);}diff --git a/packages/adapters/claude-local/src/server/claude-config.ts b/packages/adapters/claude-local/src/server/claude-config.tsindex 1f9710ca2c..20eece2fa4 100644--- a/packages/adapters/claude-local/src/server/claude-config.ts+++ b/packages/adapters/claude-local/src/server/claude-config.ts@@ -314,6 +314,8 @@ export async function prepareSandboxClaudeProbeRuntime(input: {workspaceLocalDir: tempWorkspaceDir,workspaceRemoteDir: managedRemoteCwd,timeoutSec: Math.max(1, input.helloProbeTimeoutSec),+ // The probe workspace is a throwaway temp dir; never wait on copy-back retries.+ workspaceRestoreRetryDelaysMs: [],assets: [{key: "config-seed",diff --git a/packages/adapters/codex-local/src/server/test.ts b/packages/adapters/codex-local/src/server/test.tsindex 10cbcb8d39..da22fbd0b1 100644--- a/packages/adapters/codex-local/src/server/test.ts+++ b/packages/adapters/codex-local/src/server/test.ts@@ -196,6 +196,8 @@ async function prepareCodexHelloProbe(input: {workspaceRemoteDir: input.cwd,installCommand: SANDBOX_INSTALL_COMMAND,detectCommand: input.command,+ // The probe workspace is a throwaway temp dir; never wait on copy-back retries.+ workspaceRestoreRetryDelaysMs: [],assets: [{key: "home",diff --git a/packages/adapters/grok-local/src/server/test.ts b/packages/adapters/grok-local/src/server/test.tsindex bb814c9761..22f163f662 100644--- a/packages/adapters/grok-local/src/server/test.ts+++ b/packages/adapters/grok-local/src/server/test.ts@@ -171,6 +171,8 @@ export async function testEnvironment(runId, target, adapterKey: "grok",workspaceLocalDir: runtimeWorkspaceLocalDir,workspaceRemoteDir: cwd,+ // The probe workspace is a throwaway temp dir; never wait on copy-back retries.+ workspaceRestoreRetryDelaysMs: [],assets: [{ key: "home", localDir: stagedHome, followSymlinks: true,restore: async ({ assetDir, readFile }) => { await copyBackGrokAuth({readSandboxAuth: () => readFile(path.posix.join(assetDir, "auth.json")),diff --git a/packages/adapters/opencode-local/src/server/test.ts b/packages/adapters/opencode-local/src/server/test.tsindex 628745e977..fa0823cdc6 100644--- a/packages/adapters/opencode-local/src/server/test.ts+++ b/packages/adapters/opencode-local/src/server/test.ts@@ -161,6 +161,8 @@ export async function testEnvironment(workspaceRemoteDir: cwd,installCommand: SANDBOX_INSTALL_COMMAND,detectCommand: command,+ // The probe workspace is a throwaway temp dir; never wait on copy-back retries.+ workspaceRestoreRetryDelaysMs: [],assets: localRuntimeConfigHome? [{key: "xdgConfig",diff --git a/ui/src/components/ExecutionBlockerNotice.test.tsx b/ui/src/components/ExecutionBlockerNotice.test.tsxindex 980f0a6fdf..3fd0f6a9b8 100644--- a/ui/src/components/ExecutionBlockerNotice.test.tsx+++ b/ui/src/components/ExecutionBlockerNotice.test.tsx@@ -106,7 +106,12 @@ describe("stopped task recovery notice", () => {nextAction: "The original sandbox is retained. Recover the missing files and record workspace repair evidence.",}} /></QueryClientProvider>));- expect(container.textContent).toContain("Recover the missing files");+ expect(container.textContent).toContain("could not restore the agent's workspace files");+ expect(container.textContent).toContain("A board operator must recover the files");+ // The hold also covers unsafe archives and local runs, so the notice must not promise retries or a kept sandbox.+ expect(container.textContent).not.toContain("retrying");+ expect(container.textContent).not.toContain("no work is lost");+ expect(container.querySelector("details")?.textContent).toContain("Recover the missing files");expect(container.querySelector("button")).toBeNull();expect(container.querySelector("a")?.textContent).toBe("Inspect run");expect(agentsApi.retryFailedRun).not.toHaveBeenCalled();diff --git a/ui/src/components/ExecutionBlockerNotice.tsx b/ui/src/components/ExecutionBlockerNotice.tsxindex 0cb1eb0b77..a0ecd58085 100644--- a/ui/src/components/ExecutionBlockerNotice.tsx+++ b/ui/src/components/ExecutionBlockerNotice.tsx@@ -39,7 +39,20 @@ export function ExecutionBlockerNotice({ companyId, issueId, blocker, onRetried,<div className="min-w-0 flex-1 break-words"><p>{modelRejected ? "Model unavailable." : "Recovery needed."}{blocker.runError ? ` ${blocker.runError}` : ""}</p>{modelRejected && <p>Choose a supported model or clear the task's model override, then retry.</p>}- <p>{blocker.nextAction}</p>+ {blocker.workspaceRepairRequired ? (+ <>+ {/* The stored next action is an operator runbook step; lead with what happened. This hold also covers+ unsafe archives and local runs, so do not claim retries or a retained sandbox here. */}+ <p>+ Paperclip could not restore the agent's workspace files after its last run. A board operator must+ recover the files before the agent can continue.+ </p>+ <details>+ <summary className="cursor-pointer">Technical details</summary>+ <p>{blocker.nextAction}</p>+ </details>+ </>+ ) : <p>{blocker.nextAction}</p>}{Boolean(blocker.savedMessageCount) && (<p>{blocker.savedMessageCount} saved {blocker.savedMessageCount === 1 ? "message is" : "messages are"} waiting for recovery.</p>)}diff --git a/ui/src/context/ToastContext.test.tsx b/ui/src/context/ToastContext.test.tsxindex 09912a315c..569fdfb4ee 100644--- a/ui/src/context/ToastContext.test.tsx+++ b/ui/src/context/ToastContext.test.tsx@@ -69,4 +69,34 @@ describe("ToastContext", () => {root.unmount();});});++ it("shows one toast when distinct events render the same text", () => {+ const root = createRoot(container);+ let pushToastRef: ((input: { title: string; body?: string; dedupeKey?: string }) => string | null) | null = null;++ function Consumer() {+ pushToastRef = useToastActions().pushToast;+ const toasts = useToastState();+ return <div data-testid="toast-count">{String(toasts.length)}</div>;+ }++ act(() => {+ root.render(<ToastProvider><Consumer /></ToastProvider>);+ });++ const results: Array<string | null> = [];+ act(() => {+ results.push(pushToastRef!({ title: "Ada run succeeded", dedupeKey: "run-status:one:succeeded" }));+ results.push(pushToastRef!({ title: "Ada run succeeded", dedupeKey: "run-status:two:succeeded" }));+ results.push(pushToastRef!({ title: "Ada run succeeded", body: "Trigger: comment", dedupeKey: "run-status:three:succeeded" }));+ });++ expect(results[1]).toBeNull();+ expect(results[2]).not.toBeNull();+ expect(container.querySelector('[data-testid="toast-count"]')?.textContent).toBe("2");++ act(() => {+ root.unmount();+ });+ });});diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastContext.tsxindex d9841e011f..9f99597a4d 100644--- a/ui/src/context/ToastContext.tsx+++ b/ui/src/context/ToastContext.tsx@@ -128,11 +128,18 @@ export function ToastProvider({ children }: { children: ReactNode }) {}}- const lastSeen = dedupeRef.current.get(dedupeKey);- if (lastSeen && now - lastSeen < DEDUPE_WINDOW_MS) {+ // Distinct events (two runs, two status changes) can render the same+ // visible text. Showing it twice reads as a duplicate, so match on that too.+ const contentKey = `content|${tone}|${input.title}|${input.body ?? ""}`;+ const recentlyShown = [dedupeKey, contentKey].some((key) => {+ const lastSeen = dedupeRef.current.get(key);+ return lastSeen !== undefined && now - lastSeen < DEDUPE_WINDOW_MS;+ });+ if (recentlyShown) {return null;}dedupeRef.current.set(dedupeKey, now);+ dedupeRef.current.set(contentKey, now);const id = input.id ?? generateToastId();clearTimer(id);