Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): the send-to-background action waits ten seconds, and the mark shares its slot (#721)

Yaowei Zheng48a6b3500d55
diff --git a/changelog/unreleased/2026-09-14-background-action-delay.md b/changelog/unreleased/2026-09-14-background-action-delay.md
new file mode 100644
index 00000000..2abf1eee
--- /dev/null
+++ b/changelog/unreleased/2026-09-14-background-action-delay.md
@@ -0,0 +1,14 @@
+# The send-to-background action waits ten seconds, and the background mark shares its slot
+
+- **Date:** 2026-09-14
+- **Type:** fix
+- **Scope:** `core`, `web`, `docs`
+- **PR:** [#721](https://github.com/Prism-Shadow/penguin-harness/pull/721)
+
+[中文版](2026-09-14-background-action-delay.zh.md)
+
+## What changed
+
+- The **Send to background** action on a running `exec_command` / `run_subagent` row appears only once the call has been executing for ten seconds. A command that returns in a few seconds used to flash the action and take it away again, so the row's right end jumped with every short call; now it stays still, and the action shows where waiting has actually begun.
+- The `[Background]` mark a backgrounded call wears sits at the row's right end, in the very slot the action occupies (before the expand chevron), instead of after the duration. The two never show together, so clicking the action leaves the mark in its place and the row's right end holds one right-aligned thing.
+- The note a moved call returns to the model now says plainly not to follow it up: leave the work running unattended, no polling and no input, move on to other work or end the turn, the completion arrives on its own as a `[background_task_done]` message. A model used to answer the move by opening `input_command` on the very process the user had just parked.
diff --git a/changelog/unreleased/2026-09-14-background-action-delay.zh.md b/changelog/unreleased/2026-09-14-background-action-delay.zh.md
new file mode 100644
index 00000000..97648365
--- /dev/null
+++ b/changelog/unreleased/2026-09-14-background-action-delay.zh.md
@@ -0,0 +1,14 @@
+# 「转入后台执行」满 10 秒才出现,后台标记与它同一个槽位
+
+- **Date:** 2026-09-14
+- **Type:** fix
+- **Scope:** `core`, `web`, `docs`
+- **PR:** [#721](https://github.com/Prism-Shadow/penguin-harness/pull/721)
+
+[English](2026-09-14-background-action-delay.md)
+
+## 变更内容
+
+- 执行中的 `exec_command` / `run_subagent` 行上的**转入后台执行**动作,只在调用已执行满 10 秒后才出现。此前几秒即完的命令也会闪现一下这个动作再收回,行尾随每个短调用跳来跳去;现在行尾保持不动,动作只在真正开始等待时出现。
+- 已转入后台的调用所带的「[后台任务]」标记改到行尾、也就是动作所在的同一个槽位(展开箭头之前),不再紧跟在用时之后。两者从不同时出现,点下动作即原位换成标记,行尾始终只有一样靠右的东西。
+- 转入后台的调用返回给模型的说明现在明确写出不要跟进:让它自己跑,不要轮询、不要发输入,先去做别的事或结束本轮,结束时会以 `[background_task_done]` 消息送回。此前模型常常在用户刚把进程转入后台时就对它开一个 `input_command` 跟进。
diff --git a/packages/core/src/environment/tools/exec-command.ts b/packages/core/src/environment/tools/exec-command.ts
index d31b01ac..624fce59 100644
--- a/packages/core/src/environment/tools/exec-command.ts
+++ b/packages/core/src/environment/tools/exec-command.ts
@@ -162,8 +162,10 @@ export function createExecCommandTool(
return {
stopReason: "completed",
note:
- `${DETACHED_TOOL_NOTE_PREFIX} with process_id ${id}; its completion will arrive ` +
- `as a user message — no need to poll. Use input_command to interact (kill: true stops it)]`,
+ `${DETACHED_TOOL_NOTE_PREFIX} with process_id ${id}; leave it running unattended: ` +
+ `do not poll it or send it input — its completion will arrive on its own as a ` +
+ `[background_task_done] user message. Move on to other work, or end the turn if ` +
+ `nothing else is pending; input_command with kill: true still stops it if the user asks]`,
};
}
return {
diff --git a/packages/core/src/environment/tools/run-subagent.ts b/packages/core/src/environment/tools/run-subagent.ts
index 7105c39c..9ffb707d 100644
--- a/packages/core/src/environment/tools/run-subagent.ts
+++ b/packages/core/src/environment/tools/run-subagent.ts
@@ -231,9 +231,11 @@ export function createSubagentTool(
return {
stopReason: "completed",
note:
- `${DETACHED_TOOL_NOTE_PREFIX} with subagent_id ${id}; its completion will arrive ` +
- `as a user message — no need to poll. Use input_subagent to interact ` +
- `(abort: true stops its current run)]`,
+ `${DETACHED_TOOL_NOTE_PREFIX} with subagent_id ${id}; leave it running unattended: ` +
+ `do not poll it or send it input — its completion will arrive on its own as a ` +
+ `[background_task_done] user message. Move on to other work, or end the turn if ` +
+ `nothing else is pending; input_subagent with abort: true still stops its current ` +
+ `run if the user asks]`,
};
}
return {
diff --git a/packages/docs/content/tools.en.md b/packages/docs/content/tools.en.md
index ab59e177..1d24a989 100644
--- a/packages/docs/content/tools.en.md
+++ b/packages/docs/content/tools.en.md
@@ -206,7 +206,7 @@ The Web App's subagents panel drives a selected child with the **same composer a
### Background completion reports
-A task launched with `run_in_background: true`, and a running call the user moved to the background from its row in the Web App, both report their completion as a **user message injected by the harness** — the model does not need to poll. The message opens with a `[background_task_done]` marker block (kind, id, status, one-line detail) followed by what ran and the tail of its yet-undelivered output (capped at 4000 characters; the Web App collapses the block into a one-line notice). Its `text` payload carries `sender: "harness"`, distinguishing it from human input in the Trace (see [OmniMessage](/omni-message)).
+A task launched with `run_in_background: true`, and a running call the user moved to the background from its row in the Web App, both report their completion as a **user message injected by the harness** — the model does not need to poll. A call the user moved there says so in its own result: the note tells the model to leave the work alone — no polling, no input — and to move on to other work or end the turn, because the user sent it to the background precisely so the model would not follow it up; the completion arrives on its own. The message opens with a `[background_task_done]` marker block (kind, id, status, one-line detail) followed by what ran and the tail of its yet-undelivered output (capped at 4000 characters; the Web App collapses the block into a one-line notice). Its `text` payload carries `sender: "harness"`, distinguishing it from human input in the Trace (see [OmniMessage](/omni-message)).
Delivery: while a Task is running, the report rides the next turn boundary — a final reply already streaming does not lose it, the Task simply continues for one more turn to react. While the Session is idle, the hosting server starts a new Task carrying the report (SDK embedders subscribe via `Session.onBackgroundNotice` / `takeBackgroundNotices`, or get it prepended to the next run). A command terminated through `input_command`'s `kill` sends no report — that call's own result already carries the outcome — and neither does a subagent round ended by an explicit `abort` (the aborter reads the outcome directly). Reports cover **model-initiated rounds only** — the `run_in_background` launch and `input_subagent` follow-ups; a round the user starts from the subagents panel is their own conversation with the child and sends no report (its answer text stays in the model-facing buffer for the next poll).
diff --git a/packages/docs/content/tools.zh.md b/packages/docs/content/tools.zh.md
index 666f0a6d..083ac79b 100644
--- a/packages/docs/content/tools.zh.md
+++ b/packages/docs/content/tools.zh.md
@@ -203,7 +203,7 @@ Web App 的智能体面板用**与主对话相同的 composer**(子会话变
### 后台完成回报
-以 `run_in_background: true` 启动的任务,以及用户在 Web App 的工具调用行上转入后台的调用,都在结束时以**Harness 注入的 user message** 回报完成——模型无需轮询。消息以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符;Web App 将标记块折叠为一行提示)。其 `text` payload 带 `sender: "harness"`,在 Trace 中与真人输入相区分(见 [OmniMessage](/omni-message))。
+以 `run_in_background: true` 启动的任务,以及用户在 Web App 的工具调用行上转入后台的调用,都在结束时以**Harness 注入的 user message** 回报完成——模型无需轮询。被用户转入后台的调用,其工具结果里的说明会把这一点写明:让它自己跑,不要轮询、不要发输入,先去做别的事或结束本轮——用户把它转入后台正是为了不让模型跟进;完成时自会送回。消息以 `[background_task_done]` 标记块开头(kind、id、status、一行 detail),其后是任务内容与尚未送达输出的尾部(上限 4000 字符;Web App 将标记块折叠为一行提示)。其 `text` payload 带 `sender: "harness"`,在 Trace 中与真人输入相区分(见 [OmniMessage](/omni-message))。
送达时机:Task 进行中时,回报搭乘下一个 turn 边界——即使最终回复已在流式输出,Task 也会为回应它再延续一个 turn。Session 空闲时,托管 Server 自动以该回报发起新 Task(SDK 嵌入方可订阅 `Session.onBackgroundNotice` / `takeBackgroundNotices`,否则回报并入下一次 run 的输入)。经 `input_command` 的 `kill` 终止的命令不发回报——该调用自身的结果已说明结局;被显式 `abort` 结束的子会话轮同样不发(打断者当场读到结局)。回报只覆盖**模型自己发起的轮**——`run_in_background` 的启动轮与 `input_subagent` 的续跑轮;用户从智能体面板发起的轮是用户与子会话自己的对话,不发回报(该轮答案文本留在模型面缓冲,下次轮询照常取得)。
diff --git a/packages/web/src/features/chat/live-duration.tsx b/packages/web/src/features/chat/live-duration.tsx
index acd397ba..33c188d1 100644
--- a/packages/web/src/features/chat/live-duration.tsx
+++ b/packages/web/src/features/chat/live-duration.tsx
@@ -1,14 +1,46 @@
/**
- * Live duration (inline display on running thinking/tool cards): ticks every second, showing
- * whole seconds only — decimals appear only on the settled value once the item finishes. sinceMs
- * comes from the server-side message timestamp and may drift from the local clock; negative
- * values are shown as 0; a pulsing ellipsis is shown when missing.
- * `offsetMs` is the already-settled duration of a prior segment (e.g. a tool call's argument
- * generation phase), added on top of the live segment as it ticks.
+ * Two readings of a running item's elapsed time, and only one of them is a clock.
+ * `LiveDuration` is the inline display on running thinking/tool cards: it ticks every second,
+ * showing whole seconds only — decimals appear only on the settled value once the item
+ * finishes. sinceMs comes from the server-side message timestamp and may drift from the local
+ * clock; negative values are shown as 0; a pulsing ellipsis is shown when missing. `offsetMs`
+ * is the already-settled duration of a prior segment (e.g. a tool call's argument generation
+ * phase), added on top of the live segment as it ticks.
+ * `useElapsedPast` answers a single threshold question instead, and re-renders once, at the
+ * crossing — a caller that only shows or hides something has nothing to do with a tick.
*/
import { useEffect, useState } from "react";
import { humanizeDurationLive } from "../../lib/format";
+/**
+ * Whether `sinceMs` has been running for `thresholdMs`: false until that moment, then true.
+ * One re-render at the crossing rather than a ticking clock — the answer changes once, so
+ * anything finer would only cost renders. Undefined `sinceMs` (nothing running, or no start
+ * time known) reads as false for as long as it stays undefined.
+ */
+export function useElapsedPast(sinceMs: number | undefined, thresholdMs: number): boolean {
+ const [reached, setReached] = useState(
+ () => sinceMs !== undefined && Date.now() - sinceMs >= thresholdMs,
+ );
+ useEffect(() => {
+ if (sinceMs === undefined) {
+ setReached(false);
+ return;
+ }
+ const remaining = thresholdMs - (Date.now() - sinceMs);
+ if (remaining <= 0) {
+ setReached(true);
+ return;
+ }
+ setReached(false);
+ const id = setTimeout(() => setReached(true), remaining);
+ return () => clearTimeout(id);
+ }, [sinceMs, thresholdMs]);
+ // The `sinceMs` term is load-bearing: on the render where it goes undefined the effect that
+ // clears `reached` has not run yet, so the state still holds the previous subject's answer.
+ return reached && sinceMs !== undefined;
+}
+
export function LiveDuration({ sinceMs, offsetMs = 0 }: { sinceMs?: number; offsetMs?: number }) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsx
index cef7b4c4..60611138 100644
--- a/packages/web/src/features/chat/tool-call-card.tsx
+++ b/packages/web/src/features/chat/tool-call-card.tsx
@@ -33,7 +33,7 @@ import { toneInk } from "../../lib/tone";
import { StatusIcon } from "../../components/ui/status-icon";
import type { RunState } from "../../components/ui/status-icon";
import { ApprovalButtons } from "./approval-buttons";
-import { LiveDuration } from "./live-duration";
+import { LiveDuration, useElapsedPast } from "./live-duration";
import { useTheme } from "../../state/theme";
import { agentIdFromRunSubagentArgs } from "./agent-topology";
import { SubagentChip } from "./subagent-chip";
@@ -181,11 +181,21 @@ export function isDetachedCall(output: string): boolean {
return output.includes(DETACHED_TOOL_NOTE_PREFIX);
}
+/**
+ * How long a call has to have been executing before the header offers "move to background".
+ * A call that finishes in a few seconds would otherwise flash the action and drop it again,
+ * and the row's right end would jump with every short command; ten seconds is where waiting
+ * starts to feel like waiting.
+ */
+export const BACKGROUND_ACTION_DELAY_MS = 10_000;
+
/**
* Whether the header offers "move to background": only while the call is genuinely executing
- * (that is the whole window in which there is something to move), only for a tool that has a
- * background form, and only on a main-session card — a subagent's call lives in the child
- * Session's environment, which the route does not target.
+ * (that is the whole window in which there is something to move) and has been for
+ * `BACKGROUND_ACTION_DELAY_MS` (`executedPastDelay`, the card's elapsed-time gate on the
+ * execution segment), only for a tool that has a background form, and only on a main-session
+ * card — a subagent's call lives in the child Session's environment, which the route does not
+ * target.
*
* A call launched with `run_in_background` is excluded: its work is already back in the
* registry, so there is nothing left to hand over, and the row would briefly carry the
@@ -196,9 +206,14 @@ export function showsBackgroundAction(
argsJson: string,
executing: boolean,
origin: readonly string[],
+ executedPastDelay: boolean,
): boolean {
return (
- executing && origin.length === 0 && DETACHABLE_TOOLS.has(name) && !isBackgroundCall(argsJson)
+ executing &&
+ executedPastDelay &&
+ origin.length === 0 &&
+ DETACHABLE_TOOLS.has(name) &&
+ !isBackgroundCall(argsJson)
);
}
@@ -307,6 +322,17 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen
const subtitle = headerSubtitle(item.name, item.argumentsText, !item.callStreaming);
// Executing = the call has finished streaming, output hasn't arrived yet, and it's not waiting on approval (approval wait time doesn't count toward execution).
const executing = item.callComplete && !item.outputComplete && !pending;
+ // Whether the execution segment has run long enough for the "move to background" action (one
+ // re-render at that moment, none before or after). Local-first on the start time: this end's
+ // own answer time is there the instant the pending approval clears, while the server's
+ // approvalAtMs is still a broadcast away, so falling straight back to callStartedAtMs in that
+ // window would count the human wait as execution and then restart the gate once the event
+ // lands. Local-first also keeps the value from ever moving again, and it is the clock the
+ // gate compares against.
+ const executedPastDelay = useElapsedPast(
+ executing ? (item.localApprovalAtMs ?? item.approvalAtMs ?? item.callStartedAtMs) : undefined,
+ BACKGROUND_ACTION_DELAY_MS,
+ );
// Argument-generation segment (settled): the live execution timer accumulates on top of this as a baseline, so the displayed duration doesn't shrink back once output arrives.
const genMs =
item.argStartedAtMs !== undefined && item.callStartedAtMs !== undefined
@@ -429,31 +455,41 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen
)
) : null}
</span>
- {/* Right of the duration, on a call made with run_in_background or moved there:
- a bracketed marker in the row's own mono type, the shape this row already used
- for an outcome that needs a word. A glyph here would be the session list's
- count-of-many mark doing duty for a single call, and it would say nothing to a
- reader who cannot spend a hover on it. It sits after the duration rather than
- beside the name so it never competes with the truncating subtitle, and the row's
- own status icon keeps saying what the CALL did — this says where its work went. */}
- {(isBackgroundCall(item.argumentsText) || isDetachedCall(item.output)) && (
- <span className={`shrink-0 font-mono text-xs ${toneInk.muted}`}>
- {S.chat.backgroundCall}
- </span>
- )}
<span className="min-w-0 flex-1" />
</button>
- {/* "Send to background" while the call executes: the tool hands its work back as a
- background task and the turn carries on. A sibling of the row button rather than a
- child — a <button> cannot nest another — with the hover tint on the whole row, so the
- two still read as one line. The app's inline text-action style: a real <button>
- (it acts, it navigates nowhere) painted as a link. Text at the row's own size and
- NO padding of its own, so a row carrying it measures exactly like one that does not
- — an action that changed the row's height would break the rhythm of a list of calls.
+ {/* At the row's right end, on a call made with run_in_background or moved there: a
+ bracketed marker in the row's own mono type, the shape this row already used for an
+ outcome that needs a word. A glyph here would be the session list's count-of-many
+ mark doing duty for a single call, and it would say nothing to a reader who cannot
+ spend a hover on it. It takes the very slot the "send to background" action below
+ occupies — the two never show together, and a click on the action leaves the mark
+ in its place — so the row's right end holds one thing, right-aligned, rather than a
+ word after the duration and an action further along. The row's own status icon
+ keeps saying what the CALL did; this says where its work went. */}
+ {(isBackgroundCall(item.argumentsText) || isDetachedCall(item.output)) && (
+ <span className={`shrink-0 font-mono text-xs ${toneInk.muted}`}>
+ {S.chat.backgroundCall}
+ </span>
+ )}
+ {/* "Send to background" once the call has been executing for a while: the tool hands
+ its work back as a background task and the turn carries on. A sibling of the row
+ button rather than a child — a <button> cannot nest another — with the hover tint on
+ the whole row, so the two still read as one line. The app's inline text-action style:
+ a real <button> (it acts, it navigates nowhere) painted as a link. Text at the row's
+ own size and NO padding of its own, so a row carrying it measures exactly like one
+ that does not — an action that changed the row's height would break the rhythm of a
+ list of calls. It waits BACKGROUND_ACTION_DELAY_MS before appearing: a command that
+ returns in a few seconds never shows an action it would only take away again.
No click guard: a second detach is a no-op on an already-fired controller, and once
the call closes the action unmounts on its own — which is also the feedback. */}
- {showsBackgroundAction(item.name, item.argumentsText, executing, ctx.origin) &&
+ {showsBackgroundAction(
+ item.name,
+ item.argumentsText,
+ executing,
+ ctx.origin,
+ executedPastDelay,
+ ) &&
ctx.onSendToBackground && (
<button
type="button"
diff --git a/packages/web/src/lib/omni/stream-controller.ts b/packages/web/src/lib/omni/stream-controller.ts
index 5fd77bf6..3e87c40d 100644
--- a/packages/web/src/lib/omni/stream-controller.ts
+++ b/packages/web/src/lib/omni/stream-controller.ts
@@ -642,7 +642,16 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
registerLocalDecision(model, toolCallId);
},
resolveApproval: (key) => {
- if (pending.delete(key)) deps.onPendingChange();
+ const entry = pending.get(key);
+ if (entry === undefined) return;
+ pending.delete(key);
+ // The local answer time, stamped as the pending entry goes: the approval_decision event
+ // that sets approvalAtMs lands a broadcast later, and in that window an elapsed-time gate
+ // reading the card would fall back to the call's start and count the human wait as
+ // execution — then jump forward when the event finally arrives.
+ const card = findToolCard(model, entry.origin, entry.toolCall.payload.tool_call_id);
+ if (card) card.localApprovalAtMs = now();
+ deps.onPendingChange();
},
dispose: () => {
disposed = true;
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index ebb4527f..a072885b 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -207,6 +207,16 @@ export interface ToolCallItem {
callStartedAtMs?: number;
/** Approval-granted moment (the approval_decision message time): execution timing starts from here, deducting the approval wait. */
approvalAtMs?: number;
+ /**
+ * The moment THIS client answered the approval, read from the local clock as the decision is
+ * submitted — the approval_decision event that carries approvalAtMs only arrives a broadcast
+ * later. Kept apart from approvalAtMs because that one is a server message time that
+ * noteApprovalWait subtracts callStartedAtMs (another server time) from: a local Date.now()
+ * in there would put two clocks inside one stat, so a skewed client could corrupt
+ * openApprovalWaitMs. Only the UI's elapsed-time gates read this, and they measure against
+ * Date.now(), which is the clock it is already on.
+ */
+ localApprovalAtMs?: number;
/** This card's approval wait has already been counted toward its owning Request (see noteApprovalWait): whichever of the two timestamps arrives later triggers it, guarding against double-counting. */
approvalWaitCounted?: boolean;
/**
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index a93094a3..3fc2c369 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -3,7 +3,8 @@
* authoritative state while streaming (history-closing decision), the generation guard
* against rebuild re-entrancy during replay, resync rebuild (clears the pending table +
* keeps localDecisions), approval re-delivery keyed by origin composite key + missing
- * card backfill, and history load failure/retry.
+ * card backfill, the local answer time an optimistic resolveApproval stamps, and history
+ * load failure/retry.
*/
import { describe, expect, it } from "vitest";
import {
@@ -331,6 +332,33 @@ describe("approval re-delivery (origin composite key + missing-card backfill)",
h.controller.handleOmni(withOrigin(approvalDecision("allow", "t1"), "c1"));
expect(h.controller.pendingApprovals.size).toBe(0);
});
+
+ it("an optimistic resolveApproval stamps this end's answer time, and the later approval_decision fills approvalAtMs without moving it", async () => {
+ const h = createHarness();
+ const p = h.controller.load();
+ const tc = toolCall({
+ name: "exec_command",
+ arguments: '{"cmd":"pnpm dev"}',
+ toolCallId: "t1",
+ });
+ h.resolveLoad([at(tc, "2026-07-05T00:00:00.000Z")]);
+ await p;
+ h.controller.handleServer({ type: "approval_request", toolCall: tc });
+ h.controller.resolveApproval(approvalKey(undefined, "t1"));
+ const card = findToolCard(h.controller.model, undefined, "t1") as ToolCallItem;
+ // The injected clock: clicking removes the pending entry a broadcast before the decision
+ // event, and the card carries the moment this end answered for that whole window.
+ expect(card.localApprovalAtMs).toBe(1_000_000);
+ expect(card.approvalAtMs).toBeUndefined();
+
+ // The event arrives afterwards. approvalAtMs takes the server timestamp — noteApprovalWait
+ // subtracts another server time from it, so it must never be handed a local clock — while
+ // the local stamp stays put, which is what keeps an elapsed-time gate reading it
+ // local-first from seeing its start time move and restarting.
+ h.controller.handleOmni(at(approvalDecision("allow", "t1"), "2026-07-05T00:00:05.000Z"));
+ expect(card.approvalAtMs).toBe(Date.parse("2026-07-05T00:00:05.000Z"));
+ expect(card.localApprovalAtMs).toBe(1_000_000);
+ });
});
describe("resync rebuild", () => {
diff --git a/packages/web/test/tool-call-preview.test.ts b/packages/web/test/tool-call-preview.test.ts
index f3e59198..7d40e22a 100644
--- a/packages/web/test/tool-call-preview.test.ts
+++ b/packages/web/test/tool-call-preview.test.ts
@@ -17,6 +17,7 @@ import {
previewArguments,
shortenPath,
showsBackgroundAction,
+ BACKGROUND_ACTION_DELAY_MS,
} from "../src/features/chat/tool-call-card";
import { S } from "../src/lib/strings";
@@ -198,8 +199,9 @@ describe("isDetachedCall", () => {
it("marks a call whose output carries the note the tool wrote on being moved to the background", () => {
expect(
isDetachedCall(
- "building…\n[moved to the background by the user with process_id proc-12ab34cd; its " +
- "completion will arrive as a user message — no need to poll.]",
+ "building…\n[moved to the background by the user with process_id proc-12ab34cd; leave it " +
+ "running unattended: do not poll it or send it input — its completion will arrive on its " +
+ "own as a [background_task_done] user message.]",
),
).toBe(true);
});
@@ -216,26 +218,37 @@ describe("isDetachedCall", () => {
describe("showsBackgroundAction", () => {
const EXEC = '{"cmd":"pnpm dev"}';
+ /** The card's elapsed-time gate, already crossed. */
+ const PAST = true;
it("offers the action while the two detachable tools execute on a main-session card", () => {
- expect(showsBackgroundAction("exec_command", EXEC, true, [])).toBe(true);
- expect(showsBackgroundAction("run_subagent", '{"prompt":"go"}', true, [])).toBe(true);
+ expect(showsBackgroundAction("exec_command", EXEC, true, [], PAST)).toBe(true);
+ expect(showsBackgroundAction("run_subagent", '{"prompt":"go"}', true, [], PAST)).toBe(true);
+ });
+
+ it("waits for the delay: a call that returns sooner never flashes it", () => {
+ // Ten seconds, measured by useElapsedPast on the card; this function only reads its answer.
+ expect(BACKGROUND_ACTION_DELAY_MS).toBe(10_000);
+ expect(showsBackgroundAction("exec_command", EXEC, true, [], false)).toBe(false);
+ expect(showsBackgroundAction("exec_command", EXEC, true, [], PAST)).toBe(true);
});
it("hides it once the call is no longer executing", () => {
- expect(showsBackgroundAction("exec_command", EXEC, false, [])).toBe(false);
+ expect(showsBackgroundAction("exec_command", EXEC, false, [], PAST)).toBe(false);
});
it("hides it for tools with no background form", () => {
- expect(showsBackgroundAction("read_file", '{"file_path":"a.txt"}', true, [])).toBe(false);
- expect(showsBackgroundAction("input_command", '{"process_id":"proc-1"}', true, [])).toBe(false);
- expect(showsBackgroundAction("mcp__docs__search", "{}", true, [])).toBe(false);
+ expect(showsBackgroundAction("read_file", '{"file_path":"a.txt"}', true, [], PAST)).toBe(false);
+ expect(showsBackgroundAction("input_command", '{"process_id":"proc-1"}', true, [], PAST)).toBe(
+ false,
+ );
+ expect(showsBackgroundAction("mcp__docs__search", "{}", true, [], PAST)).toBe(false);
});
it("hides it on a subagent-nested card: that call lives in the child Session's environment", () => {
- expect(showsBackgroundAction("exec_command", EXEC, true, ["session-child-12ab34cd"])).toBe(
- false,
- );
+ expect(
+ showsBackgroundAction("exec_command", EXEC, true, ["session-child-12ab34cd"], PAST),
+ ).toBe(false);
});
it("hides it on a call already launched with run_in_background: nothing left to hand over", () => {
@@ -245,6 +258,7 @@ describe("showsBackgroundAction", () => {
'{"cmd":"pnpm dev","run_in_background":true}',
true,
[],
+ PAST,
),
).toBe(false);
});