Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] acde63e614 test(terminal): prove an obsolete worker's program gone by its socket, not its pid (#11967)
On Windows the inspector reports no birth times, so the hard-cut test
could only prove the program gone by its pid not answering. Windows
reuses a freed pid at once, so a busy runner could keep the pid alive
under another process for the whole 10 s wait. The program now listens
on a socket of its own, and the test waits for that socket to close.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 06:00:53 +00:00
paseo-bot[bot] 25d9ed2985 fix(app): collapse turns with plugin-rendered work (#11974)
Calculate the summary from the work each card represents so a completed turn folds when a plugin renders its tools and reasoning.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 05:12:58 +00:00
5 changed files with 115 additions and 217 deletions
@@ -948,3 +948,46 @@ it.each([false, true])(
expect(opened.groupsByHostId.size).toBe(0);
},
);
it("folds a completed turn whose plugin replaces every tool and reasoning row", () => {
const present = createStreamPresentation();
const timestamp = new Date();
const tail: StreamItem[] = [
{ kind: "user_message", id: "prompt", text: "Work", timestamp },
{ kind: "thought", id: "reasoning", text: "Plan", status: "ready", timestamp },
toolCall("one", "Bash"),
{ kind: "assistant_message", id: "reply", text: "Done", timestamp },
];
const toolPlugin = installedTransform(installProbe("tool_call"));
const reasoningPlugin = installedTransform(installProbe("reasoning"));
const input = {
...presentationOptions,
tail,
head: [],
display: "collapseTurns" as const,
isTurnActive: false,
};
const transform: TimelineItemTransform = (item) =>
toolPlugin(item)?.flatMap((card) => [card, { ...card, id: `${card.id}/detail` }]) ??
reasoningPlugin(item);
const control = present({ ...input, transform: undefined });
expect(control.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"assistant_message",
]);
const closed = present({ ...input, transform });
expect(closed.tail.map((item) => item.kind)).toEqual(control.tail.map((item) => item.kind));
expect(closed.turns.summaryRowsByHostId.get("prompt")?.tools).toEqual(
control.turns.summaryRowsByHostId.get("prompt")?.tools,
);
const opened = present({ ...input, transform, expandedTurnHostIds: new Set(["prompt"]) });
expect(opened.tail.map((item) => item.kind)).toEqual([
"user_message",
"turn_summary",
"plugin",
"plugin",
"plugin",
"assistant_message",
]);
});
@@ -45,9 +45,14 @@ function summarizeTurn(
getGroupedCalls: CollapseTurnsInput["getGroupedCalls"],
): OverviewSummary {
const calls: (ToolCallItem | ThoughtItem)[] = [];
const countedSources = new Set<string>();
for (const item of items) {
if ((item.kind === "tool_call" || item.kind === "thought") && !isTurnTrigger(item))
calls.push(...(getGroupedCalls(item.id) ?? [item]));
const source = item.kind === "plugin" ? item.source : item;
if (!source || (source.kind !== "tool_call" && source.kind !== "thought")) continue;
if (isTurnTrigger(source) || countedSources.has(source.id)) continue;
// One source tool call can render as several plugin cards.
countedSources.add(source.id);
calls.push(...(getGroupedCalls(source.id) ?? [source]));
}
return summarizeToolCalls(calls);
}
@@ -1,8 +1,6 @@
import { mkdir, rename, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { existsSync, readFileSync } from "node:fs";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -38,66 +36,6 @@ async function commitAll(repository: string, message: string): Promise<string> {
return stdout.trim();
}
async function serveGitHttp({
request,
response,
root,
}: {
request: IncomingMessage;
response: ServerResponse;
root: string;
}) {
const url = new URL(request.url!, "http://localhost");
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);
const child = spawn("git", ["http-backend"], {
env: {
...process.env,
GIT_PROJECT_ROOT: root,
GIT_HTTP_EXPORT_ALL: "1",
PATH_INFO: url.pathname,
QUERY_STRING: url.search.slice(1),
REQUEST_METHOD: request.method,
CONTENT_TYPE: request.headers["content-type"],
CONTENT_LENGTH: String(body.length),
HTTP_GIT_PROTOCOL: request.headers["git-protocol"] as string | undefined,
},
});
const closed = once(child, "close");
child.stdin.end(body);
const output: Buffer[] = [];
for await (const chunk of child.stdout) output.push(chunk as Buffer);
const [code] = await closed;
const data = Buffer.concat(output);
const end = data.indexOf("\r\n\r\n");
if (code !== 0 || end < 0) throw new Error("git http-backend failed");
for (const line of data.subarray(0, end).toString().split("\r\n")) {
const colon = line.indexOf(":");
if (colon < 0) continue;
const name = line.slice(0, colon);
const value = line.slice(colon + 1).trim();
if (name.toLowerCase() === "status") response.statusCode = Number(value.slice(0, 3));
else response.setHeader(name, value);
}
response.end(data.subarray(end + 4));
}
function createGitFixtureServer({ root, posts }: { root: string; posts: string[] }) {
return createServer((request, response) => {
if (
request.headers.authorization !==
`Basic ${Buffer.from("fixture:fake-secret").toString("base64")}`
) {
response.writeHead(401, { "WWW-Authenticate": 'Basic realm="fixture"' }).end();
return;
}
const url = new URL(request.url!, "http://localhost");
if (request.method === "POST") posts.push(url.pathname);
void serveGitHttp({ request, response, root }).catch(() => response.writeHead(500).end());
});
}
/** Points https://github.com/fixture/repository.git at a local repository for the callback. */
async function withGitHubFixture(repository: string, run: () => Promise<void>): Promise<void> {
const overlay = {
@@ -182,98 +120,6 @@ describe("managed Git plugin sources", () => {
});
}, 30_000);
it("downloads only the files of the installed commit, not every blob in history", async () => {
const repository = await createRepository();
// A file that exists only in history, like screenshots a plugin repository later dropped.
await writeFile(path.join(repository, "history-only.bin"), "x".repeat(256 * 1024));
await commitAll(repository, "add a large asset");
const { stdout: historyBlob } = await runGitCommand(["rev-parse", "HEAD:history-only.bin"], {
cwd: repository,
});
await rm(path.join(repository, "history-only.bin"));
await commitAll(repository, "drop the asset");
await runGitCommand(["config", "uploadpack.allowFilter", "true"], { cwd: repository });
await runGitCommand(["config", "uploadpack.allowAnySHA1InWant", "true"], { cwd: repository });
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
roots.push(home);
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({
source: `git:${pathToFileURL(repository).href}`,
});
candidate = await sources.place("managed-example", candidate);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
const { stdout: checkoutRoot } = await runGitCommand(["rev-parse", "--show-toplevel"], {
cwd: candidate.directory,
});
const { stdout: missing } = await runGitCommand(
["rev-list", "--objects", "--all", "--missing=print"],
{ cwd: checkoutRoot.trim() },
);
expect(missing.split("\n")).toContain(`?${historyBlob.trim()}`);
}, 30_000);
it("fetches filtered checkout blobs for credentialed Git installs and updates", async () => {
const repository = await createRepository();
const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-smart-http-"));
roots.push(root);
await runGitCommand(["clone", "--bare", repository, "plugin.git"], { cwd: root });
const bare = path.join(root, "plugin.git");
await runGitCommand(["--git-dir", bare, "config", "uploadpack.allowFilter", "true"], {
cwd: root,
});
const posts: string[] = [];
const server = createGitFixtureServer({ root, posts });
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Expected HTTP port");
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-credential-filter-"));
roots.push(home);
const previous = process.env.GIT_CONFIG_PARAMETERS;
process.env.GIT_CONFIG_PARAMETERS = [previous, "'credential.helper='"]
.filter(Boolean)
.join(" ");
try {
const remote = `http://fixture:fake-secret@127.0.0.1:${address.port}/plugin.git`;
const sources = new ManagedPluginSources(home);
let candidate = await sources.prepareInstall({ source: remote });
candidate = await sources.place("managed-example", candidate);
sources.commit("managed-example", candidate.record);
expect(await readFile(path.join(candidate.directory, "index.server.ts"), "utf8")).toContain(
"export default",
);
expect(posts.length).toBeGreaterThanOrEqual(2);
expect(new Set(posts)).toEqual(new Set(["/plugin.git/git-upload-pack"]));
const installFetches = posts.length;
const config = await readFile(path.join(candidate.directory, ".git", "config"), "utf8");
expect(config).not.toMatch(/fixture:fake-secret/);
expect(config).toContain("https://paseo.invalid/plugin.git");
expect(config).toContain("partialclonefilter = blob:none");
await writeFile(
path.join(repository, "index.server.ts"),
"export default () => 'updated';\n",
);
const revision = await commitAll(repository, "update");
await runGitCommand(["push", bare, "main"], { cwd: repository });
const preview = await sources.preview("managed-example", candidate.directory);
expect(preview.target).toEqual({ kind: "git", commit: revision });
const updated = await sources.prepareUpdate(preview.proposal!, candidate.directory);
expect(await readFile(path.join(updated.directory, "index.server.ts"), "utf8")).toContain(
"updated",
);
expect(posts.length - installFetches).toBeGreaterThanOrEqual(2);
} finally {
if (previous === undefined) delete process.env.GIT_CONFIG_PARAMETERS;
else process.env.GIT_CONFIG_PARAMETERS = previous;
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}, 30_000);
it("offers current default HEAD after installing a tag", async () => {
const repository = await createRepository();
const home = await mkdtemp(path.join(tmpdir(), "paseo-plugin-git-home-"));
@@ -194,7 +194,7 @@ export class ManagedPluginSources {
const commit = await resolveRequestedRef(sourceRoot, input.ref);
if (target?.kind === "git" && commit !== target.commit)
throw new Error("Git target changed since review");
await checkout({ checkoutRoot: sourceRoot, commit, remote });
await checkout(sourceRoot, commit);
record = { kind: "git", remote };
}
const directory = path.resolve(sourceRoot, pluginPath);
@@ -502,7 +502,7 @@ function assertPluginPath(checkoutRoot: string, directory: string): void {
}
}
function gitRemote(remote: string) {
async function clone(remote: string, checkoutRoot: string): Promise<void> {
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
@@ -514,23 +514,12 @@ function gitRemote(remote: string) {
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
return { cloneRemote, envOverlay };
}
async function clone(remote: string, checkoutRoot: string): Promise<void> {
const { cloneRemote, envOverlay } = gitRemote(remote);
try {
// A blobless clone keeps every commit and ref for revision lookups, and checkout fetches
// only the files of the chosen commit. A full clone of a plugin repository with large
// assets in its history can outlast GIT_TIMEOUT_MS on an ordinary connection.
await runGitCommand(
["clone", "--no-checkout", "--filter=blob:none", "--", cloneRemote, checkoutRoot],
{
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
},
);
await runGitCommand(["clone", "--no-checkout", "--", cloneRemote, checkoutRoot], {
cwd: path.dirname(checkoutRoot),
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
} catch (error) {
throw redactRemoteError(error, remote);
}
@@ -556,30 +545,17 @@ function redactRemoteError(error: unknown, remote: string): Error {
return new Error(message);
}
async function checkout({
checkoutRoot,
commit,
remote,
}: {
checkoutRoot: string;
commit: string;
remote: string;
}): Promise<void> {
const { envOverlay } = gitRemote(remote);
try {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay,
timeout: GIT_TIMEOUT_MS,
});
} catch (error) {
throw redactRemoteError(error, remote);
}
async function checkout(checkoutRoot: string, commit: string): Promise<void> {
await runGitCommand(["checkout", "--detach", commit], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
await runGitCommand(["submodule", "update", "--init", "--recursive"], {
cwd: checkoutRoot,
envOverlay: GIT_ENV,
timeout: GIT_TIMEOUT_MS,
});
}
async function resolveRequestedRef(
@@ -600,7 +576,17 @@ async function resolveRequestedRef(
async function resolveRemoteCommit(remote: string, cwd: string, ref?: string): Promise<string> {
if (ref?.startsWith("-")) throw new Error("Plugin Git ref cannot start with '-'");
if (ref && /^[0-9a-f]{40,64}$/.test(ref)) return ref;
const { cloneRemote, envOverlay } = gitRemote(remote);
const publicRemote = redactRemoteCredentials(remote);
const cloneRemote = publicRemote === remote ? remote : "https://paseo.invalid/plugin.git";
const envOverlay =
cloneRemote === remote
? GIT_ENV
: {
...GIT_ENV,
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: `url.${remote}.insteadOf`,
GIT_CONFIG_VALUE_0: cloneRemote,
};
try {
const names = ref
? [`refs/heads/${ref}`, `refs/tags/${ref}^{}`, `refs/tags/${ref}`, ref]
@@ -26,7 +26,7 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
import { delimiter, join } from "node:path";
import { basename, delimiter, join } from "node:path";
import { tmpdir } from "node:os";
import pino from "pino";
import {
@@ -1667,25 +1667,53 @@ async function startManagerWithWorkerProtocol(
}
}
// Whether the program still accepts connections on its socket. Unlike its pid, which Windows
// hands to another process as soon as the program ends and records without a birth time, the
// socket closes with the program and nothing else answers on it.
async function programListens(socketPath: string): Promise<boolean> {
return await new Promise((resolve) => {
const socket = createConnection(socketPath);
socket.once("connect", () => {
socket.destroy();
resolve(true);
});
socket.once("error", () => resolve(false));
});
}
// A terminal running an idle program in a worker that reports `protocolVersion`, left running
// after its daemon lets go (stop --keep-terminals).
// after its daemon lets go (stop --keep-terminals). The program listens on `programSocket`.
async function leaveWorkerWithTerminal(
paseoHome: string,
protocolVersion: number,
): Promise<{ terminalId: string; programPid: number; workerPid: number; cwd: string }> {
): Promise<{
terminalId: string;
programPid: number;
programSocket: string;
workerPid: number;
cwd: string;
}> {
const cwd = mkdtempSync(join(tmpdir(), "worker-terminal-manager-protocol-"));
temporaryDirs.push(cwd);
const programSocket =
process.platform === "win32"
? `\\\\.\\pipe\\paseo-test-program-${basename(cwd)}`
: join(cwd, "program.sock");
const previous = await startManagerWithWorkerProtocol(paseoHome, protocolVersion);
const session = await previous.createTerminal({
workspaceId: "ws-protocol",
cwd,
...nodeTerminalCommand("setInterval(() => {}, 1000);"),
...nodeTerminalCommand(
`require("node:net").createServer().listen(${JSON.stringify(programSocket)}); setInterval(() => {}, 1000);`,
),
});
await waitForCondition(() => programListens(programSocket), 10000);
const [record] = await workerRecords(paseoHome);
await previous.detach();
return {
terminalId: session.id,
programPid: (await recordedTerminalPids(paseoHome)).get(session.id)!,
programSocket,
workerPid: record!.pid,
cwd,
};
@@ -1697,24 +1725,14 @@ it.each([1, 4, 5])(
const paseoHome = createTemporaryHome();
const old = await leaveWorkerWithTerminal(paseoHome, version);
const [record] = await workerRecords(paseoHome);
const program = record!.terminals.find((entry) => entry.id === old.terminalId)!;
const inspector = createTerminalWorkerProcessInspector();
manager = await startRealWorkerManager({ paseoHome });
expect(await readUnconfirmedTerminalCleanup(paseoHome)).toEqual([]);
// Startup launches a replacement worker after cleanup. Either old PID may already
// belong to another process, so verify that the recorded birth identities are gone.
// Startup launches a replacement worker after cleanup. The program's PID may already
// belong to another process, so its own socket is what proves it gone.
await waitForCondition(() => !isProcessAlive(record!.pid), 10000);
await expect
.poll(
async () =>
!isProcessAlive(program.pid) ||
classifyTerminalProgramProcess(program, await inspector.inspect(program.pid)).status ===
"unrelated",
{ timeout: 10000 },
)
.toBe(true);
await expect.poll(() => programListens(old.programSocket), { timeout: 10000 }).toBe(false);
expect(manager.getTerminal(old.terminalId)).toBeUndefined();
const workers = await workerRecords(paseoHome);
expect(workers).toHaveLength(1);