A local-first multi-agent app development platform, built on PenguinHarness
/**
* Mock LLM for E2E. Two protocols, chosen by the request's own path:
* - `/chat/completions` -> the OpenAI Chat Completions branch (openAiChatCompletion), which is
* where a model pinned to `client_type = "openai-chat"` reaches this process (every Volcengine
* Ark row of the catalog does).
* - anything else -> the Anthropic Messages API branch below, which "Branches on request body:"
* - title request (the prompt opens with "You are a title generator.") -> short text
* - files-card probe ("files card test") -> text with two backtick paths (one real, one missing)
* - "files rewrite test <cmd>" -> tool_use(exec_command) running <cmd>, then a short final text
* (files-folders.spec: the Agent rewrites a file the Files panel has open)
* - subagent's own turns (its prompt is the only user text) -> tool_use(exec_command) first,
* then the report text once the tool_result is back — the tool call gives the child a real
* approval point (under always-ask it parks on a NESTED approval, which the subagents-panel
* e2e approves from the panel; under allow-all it auto-runs)
* - parent asked to delegate ("run a subagent") -> tool_use(run_subagent)
* - a repeat delegation later in the same conversation ("run another subagent", keyed on the
* LAST message so history can't shadow it) -> tool_use(run_subagent) again
* - "background server test" -> tool_use(exec_command) whose command outlives its yield
* window (processes.spec: the promoted background process shows in the session's
* process list and can be stopped from there)
* - "background exit test" -> tool_use(exec_command) whose command outlives the yield
* window but exits on its own shortly after (processes.spec: the exited row can be
* removed from the process list)
* - "background pair test" -> two tool_use(exec_command) in one turn: one that stays up and
* one with a long command line that exits shortly after its yield window (processes.spec:
* "clear exited" removes only the exited row; hovering the long command shows it whole)
* - "slow stream test" -> tool_use(exec_command) with a command that prints one line
* every 200ms for ~8s (reload-midstream.spec reloads while its output streams)
* - "slow text test" -> a long text streamed one delta every 200ms for ~8s
* (reload-midstream.spec reloads while the TEXT streams)
* - "read deep path test <path>" -> tool_use(read_file) on <path>, then a short final text
* (path-hints.spec: the card's shortened subtitle keeps the whole path one hover away)
* - "scroll bounce test" -> a three-line paragraph every 50ms for ~4s, for every request of
* that conversation (scroll-follow-bounce.spec wheels up while each reply streams)
* - "image reply test" -> one text answer carrying three image srcs: a Workspace file, a path
* outside the Workspace, and another site's (reply-image.spec: only the first is fetched from
* the Session's file route)
* - last message has tool_result -> final text (turn 2)
* - otherwise (first user turn) -> thinking + text + tool_use(exec_command)
*/
import http from "node:http";
/** The run_subagent prompt; also the marker the mock uses to detect "this is the child session's own request". */
const SUBAGENT_PROMPT = "Count the TODO items in the repository";
/** The long tail of the "background pair test" exited command (processes.spec hovers the row and expects this whole line in the tooltip). */
const PAIR_LONG_ECHO =
"the-exited-process-whose-command-line-runs-far-past-the-width-of-its-row-in-the-details-card";
/** Background-subagent FAILURE prompt: the child session's every request is rejected 400, so its run fails after the retry ladder. */
const SUBAGENT_FAIL_PROMPT = "Fail the TODO count on purpose";
const PORT = Number(process.env.MOCK_PORT || 8931);
/** Count of non-replay requests seen in the "bad stream" conversation: the 1st is cut off (malformed), later ones are retries that get a full tool call. */
let malformedTurns = 0;
/** Count of requests seen in the "transient retry" conversation: the 1st is rejected 503, the 2nd streams normally. */
let transientTurns = 0;
function sse(res, event, data) {
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
function messageStart(res, msgCount = 1) {
sse(res, "message_start", {
type: "message_start",
message: {
id: "msg_mock",
type: "message",
role: "assistant",
model: "claude-4-8",
content: [],
stop_reason: null,
stop_sequence: null,
// Usage grows with context length (as real providers do): more messages in the request
// means a larger prompt. If the mock reported a fixed value, the compaction threshold
// would either be hit on the very first request or never be hit at all, and it wouldn't
// drop back down after compaction — this would make it impossible to reproduce the
// "compaction only triggers at round end" timing, and would send the engine into an
// infinite compaction loop.
usage: {
input_tokens: 40,
output_tokens: 0,
cache_read_input_tokens: 40 * msgCount,
cache_creation_input_tokens: 10,
},
},
});
}
function messageStop(res, stopReason, outputTokens) {
sse(res, "message_delta", {
type: "message_delta",
delta: { stop_reason: stopReason, stop_sequence: null },
usage: { output_tokens: outputTokens },
});
sse(res, "message_stop", { type: "message_stop" });
res.end();
}
function block(res, index, start, deltas, extra) {
sse(res, "content_block_start", { type: "content_block_start", index, content_block: start });
for (const d of deltas)
sse(res, "content_block_delta", { type: "content_block_delta", index, delta: d });
if (extra) sse(res, "content_block_delta", { type: "content_block_delta", index, delta: extra });
sse(res, "content_block_stop", { type: "content_block_stop", index });
}
/**
* One OpenAI Chat Completions request: `chat.completion.chunk` frames, closed by `data: [DONE]`.
*
* video-input.spec drives the video case: the composer inlines a clip on a model that takes one,
* and this answer says back what the model was handed — the media type and the payload's own byte
* length — so the spec can prove the `video_url` part reached the provider through AgentHub's
* patched transformer rather than being dropped, and that it was still the bytes the person
* picked. A request with no video part says so instead (which is how the spec catches a
* "silently filed away as an attachment" regression).
*
* Core's session-title request goes to the same model, so it is answered here too (a one-line
* title) rather than being mistaken for a conversation turn needing a video.
*/
function openAiChatCompletion(res, json) {
const messages = Array.isArray(json.messages) ? json.messages : [];
const parts = messages.flatMap((m) => (Array.isArray(m.content) ? m.content : []));
const text = parts
.filter((p) => p !== null && p.type === "text" && typeof p.text === "string")
.map((p) => p.text)
.join("\n");
const video = parts.find((p) => p !== null && p.type === "video_url");
const url = video !== undefined && video.video_url ? String(video.video_url.url ?? "") : "";
const comma = url.indexOf(",");
const mime = /^data:([^;,]*)/.exec(url)?.[1] ?? "";
const bytes =
comma < 0 ? 0 : Math.floor((url.slice(comma + 1).replace(/[=\s]/g, "").length * 3) / 4);
const answer = text.includes("You are a title generator.")
? "Clip check"
: video !== undefined
? `Saw a video: ${mime}, ${bytes} bytes.`
: "No video in this request.";
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive",
});
const chunk = (delta, finish = null) =>
`data: ${JSON.stringify({
id: "chatcmpl-mock",
object: "chat.completion.chunk",
created: 0,
model: json.model ?? "mock",
choices: [{ index: 0, delta, finish_reason: finish }],
})}\n\n`;
res.write(chunk({ role: "assistant", content: "" }));
res.write(chunk({ content: answer }));
res.write(chunk({}, "stop"));
res.write(
`data: ${JSON.stringify({
id: "chatcmpl-mock",
object: "chat.completion.chunk",
created: 0,
model: json.model ?? "mock",
choices: [],
usage: { prompt_tokens: 20, completion_tokens: 8, total_tokens: 28 },
})}\n\n`,
);
res.write("data: [DONE]\n\n");
res.end();
}
const server = http.createServer((req, res) => {
if (req.method !== "POST") {
res.writeHead(404).end();
return;
}
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
let json = {};
try {
json = JSON.parse(body);
} catch {}
// A model pinned to Chat Completions reaches this process on `/chat/completions`; the
// Anthropic-shaped branches below never see such a request.
if ((req.url ?? "").includes("chat/completions")) {
openAiChatCompletion(res, json);
return;
}
const messages = json.messages || [];
const flat = JSON.stringify(messages);
// Title requests are core's `buildTitlePrompt` (packages/core/src/internal/session-title.ts):
// one instruction *about* a piece of text, no system prompt, opening with this line — no other
// request of a conversation starts that way, so the phrase identifies the branch. (It used to
// key on "concise title", which that prompt no longer says: the branch had gone dead, and every
// title a spec asserted on stayed the host's own first-words fallback.)
const isTitle = flat.includes("You are a title generator.");
// After compaction the new context has only the summary left, so the message count drops
// sharply -> reported usage drops along with it, letting compaction converge.
const msgCount = messages.length;
const hasToolResult = flat.includes("tool_result");
// Child-session request: the context has only the prompt handed down by run_subagent, no parent user input.
const isSubagentTurn = flat.includes(SUBAGENT_PROMPT) && !flat.includes("run a subagent");
const wantsSubagent = flat.includes("run a subagent");
// "Bad stream" test case: the first request streams half the tool_use arguments then cuts
// the connection (no message_stop), so AgentHub reports "stream incomplete" -> GenerativeModel
// resolves it as malformed. On reconnect the engine **resends the input verbatim** — in this
// scenario the failed attempt only has a half tool_call (never committed to the ledger), so
// the retry request carries no [turn_retried] block and is byte-for-byte identical to the
// first request; the mock can only tell them apart by request count (see the malformedTurns counter).
const wantsMalformed = flat.includes("bad stream test");
// "Auth dead" test case: KEY-BASED — requests carrying the bad key (`sk-auth-bad`,
// the Anthropic protocol sends it as the x-api-key header) are rejected with a 401 +
// OpenAI-compatible body code; any other key succeeds with a plain text answer. This
// exercises the recoverable flow end to end: GenerativeModel classifies the 401 as
// failed + code "auth" (never retried) and the composer goes dead; once the spec
// updates the model's key via PUT /models, the very same conversation continues
// (live unlock via credentials_updated + runtime invalidation re-reading the config).
// Gated on !isTitle so a stray title request doesn't hit this branch.
if (flat.includes("auth dead test") && !isTitle) {
if (req.headers["x-api-key"] === "sk-auth-bad") {
res.writeHead(401, { "content-type": "application/json" });
res.end(
JSON.stringify({ error: { code: "invalid_api_key", message: "invalid x-api-key" } }),
);
return;
}
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive",
});
messageStart(res, msgCount);
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Auth restored; hello again." },
]);
messageStop(res, "end_turn", 8);
return;
}
// Background-subagent FAILURE case (background-subagent.spec): the child session's own
// requests (its context is just the fail prompt) are rejected 401 invalid_api_key —
// classified `auth`, which the engine never retries, so the child's run fails at once
// and the FAILED completion report must still arrive promptly (a retryable failure
// would climb the full ~60s reconnect ladder first — same terminal state, just slow).
// Gated on !isTitle so the failed child's title request falls back quietly.
if (
flat.includes(SUBAGENT_FAIL_PROMPT) &&
!flat.includes("background subagent fail test") &&
!isTitle
) {
res.writeHead(401, { "content-type": "application/json" });
res.end(
JSON.stringify({ error: { code: "invalid_api_key", message: "mock child failure" } }),
);
return;
}
// "Transient give-up" test case: EVERY request is rejected 503 (a retryable failure) —
// the spec clicks the reconnect countdown's give-up button mid-wait, so the
// conversation must never recover on its own (the abort ends it instead). 503 rather
// than 403 on purpose: a 4xx is a definitive rejection and ends the turn on attempt 1
// (`isFatalProviderRejection`), which leaves no ladder to give up on.
if (flat.includes("transient giveup test") && !isTitle) {
res.writeHead(503, { "content-type": "application/json" });
res.end(
JSON.stringify({ error: { code: "service_unavailable", message: "upstream unavailable" } }),
);
return;
}
// "Transient retry" test case: the first attempt opens a block, streams nothing, and ends
// cleanly without message_delta / message_stop — AgentHub reports "Streaming response
// yielded no events", GenerativeModel classifies it `malformed` (retryable), and the
// engine reconnects after its backoff base (2s, see context-engine's
// `reconnectBackoffMs`). The wait is exactly the countdown floor, which is the window the
// spec uses to observe the live ticker and click "retry now"; the 2nd attempt streams a
// normal final answer. A broken stream rather than an HTTP 5xx on purpose: the protocol
// SDK retries 5xx internally (~0.4s, measured), which hides the failure from the engine
// and from the Trace.
if (flat.includes("transient retry test") && !isTitle) {
transientTurns += 1;
if (transientTurns <= 1) {
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive",
});
messageStart(res, msgCount);
sse(res, "content_block_start", {
type: "content_block_start",
index: 0,
content_block: { type: "text", text: "" },
});
sse(res, "content_block_stop", { type: "content_block_stop", index: 0 });
res.end(); // ends normally but is missing message_delta/message_stop -> "stream incomplete"
return;
}
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive",
});
messageStart(res, msgCount);
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Service recovered; the answer is 42." },
]);
messageStop(res, "end_turn", 10);
return;
}
// "Quota fatal" test case: every request is rejected 403 with the provider's
// quota-exhaustion code. 4xx is the fatal allowlist (408/429 excluded), so the turn
// ends on the first attempt with the provider's text on screen and no ladder — the
// behaviour `isFatalProviderRejection` pins in core/test/llm.test.ts.
if (flat.includes("quota fatal test") && !isTitle) {
res.writeHead(403, { "content-type": "application/json" });
res.end(
JSON.stringify({
error: { code: "insufficient_user_quota", message: "no active subscription" },
}),
);
return;
}
res.writeHead(200, {
"content-type": "text/event-stream",
"cache-control": "no-cache",
connection: "keep-alive",
});
messageStart(res, msgCount);
if (isTitle) {
// A subagent's title request carries **the run_subagent prompt that spawned it** and
// nothing else (the parent's own title request never contains that prompt); respond
// with a distinguishable title so the E2E test can tell the two titles apart.
const forSubagent = flat.includes(SUBAGENT_PROMPT);
block(res, 0, { type: "text", text: "" }, [
{
type: "text_delta",
text: forSubagent ? "Subagent TODO summary" : "Configure Tailwind theme",
},
]);
messageStop(res, "end_turn", 8);
return;
}
// Files-card test case: the reply carries two backtick paths — demo.html was actually
// written into the Workspace beforehand by the spec via files/content, while
// missing-report.pdf doesn't exist; the card should only list the former. This branch
// must be checked before hasToolResult (the same session's history already has a
// first-round tool_result).
if (flat.includes("files card test")) {
block(res, 0, { type: "text", text: "" }, [
{
type: "text_delta",
text: "Report generated: `demo.html`; the other file `missing-report.pdf` does not exist.",
},
]);
messageStop(res, "end_turn", 18);
return;
}
// Files-panel rewrite test: the Agent rewrites a Workspace file while the panel has it open.
// Keyed on the LAST message, since the history keeps every earlier request of the
// conversation: the user's own text names the command, and its tool_result ends the turn.
const lastMessage = JSON.stringify(messages[messages.length - 1] ?? {});
const rewrite = /files rewrite test ([^"\\]+)/.exec(lastMessage);
if (rewrite) {
block(
res,
0,
{ type: "tool_use", id: "toolu_files_rewrite", name: "exec_command", input: {} },
[{ type: "input_json_delta", partial_json: JSON.stringify({ cmd: rewrite[1].trim() }) }],
);
messageStop(res, "tool_use", 12);
return;
}
// Deep-path read (path-hints.spec): a file's card keeps the whole path one hover away
// (§5.46), so the call has to read a file whose path is longer than the card shows. The
// path travels in the prompt because the mock is another process and the spec creates the
// directory; the tool_result ends the turn. Gated on !isTitle: a title request carries the
// same user text, and answering it with a tool call would leave the Session untitled.
// The stop set is the path's own characters only: the prompt sits inside JSON, so `\S+`
// would swallow the closing quote and braces into the argument.
const deepRead = /read deep path test ([^"\s\\]+)/.exec(lastMessage);
if (deepRead && !isTitle) {
block(res, 0, { type: "tool_use", id: "toolu_deep_read", name: "read_file", input: {} }, [
{ type: "input_json_delta", partial_json: JSON.stringify({ file_path: deepRead[1] }) },
]);
messageStop(res, "tool_use", 12);
return;
}
if (flat.includes("read deep path test") && lastMessage.includes("tool_result") && !isTitle) {
block(res, 0, { type: "text", text: "" }, [{ type: "text_delta", text: "Read the file." }]);
messageStop(res, "end_turn", 6);
return;
}
if (flat.includes("files rewrite test") && lastMessage.includes("tool_result")) {
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "The file was rewritten." },
]);
messageStop(res, "end_turn", 8);
return;
}
if (wantsMalformed && !hasToolResult) {
malformedTurns += 1;
if (malformedTurns === 1) {
sse(res, "content_block_start", {
type: "content_block_start",
index: 0,
content_block: {
type: "tool_use",
id: "toolu_broken_1",
name: "exec_command",
input: {},
},
});
sse(res, "content_block_delta", {
type: "content_block_delta",
index: 0,
delta: { type: "input_json_delta", partial_json: '{"cmd": "ec' },
});
sse(res, "content_block_stop", { type: "content_block_stop", index: 0 });
res.end(); // ends normally but is missing message_delta/message_stop -> AgentHub reports "stream incomplete"
return;
}
// Retry (original input resent): return a complete tool_use, then proceed normally.
block(res, 0, { type: "tool_use", id: "toolu_retry_1", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd"' },
{ type: "input_json_delta", partial_json: ': "echo ok"}' },
]);
messageStop(res, "tool_use", 12);
return;
}
// A REPEAT delegation later in the same conversation (the task-scoped panel e2e needs a
// second spawning Task): keyed on the LAST message only — the whole-history flags above
// ("run a subagent" + hasToolResult) can never take this branch once a first delegation
// sits in the history. The child flow it spawns is identical (same SUBAGENT_PROMPT). The
// ~800ms delay keeps the e2e's two observations in order: the task boundary first CLOSES
// the panel, and only then does this spawn auto-open it again.
const lastFlat = JSON.stringify(messages[messages.length - 1] ?? {});
if (lastFlat.includes("run another subagent")) {
setTimeout(() => {
block(
res,
0,
{ type: "tool_use", id: "toolu_mock_sub2", name: "run_subagent", input: {} },
[
{ type: "input_json_delta", partial_json: '{"prompt": ' },
{ type: "input_json_delta", partial_json: `${JSON.stringify(SUBAGENT_PROMPT)}}` },
],
);
messageStop(res, "tool_use", 15);
}, 800);
return;
}
// Background-notify test case (background-notify.spec): turn 1 launches a command with
// run_in_background (returns a process_id immediately); turn 2 closes the task while
// the command is still running; ~2s later the command exits and the harness injects a
// [background_task_done] user message that auto-starts a task — whose turn is keyed on
// the LAST message (the whole-history flags can't shadow it) and acknowledges.
const lastText = JSON.stringify(messages[messages.length - 1] ?? {});
if (lastText.includes("background_task_done")) {
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Acknowledged: the background command finished (bg-ack)." },
]);
messageStop(res, "end_turn", 9);
return;
}
if (flat.includes("background subagent fail test")) {
if (!hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_bgsubf_1", name: "run_subagent", input: {} }, [
{ type: "input_json_delta", partial_json: '{"prompt": ' },
{
type: "input_json_delta",
partial_json: `${JSON.stringify(SUBAGENT_FAIL_PROMPT)}, "run_in_background": true}`,
},
]);
messageStop(res, "tool_use", 15);
return;
}
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Failing subagent dispatched in the background." },
]);
messageStop(res, "end_turn", 11);
return;
}
// Background-subagent test case (background-subagent.spec): the parent launches the
// subagent with run_in_background and closes its turn; the child branch (isSubagentTurn)
// runs its usual exec_command (sleep 1) then reports. The completion arrives as a
// [background_task_done] user message handled by the lastText branch above.
if (flat.includes("background subagent test")) {
if (!hasToolResult) {
setTimeout(() => {
block(
res,
0,
{ type: "tool_use", id: "toolu_bgsub_1", name: "run_subagent", input: {} },
[
{ type: "input_json_delta", partial_json: '{"prompt": ' },
{
type: "input_json_delta",
partial_json: `${JSON.stringify(SUBAGENT_PROMPT)}, "run_in_background": true}`,
},
],
);
messageStop(res, "tool_use", 15);
}, 300);
return;
}
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Subagent dispatched in the background." },
]);
messageStop(res, "end_turn", 11);
return;
}
if (flat.includes("background notify test")) {
if (!hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_bgn_1", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd": "echo bg-notify; sleep 6",' },
{ type: "input_json_delta", partial_json: ' "run_in_background": true}' },
]);
messageStop(res, "tool_use", 14);
return;
}
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Started in the background; the report will follow." },
]);
messageStop(res, "end_turn", 11);
return;
}
if (isSubagentTurn) {
// Child turn 1: one tool call before reporting (see the header comment — the child needs
// its own approval point for the nested-approval e2e). The command sleeps ~1s so the
// whole parent Task reliably OUTLIVES the draft-flow navigation — the auto-open e2e
// needs the client to attach while the spawn is still live (a real model is far slower;
// without the sleep the mock finishes the entire tree before the page even connects).
// Turn 2: the report text, the exact string the title branch keys on.
if (!hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_sub_exec", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd"' },
{ type: "input_json_delta", partial_json: ': "sleep 1; echo counting"}' },
]);
messageStop(res, "tool_use", 10);
return;
}
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Subagent report: 3 TODOs" },
]);
messageStop(res, "end_turn", 12);
return;
}
// Background-process test case (processes.spec): an exec_command that outlives its
// yield window — the engine promotes it to a background process with a process_id,
// which the session's process list (details popover) must surface and be able to stop.
// The tiny yield keeps the turn snappy; `sleep 600` stands in for a dev server.
if (flat.includes("background server test") && !hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_bg_1", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd": "sleep 600",' },
{ type: "input_json_delta", partial_json: ' "yield_time_ms": 300}' },
]);
messageStop(res, "tool_use", 14);
return;
}
// Background process that EXITS on its own (processes.spec: the exited row keeps its
// "已退出" label and gains a remove button that deletes the entry from the list). The
// command outlives the 300ms yield window — so it is promoted to background — and
// exits ~200ms later, leaving an exited entry behind.
if (flat.includes("background exit test") && !hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_bgexit_1", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd": "sleep 0.5",' },
{ type: "input_json_delta", partial_json: ' "yield_time_ms": 300}' },
]);
messageStop(res, "tool_use", 14);
return;
}
// A running and an exited background process side by side (processes.spec: the list's
// "clear exited" action removes the exited row and leaves the running one). Two calls in
// one turn, both past their 300ms yield window: a long sleep that stays up, and a short
// one that exits ~200ms later — with a command line too long for its row, so the same
// spec can hover it and read the whole command in the tooltip.
if (flat.includes("background pair test") && !hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_bgpair_1", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd": "sleep 600",' },
{ type: "input_json_delta", partial_json: ' "yield_time_ms": 300}' },
]);
block(res, 1, { type: "tool_use", id: "toolu_bgpair_2", name: "exec_command", input: {} }, [
{
type: "input_json_delta",
partial_json: `{"cmd": "sleep 0.5 && echo ${PAIR_LONG_ECHO}",`,
},
{ type: "input_json_delta", partial_json: ' "yield_time_ms": 300}' },
]);
messageStop(res, "tool_use", 28);
return;
}
// Reply-image test case (reply-image.spec): a single-turn answer that shows a picture it made
// into the Workspace, beside one src that names nothing this Session can serve and one that is
// another site's — the three shapes a reply's image src comes in. No tool call: the point is
// what the transcript does with the Markdown, not what the Agent did.
if (flat.includes("image reply test") && !hasToolResult) {
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Here it is.\n\n" },
{ type: "text_delta", text: "\n\n" },
{ type: "text_delta", text: "\n\n" },
{ type: "text_delta", text: "\n" },
]);
messageStop(res, "end_turn", 40);
return;
}
// Slow tool-output test case (reload-midstream.spec): a real exec_command whose output
// streams one line every 200ms for ~8s — long enough to reload the page mid-stream and
// watch the output keep growing afterwards.
if (flat.includes("slow stream test") && !hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_slow_1", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd": "for i in $(seq 1 40); do' },
{ type: "input_json_delta", partial_json: ' echo line $i; sleep 0.2; done"}' },
]);
messageStop(res, "tool_use", 14);
return;
}
// Slow TEXT test case (reload-midstream.spec): a single text block streamed one delta
// every 200ms (~8s total) so the page can be reloaded while the assistant text is
// still streaming. Single turn: ends with end_turn, no tool call.
if (flat.includes("slow text test")) {
sse(res, "content_block_start", {
type: "content_block_start",
index: 0,
content_block: { type: "text", text: "" },
});
let n = 0;
const tick = () => {
n += 1;
sse(res, "content_block_delta", {
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: `chunk-${n} ` },
});
if (n < 40) {
setTimeout(tick, 200);
} else {
sse(res, "content_block_stop", { type: "content_block_stop", index: 0 });
messageStop(res, "end_turn", 80);
}
};
tick();
return;
}
// Scroll-bounce test case (scroll-follow-bounce.spec): a reply that grows by a visible step
// on every commit — one three-line paragraph every 50ms for ~4s — so the reader can wheel up
// from the bottom while the transcript is still following new text. Every request of that
// conversation answers this way, so the spec can stream one reply per gesture.
if (flat.includes("scroll bounce test")) {
sse(res, "content_block_start", {
type: "content_block_start",
index: 0,
content_block: { type: "text", text: "" },
});
const filler =
"The transcript keeps following this reply while it grows, and a reader who scrolls " +
"up from the bottom must stay exactly where the gesture left them, however much text " +
"arrives below, until they scroll back down or press the button that returns them.";
let n = 0;
const tick = () => {
n += 1;
sse(res, "content_block_delta", {
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: `Paragraph ${n}. ${filler}\n\n` },
});
if (n < 80) {
setTimeout(tick, 50);
} else {
sse(res, "content_block_stop", { type: "content_block_stop", index: 0 });
messageStop(res, "end_turn", 4000);
}
};
tick();
return;
}
if (wantsSubagent && !hasToolResult) {
block(res, 0, { type: "tool_use", id: "toolu_mock_sub", name: "run_subagent", input: {} }, [
{ type: "input_json_delta", partial_json: '{"prompt": ' },
{ type: "input_json_delta", partial_json: `${JSON.stringify(SUBAGENT_PROMPT)}}` },
]);
messageStop(res, "tool_use", 15);
return;
}
if (hasToolResult) {
// Turn 2: final answer text. The first sentence is asserted verbatim across several specs —
// keep it byte-identical and in its own paragraph. The rest is a rendering fixture for
// chat.spec: a ~170-char bare URL inside a CJK sentence (must autolink, open in a new tab,
// and wrap instead of widening the page) plus a Markdown table with an unbreakable
// 118-char plain token (must scroll inside the message body, not push the page wide).
block(res, 0, { type: "text", text: "" }, [
{ type: "text_delta", text: "Command finished; " },
{ type: "text_delta", text: "the result looks as expected.\n\n" },
{ type: "text_delta", text: "长链接折行验证:完整报告地址是 " },
{
type: "text_delta",
text: "https://example.com/penguin-harness/reports/2026-07/agent-session-0123456789abcdef0123456789abcdef/artifacts/deep-verification-run-with-a-very-long-descriptive-file-name-v3.html",
},
{ type: "text_delta", text: " ,请在浏览器中打开查看。\n\n" },
{ type: "text_delta", text: "| 指标 | 标识 | 说明 |\n| --- | --- | --- |\n" },
{
type: "text_delta",
text: "| 会话 | agent-session-0123456789abcdef0123456789abcdef-0123456789abcdef0123456789abcdef-final | 长标识验证表格横向滚动 |\n",
},
{ type: "text_delta", text: "| 结果 | completed | 全部通过 |\n" },
]);
messageStop(res, "end_turn", 20);
return;
}
// Turn 1: thinking + text + tool_use, streamed with small delays.
const steps = [];
steps.push(() =>
block(
res,
0,
{ type: "thinking", thinking: "" },
[
{ type: "thinking_delta", thinking: "Let me look at " },
{ type: "thinking_delta", thinking: "the directory structure" },
],
{ type: "signature_delta", signature: "sig_mock_abc" },
),
);
steps.push(() =>
block(res, 1, { type: "text", text: "" }, [
{ type: "text_delta", text: "I'll run a command to check." },
]),
);
steps.push(() =>
block(res, 2, { type: "tool_use", id: "toolu_mock_1", name: "exec_command", input: {} }, [
{ type: "input_json_delta", partial_json: '{"cmd"' },
{ type: "input_json_delta", partial_json: ': "ls -la"}' },
]),
);
let i = 0;
const run = () => {
if (i < steps.length) {
steps[i]();
i += 1;
setTimeout(run, 120);
} else {
messageStop(res, "tool_use", 30);
}
};
run();
});
});
server.listen(PORT, "127.0.0.1", () => {
console.log(`mock-llm on http://127.0.0.1:${PORT}`);
});