Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] 2ea18296c3 test(server): drive background command start through Codex fake 2026-12-03 21:23:58 +00:00
paseo-bot[bot] a68f30aa50 fix(server): settle Codex background commands on their original row
A shell command can finish after its turn has ended. Keep the command’s original turn ID so its completion updates the running timeline row.
2026-12-03 20:16:13 +00:00
6 changed files with 98 additions and 106 deletions
@@ -497,30 +497,6 @@ it("recognizes forge references in prose but not in code, links or paths", async
});
});
it.each([
["见 src/app/main.ts,还有", ["src/app/main.ts"]],
["改了 src/a/b/c,然后", ["src/a/b/c"]],
["src/foo.ts、src/bar.ts", ["src/foo.ts", "src/bar.ts"]],
["查看:docs/说明.md:12。", ["docs/说明.md:12"]],
["see src/app/main.ts, ok", ["src/app/main.ts"]],
])("recognizes bare file paths next to sentence punctuation: %s", async (source, expected) => {
const prepared = prepareMarkdownSource(source, "/repo");
const tree = recognizeTextLinks(
await parseMarkdown(prepared.render(), { latexMath: false }),
prepared.linkRecognition.text,
prepared.linkRecognition.inlineCode,
);
const parts = tree.children?.[0]?.children ?? [];
expect(parts.map((node) => node.content ?? node.children?.[0]?.content).join("")).toBe(source);
expect(parts.filter((node) => node.type === "Link").map((node) => node.attributes?.url)).toEqual(
expected,
);
expect(toNativeLinkRecognition(prepared.linkRecognition).text).toMatchObject({
isDisabled: false,
isDefault: false,
});
});
describe("bare URL sentence punctuation", () => {
it.each([".", ",", ";", ":", "!", "?", ")", ").", "...", "?!"])(
"leaves %s outside the link and preserves the rendered sentence",
@@ -1251,18 +1227,6 @@ it.each([
).toEqual([token]);
});
it.each([
["更正此前的进度说明:A/B/C/D 主实验", ["A/B/C/D"]],
["修改:src/index.ts,然后提交。", ["src/index.ts"]],
["见(docs/说明.md)。", ["docs/说明.md"]],
["参考「src/index.ts:12」、「README.md」", ["src/index.ts:12", "README.md"]],
["“./scripts/run”…", ["./scripts/run"]],
["文档在 docs/说明.md 里", ["docs/说明.md"]],
])("ends prose paths at CJK and typographic punctuation: %s", (source, expected) => {
const { linkRecognition } = prepareMarkdownSource(source, "/repo");
expect([...source.matchAll(linkRecognition.text)].map(([text]) => text)).toEqual(expected);
});
it.each([
"before/after",
"and/or",
+6 -48
View File
@@ -9,56 +9,11 @@ import { decodeString } from "micromark-util-decode-string";
import { fromMarkdown } from "mdast-util-from-markdown";
import type { Link, Nodes, Paragraph, PhrasingContent, Root } from "mdast";
// CJK, fullwidth and typographic punctuation (、。,:()【】「」“”…) ends bare URLs and prose
// paths; CJK letters do not.
const PUNCTUATION_BOUNDARY_RANGES: readonly (readonly [number, number])[] = [
[0x2018, 0x2019],
[0x201c, 0x201d],
[0x2026, 0x2026],
[0x3000, 0x3003],
[0x3008, 0x3011],
[0x3014, 0x301f],
[0xff01, 0xff0f],
[0xff1a, 0xff20],
[0xff3b, 0xff40],
[0xff5b, 0xff65],
];
function formatCharacterRanges(ranges: readonly (readonly [number, number])[]): string {
const escape = (codePoint: number) =>
`\\u${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
return ranges
.map(([start, end]) => (start === end ? escape(start) : `${escape(start)}-${escape(end)}`))
.join("");
}
/** The parts of `from`..`to` that no excluded range covers. */
function subtractCharacterRanges(
from: number,
to: number,
excluded: readonly (readonly [number, number])[],
): [number, number][] {
const kept: [number, number][] = [];
let next = from;
for (const [start, end] of excluded) {
if (start > next) kept.push([next, start - 1]);
next = end + 1;
}
if (next <= to) kept.push([next, to]);
return kept;
}
const URL_BOUNDARY = formatCharacterRanges(PUNCTUATION_BOUNDARY_RANGES);
// Non-ASCII characters a path can contain: everything from U+0080 except boundary punctuation.
const PATH_NON_ASCII = formatCharacterRanges(
subtractCharacterRanges(0x80, 0xffff, PUNCTUATION_BOUNDARY_RANGES),
);
// Keep this regex in the syntax shared by JavaScript, ICU and java.util.regex.
// The Unicode flag makes Metro expand it to escapes rejected by native engines.
const PATH_CHARACTER = String.raw`[a-zA-Z0-9${PATH_NON_ASCII}_@.%+-]`;
const PATH_CHARACTER = String.raw`[a-zA-Z0-9\u0080-\uFFFF_@.%+-]`;
const PATH_LETTER = String.raw`[a-zA-Z]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9${PATH_NON_ASCII}_@%+-]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9\u0080-\uFFFF_@%+-]`;
const LINE_SUFFIX = String.raw`(?::\d+(?::\d+)?(?:-\d+(?::\d+)?)?)?`;
const FILE_EXTENSIONS = [...ASSISTANT_FILE_EXTENSIONS]
.map((extension) => extension.replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`))
@@ -75,13 +30,16 @@ function createTextPattern(path: string, forgeReferencePattern?: string): RegExp
const forgeReference = forgeReferencePattern ? `|${forgeReferencePattern}` : "";
// The native adapter mistakes a literal + in lookbehind for a quantifier; use its hex escape.
return new RegExp(
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9${PATH_NON_ASCII}_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9${PATH_NON_ASCII}_@%+:/\\-]|\.${PATH_CHARACTER}))`,
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9\u0080-\uFFFF_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9\u0080-\uFFFF_@%+:/\\-]|\.${PATH_CHARACTER}))`,
"g",
);
}
// Matches bare URLs that MD4C does not autolink, like single-label or bracketed hosts.
// Quotes and unbalanced closing parentheses end the URL. Trailing sentence punctuation stays outside.
// CJK, fullwidth and typographic punctuation (、。,()【】「」“”…) also ends it; CJK letters do not.
const URL_BOUNDARY =
"\\u2018\\u2019\\u201C\\u201D\\u2026\\u3000-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\uFF01-\\uFF0F\\uFF1A-\\uFF20\\uFF3B-\\uFF40\\uFF5B-\\uFF65";
const URL_CHARACTER = String.raw`[^\s<>()"'\x60${URL_BOUNDARY}]`;
const URL_GROUP = String.raw`\(${URL_CHARACTER}*\)`;
const BARE_URL = String.raw`https?://(?:${URL_CHARACTER}|${URL_GROUP})*(?:[^\s<>()"'\x60.,;:!?${URL_BOUNDARY}]|${URL_GROUP})`;
@@ -32,6 +32,7 @@ import {
normalizeCodexOutputSchema,
toAgentUsage,
} from "./codex-app-server-agent.js";
import { projectTimelineRows } from "../timeline-projection.js";
import { AgentTimeline, type TimelineEntry } from "../timeline/index.js";
describe("mapCodexPlanUpdateToTodo", () => {
@@ -9292,6 +9293,55 @@ test("retains a disconnected Codex session while it reconnects", async () => {
}
});
test("projects a Codex shell completion after the reply onto its original row", async () => {
const appServer = createFakeCodexAppServer();
const session = new CodexAppServerAgentSession(
createConfig(),
null,
createTestLogger(),
async () => appServer.child,
);
const events: Extract<AgentStreamEvent, { type: "timeline" }>[] = [];
session.subscribe((event) => {
if (event.type === "timeline") events.push(event);
});
try {
await session.startTurn("Start the command and reply without waiting");
await appServer.waitForTurnStart();
const threadId = "thread-1";
const callId = "background-command";
const command = "sleep 40; echo DONE-AFTER-REPLY";
const started = waitForTimelineToolCall(session, callId);
appServer.startsLegacyCommand({ threadId, callId, command });
await expect(started).resolves.toMatchObject({ item: { status: "running" } });
appServer.says({ threadId, itemId: "reply", text: "Sleep started." });
const replied = waitForNextEvent(session, "turn_completed");
appServer.completeTurn();
await replied;
const finished = waitForTimelineToolCall(session, callId);
appServer.completesSilentLegacyCommand({ threadId, callId, command, cwd: "/workspace" });
await expect(finished).resolves.toMatchObject({ item: { status: "completed" } });
const rows = projectTimelineRows({
mode: "projected",
rows: events.map((event, index) => ({
seq: index + 1,
timestamp: "2026-01-01T00:00:00Z",
turnId: event.turnId,
item: event.item,
})),
});
expect(rows.filter(({ item }) => item.type === "tool_call")).toMatchObject([
{ item: { callId, status: "completed", detail: { exitCode: 0 } } },
]);
} finally {
await session.close();
}
});
test("publishes a materialized image before dispatching the following turn completion", async () => {
const appServer = createFakeCodexAppServer();
const session = new CodexAppServerAgentSession(
@@ -3899,6 +3899,8 @@ export class CodexAppServerAgentSession implements AgentSession {
>();
private nextTerminalInteractionOrdinal = 0;
private emittedTerminalInteractionKeys = new Set<string>();
// Shell calls can outlive the foreground turn that started them.
private readonly runningShellTurnIds = new Map<string, string>();
private emittedExecCommandStartedCallIds = new Set<string>();
private emittedExecCommandCompletedCallIds = new Set<string>();
private emittedItemStartedIds = new Set<string>();
@@ -4187,6 +4189,7 @@ export class CodexAppServerAgentSession implements AgentSession {
private handleUnexpectedTermination(error: Error): void {
this.connectionState = "disconnected";
this.background.stop();
this.runningShellTurnIds.clear();
const hasActiveRootTurn = this.activeForegroundTurnId !== null || this.currentTurnId !== null;
this.clearPendingPermissions({ preservePlanApprovals: !hasActiveRootTurn });
if (hasActiveRootTurn) {
@@ -5618,6 +5621,7 @@ export class CodexAppServerAgentSession implements AgentSession {
this.supportsInstructionSnapshots,
);
this.currentThreadId = threadId;
this.runningShellTurnIds.clear();
// Codex writes a forked thread's rollout when it forks it, even before any turn.
this.savedThreadId = threadId;
this.cachedRuntimeInfo = null;
@@ -5911,6 +5915,7 @@ export class CodexAppServerAgentSession implements AgentSession {
private async disposeClient(): Promise<void> {
this.background.stop();
this.runningShellTurnIds.clear();
const client = this.client;
this.connectionState = "disconnected";
this.currentTurnId = null;
@@ -6248,7 +6253,20 @@ export class CodexAppServerAgentSession implements AgentSession {
}
private notifySubscribers(event: AgentStreamEvent): void {
const turnId = getAgentStreamEventTurnId(event) ?? this.activeForegroundTurnId;
let turnId = getAgentStreamEventTurnId(event) ?? this.activeForegroundTurnId;
if (
event.type === "timeline" &&
event.item.type === "tool_call" &&
event.item.detail.type === "shell"
) {
const { callId, status } = event.item;
turnId = this.runningShellTurnIds.get(callId) ?? turnId;
if (status === "running" && turnId) {
this.runningShellTurnIds.set(callId, turnId);
} else {
this.runningShellTurnIds.delete(callId);
}
}
const tagged = turnId ? { ...event, turnId } : event;
if (this.startupEvents) {
this.startupEvents.push(tagged);
@@ -17,16 +17,15 @@ interface FakeSubAgentActivity {
kind: "started" | "interacted" | "interrupted" | "completed";
parentThreadId?: string;
}
interface FakeLegacyCommand {
interface FakeCommand {
threadId: string;
callId: string;
command: string;
}
interface FakeLegacyCommand extends FakeCommand {
output: string;
}
interface FakeSilentCommand {
threadId: string;
callId: string;
command: string;
interface FakeSilentCommand extends FakeCommand {
cwd: string;
}
interface FakeTerminalCommand {
@@ -102,6 +101,7 @@ export interface FakeCodexAppServer {
beginsSubAgentActivity(params: FakeSubAgentActivity): void;
completesSubAgentActivity(params: FakeSubAgentActivity): void;
completesCompaction(params: { threadId: string; itemId: string }): void;
startsLegacyCommand(params: FakeCommand): void;
runsLegacyCommand(params: FakeLegacyCommand): void;
startsFileChange(params: FakeFileChange): void;
appliesLegacyPatch(params: FakeLegacyPatch): void;
@@ -371,6 +371,14 @@ export function createFakeCodexAppServer(
writeNotification(method, { threadId, msg });
}
function startsLegacyCommand(params: FakeCommand): void {
writeLegacyEvent(params.threadId, "codex/event/exec_command_begin", {
type: "exec_command_begin",
call_id: params.callId,
command: params.command,
});
}
return {
child,
recordedRollbacks,
@@ -485,12 +493,9 @@ export function createFakeCodexAppServer(
completesCompaction(params) {
completeItem(params.threadId, { type: "contextCompaction", id: params.itemId });
},
startsLegacyCommand,
runsLegacyCommand(params) {
writeLegacyEvent(params.threadId, "codex/event/exec_command_begin", {
type: "exec_command_begin",
call_id: params.callId,
command: params.command,
});
startsLegacyCommand(params);
writeLegacyEvent(params.threadId, "codex/event/exec_command_output_delta", {
type: "exec_command_output_delta",
call_id: params.callId,
+8 -11
View File
@@ -185,7 +185,9 @@ test("filters by search and clears to all plugins", async ({ page }) => {
await submitSearch(page, "graphite");
await expect(page).toHaveURL(/\/plugins\/all\?q=graphite$/);
await expectSearchResultsAfterDirectory(page, "graphite");
await expect(
page.getByRole("heading", { level: 1, name: /^Results for “graphite”/ }),
).toBeVisible();
await expect(page.getByRole("main").getByRole("link", { name: /Graphite/ })).toBeVisible();
await expect(page.getByRole("link", { name: /Dracula/ })).toHaveCount(0);
@@ -215,7 +217,10 @@ test("submits the visible search term when its input event was missed", async ({
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/plugins\/all\?q=graphite&window=month$/);
await expectSearchResultsAfterDirectory(page, "graphite");
// The URL changes before the results route finishes loading its data and code.
await expect(
page.getByRole("heading", { level: 1, name: /^Results for “graphite”/ }),
).toBeVisible({ timeout: 10000 });
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
@@ -281,7 +286,7 @@ test("searches from the directory on submit, and Back returns to the directory",
await page.keyboard.press("Enter");
await expect(page).toHaveURL(/\/plugins\/all\?q=gra$/);
await expectSearchResultsAfterDirectory(page, "gra");
await expect(page.getByRole("heading", { level: 1, name: /^Results for “gra”/ })).toBeVisible();
expect(await historyLength(page)).toBe(entries + 1);
await page.goBack();
@@ -496,14 +501,6 @@ async function expectDirectorySearch(page: Page, term: string, window: string) {
);
}
// The URL changes as soon as the directory submits, but the results route shows only after
// its registry server call returns. On a loaded CI runner that call has taken over 4 s.
async function expectSearchResultsAfterDirectory(page: Page, term: string) {
await expect(
page.getByRole("heading", { level: 1, name: new RegExp(`^Results for “${term}”`) }),
).toBeVisible({ timeout: 10000 });
}
async function typeSearch(page: Page, term: string) {
await page.getByRole("searchbox", { name: "Search plugins" }).pressSequentially(term);
}