Compare commits

..
Author SHA1 Message Date
Okan YILDIRIM 4f2fbe18af fix(archive): bound worktree teardown and stream its output (#9852)
Give worktree teardown commands a shared one-minute deadline. Projects can override it with `worktree.teardownTimeoutMs` in `paseo.json`. Drain output so successful teardowns can exceed the old 1 MiB buffer. Bound the output retained for diagnostics.

At the deadline, try to terminate the command, close its output streams, and keep the worktree on disk. An exit status of zero in response to the stop signal still counts as a timeout.

Closes #9857.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
2026-11-18 13:10:41 +07:00
paseo-bot[bot]andOkan YILDIRIM f81bc2b5a3 Keep the prompt and whole reply when an empty chat reconnects mid-reply (#9723)
Recover missing timeline rows when a chat was empty before disconnect and live reply rows arrive before history catch-up. Keep the replica cache at schema version 1.

Closes #9650.
Supersedes #9626.

Co-authored-by: Okan YILDIRIM <63511519+ragokan@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-18 12:59:03 +07:00
Monarch MaisuriyaandClaude Opus 5.5 3815e72359 fix(desktop): refuse browser screenshots with no painted pixels (#9807)
Viewport and full-page browser screenshots wait for a frame with non-transparent pixels. When the page does not paint within the existing capture budget, the tool returns screenshot_no_frame.

Fixes #9810.

Co-authored-by: monarchmaisuriya <monarchmaisuriya7600@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:47:31 +07:00
paseo-bot[bot]andmgranderath 871c714b46 Create worktrees in large repos without scanning every ignored file (#10020)
List ignored directories as single entries and only search inside them
when a .worktreeinclude pattern matches the directory or names a path
inside it. A bare .env no longer selects node_modules/pkg/.env.

Verified with real Git and isolated daemon workspace creation on Linux.
With 300,000 ignored files, Git trace2 recorded over 6,000 directory
visits before the fix and fewer than five after. The workspace copied
the root .env. The lifecycle test also verified rollback when copying
fails.

Closes #10004

Co-authored-by: mgranderath <22001111+mgranderath@users.noreply.github.com>
2026-11-18 12:26:35 +07:00
Mohamed Boudra f510b3edb7 Tell plugin agents to develop in a directory plugin, never a Git or npm installation (#10061)
* Tell plugin agents to develop in a directory plugin, never a Git or npm installation

paseo plugin update replaces a Git or npm installation and remove deletes it,
so edits and commits made in Paseo's managed copy are lost. The paseo-plugin
skill now says to clone the source outside the daemon home and install that
directory, and to move any work out of a managed copy before update or remove.

Refs #7904

* Rewrite the plugin development guidance as plain steps

* Keep settings, runtime ID, and build output when moving a plugin to a local folder
2026-11-18 12:05:21 +07:00
paseo-bot[bot]andClaude Opus 5.5 a75c2b4635 Keep background workspaces out of the dock badge and favicon (#9983)
* Keep background workspaces out of the dock badge and favicon

A workspace created with `--background` is hidden from the sidebar, but an
agent finishing in it still counted toward the macOS dock badge and turned
the web favicon to attention, pointing at something the user cannot see.

The dock badge now skips background workspaces, and the favicon skips
agents whose workspace is background, the same way both already skipped
background agents. The favicon selector also rescans when the workspace
map changes, so an agent synced before its workspace is dropped once the
workspace arrives.

Closes #9975

* Count background workspaces in the badge while Show background is on

The sidebar shows background workspaces when Show background is on, so
the dock badge and favicon now count them in that case too. They follow
the same setting the sidebar reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 04:55:46 +00:00
38 changed files with 1704 additions and 239 deletions
+4 -1
View File
@@ -117,7 +117,10 @@ There is no renderer prep/restore handshake or lifetime background-throttling ov
Screenshot capture temporarily enables frame production inside the shared serialized queue,
restores the previous throttling policy on success or failure, and retains a 5-second capture budget.
The browser tool takes one viewport frame through Electron's frame subscription and releases the
subscription on completion or cancellation. A resized resident guest can produce fresh pixels
subscription on completion or cancellation. Guest pages have a transparent base background, so a page
that has painted nothing yet (a dev server hiding `body` until its JS boots) produces frames where
every pixel is transparent. Both screenshot paths skip those frames and return `screenshot_no_frame`
when the capture budget expires without a painted one. A resized resident guest can produce fresh pixels
while `capturePage()` leaves its surface-copy request pending; waiting for animation frames or
retrying the copy does not repair that state. Full-page screenshots retain the CDP path with layout
metrics and screenshot clip.
-15
View File
@@ -49,21 +49,6 @@ restarting the process. It writes snapshots and native failure state under
production package. This needs a native rebuild when the Unistyles patch changes; a Metro
reload cannot update it.
To check the first Android composer tap after pinch-to-zoom, install the rebuilt
APK and connect it to a chat whose latest assistant message contains a visible
Markdown image. For example, put `picture.png` in the agent workspace and have
the assistant reply with `![Test image](picture.png)`. Set `CHAT_URL` to the
chat's Paseo deep link and run from the repository root:
```bash
agent-device test packages/app/e2e/mobile/composer-keyboard/lightbox-pinch.android.ad \
--platform android --serial emulator-5554 -e APP_ID=sh.paseo -e "CHAT_URL=$CHAT_URL"
```
Use `APP_ID=sh.paseo.debug` for a development build. If the image has different
alt text, pass it with `-e IMAGE_LABEL="..."`. The test pinches the image, closes
it, types in the composer, and checks that a single Attach tap opens Upload file.
For Android keyboard continuity, run the current checkout in the app, open an idle terminal
with an empty prompt, hide its keyboard, and run:
+11 -3
View File
@@ -49,9 +49,17 @@ Large unbounded timeline responses can exceed relay frame limits, so catch-up us
Page limits are projected-item targets. A tool call lifecycle is one projected item even if it spans many source sequence numbers, and assistant/reasoning chunks are merged before counting. The response carries `seqStart`, `seqEnd`, `sourceSeqRanges`, and `collapsed` so clients can advance sequence cursors without rendering delta rows.
When live delivery detects a sequence gap, the app fetches `direction: "after"`. If the daemon
responds with `hasNewer: true`, the app immediately fetches the next page from `endCursor`. Gap
recovery is complete only when `hasNewer: false`.
When live delivery detects a sequence gap, the app fetches `direction: "after"` its end cursor. If
the daemon responds with `hasNewer: true`, the app immediately fetches the next page from
`endCursor`. Gap recovery is complete only when `hasNewer: false`.
A chat that was empty when it last caught up has no end cursor to compare a live row against. Such a
row starts coverage only if it is the epoch's first row, seq 1. A later row means the chat missed the
rows before it, such as a prompt sent while the app was offline, so the app drops it and recovers
after seq 0. Coverage started at that later row would make the resume page look already applied, and
the chat and its replica cache would keep only the end of the reply. A recovery that waits behind a
running catch-up starts after whatever that catch-up applied, because the app applies a forward page
row by row and an older cursor repeats rows.
Initialization timeouts guard lack of catch-up progress, not the full multi-page sync. A successful page that queues the next `after` page refreshes the watchdog.
@@ -527,7 +527,17 @@ async function expectHiddenStreamingSubmissionOrderAfterWorkspaceEviction(
expect(gate.getClientRequestCount("agent.timeline.set_subscription.request")).toBe(
subscriptionRequests,
);
const requestsBeforeRelease = rememberTimelineRequestCounts(gate, target.agentId);
gate.releaseHeldAgentStreamEvent("turn_started");
// The chat never saw the hidden prompt's live row, so the reply's first row is a gap.
// The chat recovers the missing rows once, while its workspace is still evicted.
await expect
.poll(() => gate.getTimelineRequestCount("after", target.agentId))
.toBe(requestsBeforeRelease.after + 1);
await gate.waitForServerMessage(
"fetch_agent_timeline_response",
gate.getClientRequestCount("fetch_agent_timeline_request"),
);
const requestsBeforeReturn = rememberTimelineRequestCounts(gate, target.agentId);
await waitForWorkspaceInSidebar(page, {
serverId: getServerId(),
@@ -14,6 +14,8 @@ import {
answerFreshnessCheck,
commitTimelineTurnsWhileDisconnected,
disconnectViewedTimeline,
expectEmptyChatSynced,
expectPromptAndWholeReply,
expectResumeAnsweredWithoutFetch,
expectResumeOverflowFallsBackToOneTail,
hideTabAndReturn,
@@ -22,7 +24,11 @@ import {
restoreUnchangedViewedTimeline,
restoreViewedTimelineHoldingCatchUp,
restoreViewedTimelineWithHeldResponse,
restoreViewedTimelineWithLiveRowsFirst,
reopenWithFreshnessCheckUnanswered,
seedStreamingReplyAgent,
sendPromptWhileDisconnected,
stopStreamingReply,
waitForResumeAnswer,
reopenAppWatchingForUpdatingToast,
watchForUpdatingToast,
@@ -147,4 +153,27 @@ test.describe("Agent timeline resume", () => {
await agent.cleanup();
}
});
test("an empty chat that reconnects mid-reply keeps the prompt and the whole reply", async ({
page,
}) => {
test.setTimeout(120_000);
const gate = await installDaemonWebSocketGate(page);
const agent = await seedStreamingReplyAgent();
try {
await openAgentTimeline(page, agent);
await expectEmptyChatSynced(page, gate);
await disconnectViewedTimeline(page, gate);
await sendPromptWhileDisconnected(agent);
await restoreViewedTimelineWithLiveRowsFirst(gate);
const reply = await stopStreamingReply(agent);
await expectPromptAndWholeReply(page, agent, reply);
await page.reload();
await expectPromptAndWholeReply(page, agent, reply);
} finally {
gate.restore();
await agent.cleanup();
}
});
});
@@ -1,15 +0,0 @@
# CHAT_URL opens a connected chat containing a visible Markdown image with alt text IMAGE_LABEL.
context platform=android timeout=120000 retries=0
env APP_ID=sh.paseo.debug
env IMAGE_LABEL="Test image"
open "${APP_ID}" "${CHAT_URL}"
wait "label=\"${IMAGE_LABEL}\"" 30000
press "label=\"${IMAGE_LABEL}\""
wait "label=\"Close image\"" 5000
gesture pinch 1.7
press "label=\"Close image\""
press "editable=true"
type "pinch regression"
press "role=\"button\" label=\"Add attachment\""
wait "label=\"Upload file\"" 3000
@@ -1,5 +1,6 @@
import { expect, type Page } from "@playwright/test";
import type { installDaemonWebSocketGate } from "./daemon-websocket-gate";
import { seedMockAgentWorkspace, type MockAgentWorkspace } from "./mock-agent";
import { readReplicaCache } from "./replica-cache-storage";
import type { LongTimelineAgent } from "./timeline-pagination";
import {
@@ -241,3 +242,100 @@ export async function restoreUnchangedViewedTimeline(
gate.restore();
await expectReconnectingToastGone(page);
}
export interface StreamingReplyAgent extends MockAgentWorkspace {
prompt: string;
}
/**
* A mock agent with no history whose reply streams one word every 100 ms. At 2,000 words the
* reply outlasts the test's timeout, so it is still streaming however long the app takes to
* reconnect. The test ends the turn with {@link stopStreamingReply}.
*/
export async function seedStreamingReplyAgent(): Promise<StreamingReplyAgent> {
const reply = Array.from({ length: 2_000 }, (_unused, index) => `word${index}`).join(" ");
const agent = await seedMockAgentWorkspace({
repoPrefix: "reply-reconnect-",
title: "Reply through reconnect",
featureValues: {
mockStreamingAssistantResponse: reply,
mockStreamingAssistantIntervalMs: 100,
},
});
return {
...agent,
prompt: "stream through a reconnect",
cleanup: async () => {
await agent.client.cancelAgent(agent.agentId).catch(() => undefined);
await agent.cleanup();
},
};
}
interface TimelineReader {
fetchAgentTimeline(
agentId: string,
request: { direction: "tail"; limit: number },
): Promise<{ entries: Array<{ item: { type: string; text?: string } }> }>;
}
async function readDaemonReply(agent: StreamingReplyAgent): Promise<string> {
const timeline = await (agent.client as unknown as TimelineReader).fetchAgentTimeline(
agent.agentId,
{ direction: "tail", limit: 0 },
);
return timeline.entries
.map(({ item }) => (item.type === "assistant_message" ? (item.text ?? "") : ""))
.join("");
}
/** Waits for the empty chat's first catch-up, so the chat is synced with no range. */
export async function expectEmptyChatSynced(page: Page, gate: DaemonWebSocketGate): Promise<void> {
await gate.waitForServerMessage(TIMELINE_RESPONSE);
await expect(page.getByTestId("agent-chat-scroll").filter({ visible: true })).toHaveCount(1, {
timeout: 30_000,
});
}
/** Another client sends the prompt, and the reply starts, while the chat is away. */
export async function sendPromptWhileDisconnected(agent: StreamingReplyAgent): Promise<void> {
await agent.client.sendAgentMessage(agent.agentId, agent.prompt);
await expect.poll(() => readDaemonReply(agent), { timeout: 30_000 }).toContain("word10");
}
/** Reconnects with live reply chunks reaching the chat before the catch-up page that holds them. */
export async function restoreViewedTimelineWithLiveRowsFirst(
gate: DaemonWebSocketGate,
): Promise<void> {
gate.holdNextClientRequest(TIMELINE_REQUEST);
const chunksBeforeReconnect = gate.getAgentStreamItemCount("assistant_message");
gate.restore();
await gate.waitForHeldClientRequest();
await gate.waitForAgentStreamItem("assistant_message", chunksBeforeReconnect + 5);
gate.releaseHeldClientRequest();
}
/** Stops the turn and returns the reply as the daemon recorded it. */
export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<string> {
await agent.client.cancelAgent(agent.agentId);
await agent.client.waitForFinish(agent.agentId, 30_000);
const reply = (await readDaemonReply(agent)).trim();
expect(reply).toMatch(/^word0 word1 word2 .* word10 /);
return reply;
}
export async function expectPromptAndWholeReply(
page: Page,
agent: StreamingReplyAgent,
reply: string,
): Promise<void> {
const chat = page.getByTestId("agent-chat-scroll").filter({ visible: true }).first();
await expect(chat.getByText(agent.prompt, { exact: true })).toBeVisible({ timeout: 30_000 });
await expect
.poll(
async () =>
(await chat.getByTestId("assistant-message").allInnerTexts()).map((text) => text.trim()),
{ timeout: 30_000 },
)
.toEqual([reply]);
}
+11 -2
View File
@@ -6,6 +6,7 @@ import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state";
import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status";
import { isNative } from "@/constants/platform";
import { useSessionStore } from "@/stores/session-store";
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
import { useHosts } from "@/runtime/host-runtime";
type ColorScheme = "dark" | "light";
@@ -85,8 +86,16 @@ export function useFaviconStatus() {
// The favicon reads the whole fleet, so it has to keep every host's directory loading even
// though it no longer subscribes to the agent maps.
useAllDirectoryDemand({ serverIds, enabled: !isNative });
const selectFaviconStatus = useMemo(createFaviconStatusSelector, []);
const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []);
// Background workspaces count exactly when the sidebar shows them.
const showBackground = useSidebarViewStore((state) => state.showBackground);
const selectFaviconStatus = useMemo(
() => createFaviconStatusSelector({ showBackground }),
[showBackground],
);
const selectMacDockBadgeCount = useMemo(
() => createMacDockBadgeCountSelector({ showBackground }),
[showBackground],
);
const status = useSessionStore(selectFaviconStatus);
const dockBadgeCount = useSessionStore(selectMacDockBadgeCount);
const [colorScheme, setColorScheme] = useState<ColorScheme>(getSystemColorScheme);
+315
View File
@@ -6,6 +6,7 @@ import {
type SqliteValue,
} from "@/runtime/replica-cache/row-store-sqlite";
import { afterEach, describe, expect, it } from "vitest";
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import type { CachedTimeline } from "@/runtime/replica-cache";
import {
@@ -17,6 +18,8 @@ import {
} from "@/stores/session-store";
import { useCreateFlowStore, type PendingCreateAttempt } from "@/stores/create-flow-store";
import type { StreamItem } from "@/types/stream";
import type { AgentStreamReducerEvent } from "./session-stream-reducers";
import type { ProjectedTimelineForwardFetchPlan } from "./timeline-sync-plan";
import { reduceTurnLiveness, type TurnLivenessTransition } from "./turn-liveness";
import {
createTimelineReplica,
@@ -1379,6 +1382,318 @@ describe("create handoff lifetime", () => {
});
});
describe("a chat that was empty when it went offline", () => {
const EPOCH = "epoch-1";
const PROMPT = "stream through a reconnect";
const THOUGHT = "Thinking before the reply.";
const TURN_ID = "turn-1";
const TIMESTAMP = "2026-10-31T10:00:00.000Z";
/** The daemon's timeline: one row per flushed chunk, read back as projected pages. */
class DaemonTimeline {
private readonly rows: Array<{ seq: number; item: AgentTimelineItem }> = [];
record(timelineItem: AgentTimelineItem): AgentStreamReducerEvent {
const seq = this.rows.length + 1;
this.rows.push({ seq, item: timelineItem });
return {
event: { type: "timeline", provider: "mock", turnId: TURN_ID, item: timelineItem },
seq,
epoch: EPOCH,
timestamp: new Date(TIMESTAMP),
};
}
page(request: ProjectedTimelineForwardFetchPlan): TimelineResponsePayload {
const maxSeq = this.rows.at(-1)?.seq ?? 0;
const after = request.direction === "after" ? request.cursor.seq : 0;
const entries = this.projected().filter((entry) => entry.seqEnd > after);
const first = entries[0];
const startSeq = request.direction === "after" ? after + 1 : first?.seqStart;
return {
requestId: `${request.direction}-${after}`,
agentId: AGENT_ID,
agent: null,
direction: request.direction,
projection: "projected",
reset: false,
epoch: EPOCH,
window: { minSeq: this.rows[0]?.seq ?? 0, maxSeq, nextSeq: maxSeq + 1 },
startCursor: first && startSeq !== undefined ? { epoch: EPOCH, seq: startSeq } : null,
endCursor: first ? { epoch: EPOCH, seq: maxSeq } : null,
entries,
error: null,
hasNewer: false,
hasOlder: after > 0,
staleCursor: false,
gap: false,
};
}
/** Contiguous reply and thought chunks read back as one row, like the daemon's projection. */
private projected(): TimelineResponsePayload["entries"] {
const entries: TimelineResponsePayload["entries"] = [];
for (const { seq, item: row } of this.rows) {
const previous = entries.at(-1);
const continues =
previous !== undefined &&
((row.type === "assistant_message" &&
previous.item.type === "assistant_message" &&
previous.item.messageId === row.messageId) ||
(row.type === "reasoning" && previous.item.type === "reasoning"));
if (
continues &&
(previous.item.type === "assistant_message" || previous.item.type === "reasoning") &&
(row.type === "assistant_message" || row.type === "reasoning")
) {
previous.item = { ...previous.item, text: `${previous.item.text}${row.text}` };
previous.seqEnd = seq;
previous.sourceSeqRanges = [{ startSeq: previous.seqStart, endSeq: seq }];
previous.collapsed = [
row.type === "assistant_message" ? "assistant_merge" : "reasoning_merge",
];
continue;
}
entries.push({
provider: "mock",
item: row,
timestamp: TIMESTAMP,
seqStart: seq,
seqEnd: seq,
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
collapsed: [],
turnId: TURN_ID,
});
}
return entries;
}
}
interface PendingFetch {
request: ProjectedTimelineForwardFetchPlan;
/** Delivers a page the way the host runtime does: queued live chunks first, then the page. */
deliver(page: TimelineResponsePayload): void;
}
function openChat(storage: TimelineReplicaStorage) {
const fetches: PendingFetch[] = [];
const errors: unknown[] = [];
const fetch = (request: ProjectedTimelineForwardFetchPlan) =>
new Promise<{ hasNewer: boolean; endCursor: { epoch: string; seq: number } | null }>(
(resolve) => {
fetches.push({
request,
deliver: (page) => {
owner.flushStreamAgent(AGENT_ID);
owner.applyTimelineResponse(page);
resolve({ hasNewer: page.hasNewer, endCursor: page.endCursor });
},
});
},
);
const replica = createTimelineReplica({
serverId: SERVER_ID,
storage,
prepareAgent: async () => undefined,
});
const owner = createViewedTimelineOwner({
serverId: SERVER_ID,
replica,
replaceDemandedAgentIds: () => undefined,
drainQueuedAgentMessage: () => undefined,
applyTurnLiveness: () => undefined,
ports: {
canCheckFreshness: () => true,
observe: () => ({ ready: Promise.resolve(), release: async () => undefined }),
readCursor: (agentId) => {
const timeline = selectAgentTimelineState(
useSessionStore.getState().sessions[SERVER_ID],
agentId,
);
return timeline.status === "synced" && timeline.range
? { epoch: timeline.range.epoch, endSeq: timeline.range.endSeq }
: undefined;
},
fetchPage: (_agentId, request) => fetch(request),
fetchLatestTail: () =>
fetch({ direction: "tail", limit: 40, projection: "projected", wholeTurns: true }),
reportError: (error) => errors.push(error),
},
});
owner.setConnected(true);
owner.replaceVisibleAgentIds("test", [AGENT_ID]);
return {
owner,
async nextFetch(): Promise<PendingFetch> {
await expect.poll(() => fetches.length).toBeGreaterThan(0);
return fetches.shift()!;
},
live(event: AgentStreamReducerEvent): void {
owner.applyStreamEvent(AGENT_ID, event);
owner.flushStreamAgent(AGENT_ID);
},
/** Answers every catch-up the chat still asks for until it reports itself current. */
async settle(daemon: DaemonTimeline): Promise<void> {
for (let turn = 0; turn < 20; turn += 1) {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(errors).toEqual([]);
const next = fetches.shift();
if (next) next.deliver(daemon.page(next.request));
else if (owner.getAgentTimelineStatus(AGENT_ID) === "ready") return;
}
throw new Error("The chat never caught up");
},
};
}
function rows(): Array<{ kind: StreamItem["kind"]; text: string }> {
const session = useSessionStore.getState().sessions[SERVER_ID];
return [
...(session?.agentStreamTail.get(AGENT_ID) ?? []),
...(session?.agentStreamHead.get(AGENT_ID) ?? []),
].map((entry) => ({
kind: entry.kind,
text: "text" in entry && typeof entry.text === "string" ? entry.text : "",
}));
}
const reply = (words: number) =>
Array.from({ length: words }, (_unused, index) => `word${index}`).join(" ");
const chunk = (index: number) => `${index === 0 ? "" : " "}word${index}`;
const replyChunk = (index: number): AgentTimelineItem => ({
type: "assistant_message",
text: chunk(index),
messageId: "reply-1",
});
/**
* Opens the chat while its timeline is empty, then drops the connection while the prompt,
* an optional thought and the first three reply chunks are recorded.
*/
async function goOfflineWhileTheReplyStarts(input: {
reasoning: boolean;
storage: TimelineReplicaStorage;
}) {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const daemon = new DaemonTimeline();
const chat = openChat(input.storage);
const opened = await chat.nextFetch();
opened.deliver(daemon.page(opened.request));
expect(
selectAgentTimelineState(useSessionStore.getState().sessions[SERVER_ID], AGENT_ID),
).toEqual({ status: "synced", items: [], range: null, older: "none", newer: "none" });
chat.owner.setConnected(false);
daemon.record({ type: "user_message", text: PROMPT, messageId: "prompt-1" });
if (input.reasoning) daemon.record({ type: "reasoning", text: THOUGHT });
for (const index of [0, 1, 2]) daemon.record(replyChunk(index));
chat.owner.setConnected(true);
const catchUp = await chat.nextFetch();
return { daemon, chat, catchUp };
}
function expectedRows(reasoning: boolean, words: number) {
return [
{ kind: "user_message", text: PROMPT },
...(reasoning ? [{ kind: "thought", text: THOUGHT }] : []),
{ kind: "assistant_message", text: reply(words) },
];
}
/** A saved range that starts after the prompt claims history the chat never received. */
function expectCoverageFromTheFirstRow(commits: CachedTimeline[]): void {
expect(commits.map((commit) => commit.range?.startSeq ?? 1)).toEqual(commits.map(() => 1));
}
it.each([true, false])(
"keeps the prompt and the whole reply when live chunks arrive before a page that holds them (reasoning=%s)",
async (reasoning) => {
const commits: CachedTimeline[] = [];
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
reasoning,
storage: {
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
},
});
try {
chat.live(daemon.record(replyChunk(3)));
chat.live(daemon.record(replyChunk(4)));
catchUp.deliver(daemon.page(catchUp.request));
chat.live(daemon.record(replyChunk(5)));
await chat.settle(daemon);
expect(rows()).toEqual(expectedRows(reasoning, 6));
expectCoverageFromTheFirstRow(commits);
} finally {
chat.owner.dispose();
}
// The saved chat paints the same rows after a reload.
const saved = commits.at(-1);
useSessionStore.getState().clearSession(SERVER_ID);
useSessionStore.getState().initializeSession(SERVER_ID, null);
const reopened = createOwner({
readTimeline: async () => saved,
commitTimeline: () => undefined,
});
try {
reopened.replaceVisibleAgentIds("test", [AGENT_ID]);
await expect.poll(rows).toEqual(expectedRows(reasoning, 6));
} finally {
reopened.dispose();
}
},
);
it("keeps the prompt when the page already holds a chunk the chat has not seen live", async () => {
const commits: CachedTimeline[] = [];
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
reasoning: true,
storage: {
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
},
});
try {
chat.live(daemon.record(replyChunk(3)));
const notYetLive = daemon.record(replyChunk(4));
catchUp.deliver(daemon.page(catchUp.request));
chat.live(notYetLive);
chat.live(daemon.record(replyChunk(5)));
await chat.settle(daemon);
expect(rows()).toEqual(expectedRows(true, 6));
expectCoverageFromTheFirstRow(commits);
} finally {
chat.owner.dispose();
}
});
it("finishes the reply when its last chunks arrive while an older page is in flight", async () => {
const commits: CachedTimeline[] = [];
const { daemon, chat, catchUp } = await goOfflineWhileTheReplyStarts({
reasoning: true,
storage: {
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
},
});
try {
const olderPage = daemon.page(catchUp.request);
chat.live(daemon.record(replyChunk(3)));
chat.live(daemon.record(replyChunk(4)));
catchUp.deliver(olderPage);
await chat.settle(daemon);
expect(rows()).toEqual(expectedRows(true, 5));
expectCoverageFromTheFirstRow(commits);
} finally {
chat.owner.dispose();
}
});
});
function createSqliteCache() {
const database = new DatabaseSync(":memory:");
let beforeRead = async () => {};
@@ -53,6 +53,7 @@ it.each([false, true])(
(hasAuthoritativeBaseline) => {
let head: StreamItem[] = [];
let tail: StreamItem[] = [];
let cursor: TimelineCursor | undefined;
for (const [index, turnId] of ["turn-1", "turn-2"].entries()) {
const result = processAgentStreamEvent({
event: {
@@ -65,12 +66,13 @@ it.each([false, true])(
epoch: "epoch-1",
currentTail: tail,
currentHead: head,
currentCursor: undefined,
currentCursor: cursor,
timestamp: new Date(1000),
hasAuthoritativeBaseline,
});
head = result.head;
tail = result.tail;
cursor = result.cursor ?? cursor;
}
expect([...tail, ...head]).toMatchObject([
{ kind: "thought", text: "turn-1", turnId: "turn-1" },
@@ -2848,7 +2850,7 @@ describe("processTimelineResponse", () => {
],
currentTail: [],
currentHead: [],
currentCursor: undefined,
currentCursor: { epoch: "epoch-1", startSeq: 60, endSeq: 79 },
});
expect(getAssistantTexts([...live.tail, ...live.head])).toEqual([
"First paragraph.\n\nSecond paragraph.",
@@ -3677,6 +3679,7 @@ describe("processAgentStreamEvent", () => {
event: makeAssistantTimelineEvent("[System Error] failed"),
epoch: "timeline-1",
seq: 42,
currentCursor: { epoch: "timeline-1", startSeq: 1, endSeq: 41 },
});
expect(result.head).toEqual([
@@ -3897,6 +3900,24 @@ describe("processAgentStreamEvent", () => {
});
});
it("catches up from the first row when a chat that was empty receives a later row", () => {
const result = processAgentStreamEvent({
...baseStreamInput,
event: makeTimelineEvent("word3"),
seq: 6,
epoch: "epoch-1",
currentCursor: undefined,
});
expect(result).toMatchObject({
head: [],
changedHead: false,
cursor: null,
cursorChanged: false,
sideEffects: [{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 0 } }],
});
});
it("renders a live row over painted items without creating an authoritative cursor", () => {
const result = processAgentStreamEvent({
...baseStreamInput,
@@ -4087,7 +4108,7 @@ describe("processAgentStreamEvents", () => {
],
currentTail: [],
currentHead: [],
currentCursor: undefined,
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 237 },
});
expect(result.changedTail).toBe(false);
@@ -4261,6 +4282,7 @@ describe("processAgentStreamEvents", () => {
currentTail: [],
currentHead: [],
currentCursor: undefined,
hasAuthoritativeBaseline: false,
timestamp: new Date("2026-05-02T10:00:00.186Z"),
});
@@ -4462,7 +4484,7 @@ describe("createAgentStreamReducerQueue", () => {
const scheduler = createManualScheduler();
let currentTail: StreamItem[] = [];
let currentHead: StreamItem[] = [];
let currentCursor: TimelineCursor | undefined;
let currentCursor: TimelineCursor | undefined = { epoch: "epoch-1", startSeq: 1, endSeq: 1 };
const queue = createAgentStreamReducerQueue({
getSnapshot: () => ({
@@ -4505,7 +4527,7 @@ describe("createAgentStreamReducerQueue", () => {
expect(getAssistantTexts(currentHead)).toEqual(["This is a paragraph continues."]);
expect(currentCursor).toEqual({
epoch: "epoch-1",
startSeq: 2,
startSeq: 1,
endSeq: 4,
});
});
@@ -289,7 +289,10 @@ function classifySessionTimelineSeq({
seq: number;
}): SessionTimelineSeqDecision {
if (!cursor) {
return "init";
// A synced chat without coverage was empty when it last caught up. Only an epoch's
// first row can start coverage; a later row means rows before it were missed, for
// example while offline, and a cursor started there would hide them from catch-up.
return seq === 1 ? "init" : "gap";
}
if (cursor.epoch !== epoch) {
return "drop_epoch";
@@ -1543,14 +1546,14 @@ function processTimelineSequencingGate(input: {
return {
...base,
shouldApplyStreamEvent: false,
sideEffects: currentCursor
? [
{
type: "catch_up",
cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq },
},
]
: [],
sideEffects: [
{
type: "catch_up",
cursor: currentCursor
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
: { epoch, endSeq: 0 },
},
],
};
}
if (decision === "drop_epoch" && seq === 1) {
@@ -64,6 +64,21 @@ export function planTimelineResumeFetch(
: planTimelineTailFetch();
}
/**
* A catch-up that waited behind another starts after the rows applied meanwhile. A forward
* page is applied row by row, so asking again for rows the chat already holds repeats them.
*/
export function planTimelineCatchUpPastApplied(
request: ProjectedTimelineForwardFetchPlan,
applied: { epoch: string; endSeq: number } | undefined,
): ProjectedTimelineForwardFetchPlan {
if (request.direction !== "after" || !applied) return request;
if (applied.epoch !== request.cursor.epoch || applied.endSeq <= request.cursor.seq) {
return request;
}
return planTimelineCatchUpAfter({ epoch: applied.epoch, seq: applied.endSeq });
}
export function planTimelineOlderFetch(cursor: TimelineSyncCursor) {
return {
direction: "before",
@@ -441,6 +441,96 @@ test("a gap absorbed by a running tail is recovered after the tail completes", a
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
});
test("a gap parked behind a running tail resumes after the rows that tail applied", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
(await world.nextMembership()).succeed();
const tail = await world.nextFetch("agent-a");
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 7 });
tail.respond({ hasNewer: false, seq: 7 });
const recovery = await world.nextFetch("agent-a");
expect(recovery.request).toEqual({
direction: "after",
cursor: { epoch: "epoch-agent-a", seq: 7 },
limit: 40,
projection: "projected",
wholeTurns: true,
});
recovery.respond({ hasNewer: false, seq: 7 });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.dispose();
});
test("a chat without coverage that recovers a gap loads the latest tail when history overflows a page", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
(await world.nextMembership()).succeed();
const tail = await world.nextFetch("agent-a");
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
tail.respond({ hasNewer: false, seq: 0 });
const recovery = await world.nextFetch("agent-a");
expect(recovery.request).toEqual({
direction: "after",
cursor: { epoch: "epoch-agent-a", seq: 0 },
limit: 40,
projection: "projected",
wholeTurns: true,
});
recovery.respond({ hasNewer: true, seq: 40 });
const fallback = await world.nextFetch("agent-a");
expect(fallback.request).toEqual({
direction: "tail",
limit: 40,
projection: "projected",
wholeTurns: true,
});
fallback.respond({ hasNewer: false, seq: 90 });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.dispose();
});
test("a recovery's follow-up page starts after rows another fetch applied meanwhile", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
world.sync.replaceVisibleAgentIds("workspace", ["agent-a"]);
(await world.nextMembership()).succeed();
(await world.nextFetch("agent-a")).respond({ hasNewer: false, seq: 0 });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 0 });
const firstPage = await world.nextFetch("agent-a");
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 40 });
firstPage.respond({ hasNewer: true, seq: 40 });
const latestTail = await world.nextFetch("agent-a");
expect(latestTail.request.direction).toBe("tail");
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 40 });
const recovery = await world.nextFetch("agent-a");
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 300 });
latestTail.respond({ hasNewer: false, seq: 300 });
recovery.respond({ hasNewer: true, seq: 80 });
const followUp = await world.nextFetch("agent-a");
expect(followUp.request).toEqual({
direction: "after",
cursor: { epoch: "epoch-agent-a", seq: 300 },
limit: 40,
projection: "projected",
wholeTurns: true,
});
followUp.respond({ hasNewer: false, seq: 300 });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.dispose();
});
test("reports a chat current only once its parked follow-up page completes", async () => {
const world = new TimelineWorld();
world.sync.setConnected(true);
@@ -885,7 +975,8 @@ test("gap recovery supersedes completed catch-up and pages through the current t
const membership = await world.nextMembership();
membership.succeed();
const initial = await world.nextFetch("agent-a");
initial.respond({ hasNewer: false });
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
initial.respond({ hasNewer: false, seq: 10 });
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
@@ -1,5 +1,6 @@
import {
planTimelineCatchUpAfter,
planTimelineCatchUpPastApplied,
planTimelineResumeFetch,
type ProjectedTimelineForwardFetchPlan,
} from "./timeline-sync-plan";
@@ -741,7 +742,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
await fetchUntilCurrent(
agentId,
generation,
planTimelineCatchUpAfter(page.endCursor),
planTimelineCatchUpPastApplied(
planTimelineCatchUpAfter(page.endCursor),
ports.readCursor(agentId),
),
false,
);
return;
@@ -819,7 +823,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
ensureCacheLoaded(agentId);
return;
}
const nextRequest = request ?? planTimelineResumeFetch(ports.readCursor(agentId));
const applied = ports.readCursor(agentId);
const nextRequest = request
? planTimelineCatchUpPastApplied(request, applied)
: planTimelineResumeFetch(applied);
const current = catchUps.get(agentId);
const decision = decideCatchUp({ current, request: nextRequest, supersede });
if (decision === "keep-and-park") {
@@ -833,11 +840,13 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
catchUpGenerations.set(agentId, generation);
catchUps.set(agentId, { generation, status: "running", request: nextRequest });
pendingCatchUps.delete(agentId);
// A gap recovery pages forward to keep the coverage it extends. Without coverage there is
// nothing to keep, so an overflowing page falls back to the latest tail, as a resume does.
void fetchUntilCurrent(
agentId,
generation,
nextRequest,
request === undefined && nextRequest.direction === "after",
nextRequest.direction === "after" && (request === undefined || applied === undefined),
);
};
@@ -73,6 +73,18 @@ describe("desktop-badge-state", () => {
expect(selectMacDockBadgeCount(state)).toBe(3);
});
it("leaves out background workspaces, which the sidebar hides", () => {
const hidden = { ...workspace("a", "attention"), background: true };
expect(selectMacDockBadgeCount(stateWith(hidden))).toBeUndefined();
expect(selectMacDockBadgeCount(stateWith(hidden, workspace("b", "failed")))).toBe(1);
});
it("counts background workspaces while Show background puts them in the sidebar", () => {
const hidden = { ...workspace("a", "attention"), background: true };
expect(selectMacDockBadgeCount(stateWith(hidden), { showBackground: true })).toBe(1);
expect(createMacDockBadgeCountSelector({ showBackground: true })(stateWith(hidden))).toBe(1);
});
it("recounts only when a workspace map is replaced", () => {
const select = createMacDockBadgeCountSelector();
const state = stateWith(workspace("a", "attention"));
+16 -6
View File
@@ -19,11 +19,21 @@ export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspa
* The macOS dock badge only needs a count, so count here instead of materialising every
* workspace status and comparing the whole list on every store write.
*/
export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | undefined {
export interface DockBadgeOptions {
/** Count background workspaces too, as the sidebar shows them while Show background is on. */
showBackground?: boolean;
}
export function selectMacDockBadgeCount(
state: WorkspaceStatusSource,
options: DockBadgeOptions = {},
): number | undefined {
let actionableCount = 0;
for (const session of Object.values(state.sessions)) {
if (!session) continue;
for (const workspace of session.workspaces.values()) {
// A hidden background workspace would leave the badge pointing at nothing in the sidebar.
if (workspace.background && !options.showBackground) continue;
if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1;
}
}
@@ -31,11 +41,11 @@ export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number |
}
/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */
export function createMacDockBadgeCountSelector(): (
state: WorkspaceStatusSource,
) => number | undefined {
export function createMacDockBadgeCountSelector(
options: DockBadgeOptions = {},
): (state: WorkspaceStatusSource) => number | undefined {
return memoizeOnSessionMaps<WorkspaceStatusSession, WorkspaceStatusSource, number | undefined>(
(session) => session.workspaces,
selectMacDockBadgeCount,
(session) => [session.workspaces],
(state) => selectMacDockBadgeCount(state, options),
);
}
+59 -2
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import type { Agent } from "@/stores/session-store";
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status";
function agent(input: Partial<Agent> & { id: string }): Agent {
@@ -14,7 +14,21 @@ function agent(input: Partial<Agent> & { id: string }): Agent {
}
function stateWith(...agents: Agent[]) {
return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } };
return stateWithWorkspaces([], ...agents);
}
function stateWithWorkspaces(
workspaces: Array<Pick<WorkspaceDescriptor, "id" | "background">>,
...agents: Agent[]
) {
return {
sessions: {
srv: {
agents: new Map(agents.map((entry) => [entry.id, entry])),
workspaces: new Map(workspaces.map((entry) => [entry.id, entry])),
},
},
};
}
describe("deriveFaviconStatus", () => {
@@ -50,6 +64,37 @@ describe("deriveFaviconStatus", () => {
),
).toBe("none");
});
it("ignores agents in background workspaces, which the sidebar hides", () => {
const hidden = { id: "ws-hidden", background: true };
expect(
deriveFaviconStatus(
stateWithWorkspaces(
[hidden],
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
agent({ id: "b", workspaceId: "ws-hidden", status: "running" }),
),
),
).toBe("none");
expect(
deriveFaviconStatus(
stateWithWorkspaces(
[hidden, { id: "ws-shown", background: false }],
agent({ id: "a", workspaceId: "ws-hidden", status: "running" }),
agent({ id: "b", workspaceId: "ws-shown", requiresAttention: true }),
),
),
).toBe("attention");
});
it("counts agents in background workspaces while Show background puts them in the sidebar", () => {
const state = stateWithWorkspaces(
[{ id: "ws-hidden", background: true }],
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
);
expect(deriveFaviconStatus(state, { showBackground: true })).toBe("attention");
expect(createFaviconStatusSelector({ showBackground: true })(state)).toBe("attention");
});
});
describe("createFaviconStatusSelector", () => {
@@ -63,6 +108,18 @@ describe("createFaviconStatusSelector", () => {
expect(select({ sessions: { ...state.sessions } })).toBe("running");
});
it("rescans when a workspace map is replaced", () => {
const select = createFaviconStatusSelector();
const state = stateWithWorkspaces(
[],
agent({ id: "a", workspaceId: "ws-hidden", requiresAttention: true }),
);
expect(select(state)).toBe("attention");
// The agent synced before its workspace; only the workspace map changes.
const workspaces = new Map([["ws-hidden", { id: "ws-hidden", background: true }]]);
expect(select({ sessions: { srv: { ...state.sessions.srv, workspaces } } })).toBe("none");
});
it("rescans when an agent map is replaced", () => {
const select = createFaviconStatusSelector();
expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running");
+22 -6
View File
@@ -1,10 +1,11 @@
import type { Agent } from "@/stores/session-store";
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
import { memoizeOnSessionMaps } from "./memoize-on-session-maps";
export type FaviconStatus = "none" | "running" | "attention";
interface FaviconAgentSession {
agents: ReadonlyMap<string, Agent>;
workspaces: ReadonlyMap<string, Pick<WorkspaceDescriptor, "background">>;
}
interface FaviconAgentSource {
@@ -16,13 +17,22 @@ interface FaviconAgentSource {
* three states here instead of building the aggregated agent list: the list allocates a
* projection per agent, deep-compares it and sorts every agent on the host on each update.
*/
export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus {
export interface FaviconStatusOptions {
/** Count agents in background workspaces too, as the sidebar shows them while Show background is on. */
showBackground?: boolean;
}
export function deriveFaviconStatus(
state: FaviconAgentSource,
options: FaviconStatusOptions = {},
): FaviconStatus {
let hasAttention = false;
let hasNeedsInput = false;
for (const session of Object.values(state.sessions)) {
if (!session) continue;
for (const agent of session.agents.values()) {
if (agent.background || agent.archivedAt) continue;
if (!options.showBackground && isInBackgroundWorkspace(agent, session)) continue;
if (agent.status === "running") return "running";
if (agent.requiresAttention) hasAttention = true;
if (agent.pendingPermissions.length > 0) hasNeedsInput = true;
@@ -31,10 +41,16 @@ export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus {
return hasAttention || hasNeedsInput ? "attention" : "none";
}
/** A session-store selector for the favicon status that rescans only when an agent map changes. */
export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus {
function isInBackgroundWorkspace(agent: Agent, session: FaviconAgentSession): boolean {
return agent.workspaceId ? session.workspaces.get(agent.workspaceId)?.background === true : false;
}
/** A session-store selector for the favicon status that rescans only when an agent or workspace map changes. */
export function createFaviconStatusSelector(
options: FaviconStatusOptions = {},
): (state: FaviconAgentSource) => FaviconStatus {
return memoizeOnSessionMaps<FaviconAgentSession, FaviconAgentSource, FaviconStatus>(
(session) => session.agents,
deriveFaviconStatus,
(session) => [session.agents, session.workspaces],
(state) => deriveFaviconStatus(state, options),
);
}
@@ -4,18 +4,18 @@ interface SessionsSource<TSession> {
/**
* Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has
* changed. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
* changed. `pickMaps` returns every map the selector reads from one session. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
* a reference check per host instead of a walk over every entry.
*/
export function memoizeOnSessionMaps<TSession, TState extends SessionsSource<TSession>, TResult>(
pickMap: (session: TSession) => unknown,
pickMaps: (session: TSession) => readonly unknown[],
derive: (state: TState) => TResult,
): (state: TState) => TResult {
let previousMaps: unknown[] | null = null;
let previousResult: TResult;
return (state) => {
const maps = Object.values(state.sessions).map((session) =>
session ? pickMap(session) : undefined,
const maps = Object.values(state.sessions).flatMap((session) =>
session ? pickMaps(session) : [undefined],
);
if (
previousMaps &&
@@ -4,6 +4,8 @@ import { adaptWebContents, HostSnapshotEngineRegistry } from "./ipc.js";
import type { IsolatedKeyboardInputEvent } from "./trusted-input.js";
class FakeImage implements TabImage {
public constructor(private readonly alpha = 255) {}
public toPNG(): Uint8Array {
return new Uint8Array([137, 80, 78, 71]);
}
@@ -11,6 +13,10 @@ class FakeImage implements TabImage {
public getSize(): { width: number; height: number } {
return { width: 640, height: 480 };
}
public toBitmap(): Uint8Array {
return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]);
}
}
class FakeDebugger {
@@ -268,6 +274,24 @@ describe("browser automation IPC adapter", () => {
expect(contents.endedFrameSubscriptions).toBe(1);
});
test("skips frames with no painted pixels and captures the first painted frame", async () => {
const contents = new FakeWebContents(2004);
const tab = adaptWebContents(contents);
const controller = new AbortController();
const capture = tab.captureFrame(controller.signal);
const unpainted = new FakeImage(0);
const painted = new FakeImage(255);
contents.frameListener?.(unpainted);
expect(contents.frameListener).not.toBeNull();
contents.frameListener?.(painted);
expect(await capture).toBe(painted);
expect(contents.frameListener).toBeNull();
controller.abort();
expect(contents.endedFrameSubscriptions).toBe(1);
});
test("cancels a pending frame subscription when the capture budget expires", async () => {
const contents = new FakeWebContents(2001);
const tab = adaptWebContents(contents);
@@ -1,4 +1,4 @@
import { ipcMain } from "electron";
import { ipcMain, nativeImage } from "electron";
import { BrowserAutomationExecuteRequestSchema } from "@getpaseo/protocol/browser-automation/rpc-schemas";
import type {
BrowserAutomationConsoleLogEntry,
@@ -15,7 +15,7 @@ import {
promptShimInstallScript,
promptShimRestoreScript,
} from "./dialog-handling.js";
import { BrowserTabClosedError, executeAutomationCommand } from "./service.js";
import { BrowserTabClosedError, executeAutomationCommand, hasPaintedPixels } from "./service.js";
import { BrowserSnapshotEngine } from "./snapshot-engine.js";
import {
listRegisteredPaseoBrowserIds,
@@ -133,6 +133,7 @@ export function adaptWebContents(contents: BrowserAutomationWebContents): TabCon
goForward: () => contents.goForward(),
reload: () => contents.reload(),
captureFrame: (signal) => captureViewportFrame(contents, signal),
decodePng: (png) => nativeImage.createFromBuffer(Buffer.from(png)),
invalidate: () => contents.invalidate(),
withFrameProduction: async (capture) => {
const previous = contents.getBackgroundThrottling();
@@ -182,6 +183,9 @@ function captureViewportFrame(
// A resized resident guest can paint while capturePage's surface-copy
// request remains pending. Subscribe to its rendered frames instead.
contents.beginFrameSubscription(false, (image) => {
// Keep the subscription open until the page has painted; the capture
// budget turns a page that never paints into screenshot_no_frame.
if (!hasPaintedPixels(image)) return;
stop();
resolve(image);
});
@@ -22,6 +22,7 @@ class FakeImage implements TabImage {
public constructor(
private readonly bytes = new Uint8Array([137, 80, 78, 71, 1, 2, 3]),
private readonly size = { width: 640, height: 480 },
private readonly alpha = 255,
) {}
public toPNG(): Uint8Array {
@@ -31,8 +32,14 @@ class FakeImage implements TabImage {
public getSize(): { width: number; height: number } {
return this.size;
}
public toBitmap(): Uint8Array {
return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]);
}
}
const UNPAINTED_FULL_PAGE_PNG = "unpaintedPng";
class FakeTab implements TabContents {
public withFrameProduction<T>(capture: () => Promise<T>): Promise<T> {
return capture();
@@ -77,6 +84,7 @@ class FakeTab implements TabContents {
public fullPageScreenshotThrows = false;
public fullPageScreenshotErrorMessage = "UnknownVizError";
public fullPageCaptureFailuresBeforeSuccess = 0;
public fullPageUnpaintedCapturesBeforePainted = 0;
public layoutMetrics = {
cssLayoutViewport: { clientWidth: 390, clientHeight: 844 },
cssContentSize: { width: 390, height: 1200 },
@@ -191,6 +199,11 @@ class FakeTab implements TabContents {
this.actions.push("invalidate");
}
public decodePng(png: Uint8Array): TabImage {
const unpainted = Buffer.from(png).equals(Buffer.from(UNPAINTED_FULL_PAGE_PNG, "base64"));
return new FakeImage(png, { width: 390, height: 1200 }, unpainted ? 0 : 255);
}
public getConsoleMessages(): BrowserAutomationConsoleLogEntry[] {
return this.consoleMessages;
}
@@ -218,6 +231,10 @@ class FakeTab implements TabContents {
if (this.fullPageScreenshotThrows) {
throw new Error(this.fullPageScreenshotErrorMessage);
}
if (this.fullPageUnpaintedCapturesBeforePainted > 0) {
this.fullPageUnpaintedCapturesBeforePainted -= 1;
return { data: UNPAINTED_FULL_PAGE_PNG };
}
return { data: this.fullPageScreenshotData };
}
if (command === "Runtime.evaluate") {
@@ -2035,6 +2052,56 @@ describe("executeAutomationCommand", () => {
}
});
test("screenshot with fullPage waits for a CDP image with painted pixels", async () => {
vi.useFakeTimers();
try {
const browser = new BrowserAutomationHarness();
browser.tab.fullPageUnpaintedCapturesBeforePainted = 1;
const resultPromise = browser.execute({
command: "screenshot",
args: { browserId: BROWSER_A, fullPage: true },
});
await vi.advanceTimersByTimeAsync(200);
await expect(resultPromise).resolves.toMatchObject({
ok: true,
result: { command: "screenshot", dataBase64: "fullPagePng" },
});
expect(
browser.tab.debugCommands.filter((entry) => entry.command === "Page.captureScreenshot"),
).toHaveLength(2);
} finally {
vi.useRealTimers();
}
});
test("screenshot with fullPage returns no-frame when the page never paints", async () => {
vi.useFakeTimers();
try {
const browser = new BrowserAutomationHarness();
browser.tab.fullPageUnpaintedCapturesBeforePainted = Number.POSITIVE_INFINITY;
const resultPromise = browser.execute({
command: "screenshot",
args: { browserId: BROWSER_A, fullPage: true },
});
await vi.advanceTimersByTimeAsync(5_000);
await expect(resultPromise).resolves.toEqual({
requestId: "req-screenshot",
ok: false,
error: {
code: "screenshot_no_frame",
message: "The tab has not painted yet. Retry the screenshot.",
retryable: true,
},
});
} finally {
vi.useRealTimers();
}
});
test("screenshot with fullPage surfaces ordinary CDP capture errors", async () => {
const browser = new BrowserAutomationHarness();
browser.tab.fullPageScreenshotThrows = true;
@@ -36,6 +36,7 @@ export interface TabContents {
goForward(): void;
reload(): void;
captureFrame(signal: AbortSignal): Promise<TabImage>;
decodePng(png: Uint8Array): TabImage;
invalidate(): void;
withFrameProduction<T>(capture: () => Promise<T>): Promise<T>;
sendInputEvent(event: IsolatedKeyboardInputEvent): void;
@@ -52,6 +53,22 @@ export interface TabContents {
export interface TabImage {
toPNG(): Uint8Array;
getSize(): { width: number; height: number };
// Raw 32-bit pixels. Alpha is the fourth byte of each pixel in BGRA and RGBA order alike.
toBitmap(): Uint8Array;
}
// Electron guest pages have a transparent base background, so a page that has
// painted nothing yet (for example a dev server hiding body until its JS boots)
// yields a frame where every pixel is transparent. That frame is not a
// screenshot of the page.
export function hasPaintedPixels(image: TabImage): boolean {
const bitmap = image.toBitmap();
for (let alpha = 3; alpha < bitmap.length; alpha += 4) {
if (bitmap[alpha] !== 0) {
return true;
}
}
return false;
}
export interface BrowserRegistry {
@@ -1348,11 +1365,18 @@ async function executeFullPageScreenshot(
const metrics = await getCdpLayoutMetrics(target.contents);
width = metrics.contentWidth;
height = metrics.contentHeight;
return (await sendDebugCommand("Page.captureScreenshot", {
const result = (await sendDebugCommand("Page.captureScreenshot", {
format: "png",
captureBeyondViewport: true,
clip: { x: 0, y: 0, width, height, scale: 1 },
})) as CdpCaptureScreenshotResult;
if (
result.data &&
!hasPaintedPixels(target.contents.decodePng(Buffer.from(result.data, "base64")))
) {
throw new Error("Page.captureScreenshot returned no painted frame");
}
return result;
});
} catch (error) {
if (isScreenshotNoFrameError(error)) {
@@ -47,6 +47,9 @@ export const PaseoWorktreeConfigRawSchema = z
.object({
setup: PaseoLifecycleCommandRawSchema.optional(),
teardown: PaseoLifecycleCommandRawSchema.optional(),
// Checked by WorktreeConfigSchema, where an invalid value falls back to the default, so it
// never stops paseo.json from being edited or sent to the app.
teardownTimeoutMs: z.unknown().optional(),
terminals: z.unknown().optional(),
servicePorts: PaseoServicePortAllocationSchema.optional(),
})
@@ -79,9 +82,20 @@ export const PaseoConfigRawSchema = z
})
.passthrough();
// Node timers can't wait longer than this; a longer delay fires at once.
const MAX_TIMER_DELAY_MS = 2_147_483_647;
export const WorktreeConfigSchema = PaseoWorktreeConfigRawSchema.extend({
setup: z.unknown().optional().transform(normalizeLifecycleCommands),
teardown: z.unknown().optional().transform(normalizeLifecycleCommands),
// Its own catch, so an invalid limit doesn't drop the commands with the rest of the worktree.
teardownTimeoutMs: z
.number()
.int()
.positive()
.max(MAX_TIMER_DELAY_MS)
.optional()
.catch(undefined),
})
.passthrough()
.catch({ setup: [], teardown: [] });
@@ -1,5 +1,13 @@
import { execFile, execFileSync, spawn } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { execFile, execFileSync } from "node:child_process";
import {
chmodSync,
existsSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
@@ -569,7 +577,130 @@ test.skipIf(process.platform === "win32")(
60000,
);
async function createWorktreeWithTeardown(
slug: string,
worktreeConfig: { teardown: string; teardownTimeoutMs?: number },
): Promise<{ workspaceId: string; worktreePath: string }> {
const repoDir = createGitRepo();
writeFileSync(path.join(repoDir, "paseo.json"), JSON.stringify({ worktree: worktreeConfig }));
execFileSync("git", ["add", "paseo.json"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "add teardown"], {
cwd: repoDir,
stdio: "pipe",
});
const result = await ctx.client.createWorkspace({
source: { kind: "worktree", cwd: repoDir, worktreeSlug: slug, baseBranch: "main" },
});
const workspace = result.workspace;
if (!workspace?.workspaceDirectory) {
throw new Error(result.error ?? "Failed to create worktree workspace");
}
return { workspaceId: workspace.id, worktreePath: workspace.workspaceDirectory };
}
function isProcessRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
test.skipIf(process.platform === "win32")(
"a paseo.json teardown that never exits is stopped and the archive answers",
async () => {
const pidFile = path.join(makeTempDir("hanging-teardown-"), "sleep.pid");
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("hanging-teardown", {
teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`,
teardownTimeoutMs: 2000,
});
try {
const archive = await ctx.client.archiveWorkspace(workspaceId);
expect({
error: archive.error,
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
worktreeOnDisk: existsSync(worktreePath),
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true });
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
await expect.poll(() => isProcessRunning(sleepPid), { timeout: 5000 }).toBe(false);
} finally {
if (existsSync(pidFile)) {
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL");
}
}
},
30000,
);
test.skipIf(process.platform === "win32")(
"a paseo.json teardown that prints more than 1 MiB still removes the worktree",
async () => {
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("chatty-teardown", {
teardown: `node -e "process.stdout.write('x'.repeat(2 * 1024 * 1024))"`,
});
const archive = await ctx.client.archiveWorkspace(workspaceId);
expect({
error: archive.error,
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
worktreeOnDisk: existsSync(worktreePath),
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: false });
},
60000,
);
test.skipIf(process.platform === "win32")(
"a teardown that handles SIGTERM and exits zero still leaves the worktree",
async () => {
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-trap", {
teardown: `trap 'exit 0' TERM; sleep 5 & wait`,
teardownTimeoutMs: 2000,
});
const archive = await ctx.client.archiveWorkspace(workspaceId);
expect({
error: archive.error,
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
worktreeOnDisk: existsSync(worktreePath),
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true });
},
15000,
);
test.skipIf(process.platform === "win32")(
"the archive answers when an exited teardown shell's child holds its output open",
async () => {
const pidFile = path.join(makeTempDir("teardown-open-output-"), "sleep.pid");
const { workspaceId, worktreePath } = await createWorktreeWithTeardown("teardown-open-output", {
teardown: `sleep 12 & echo $! > ${JSON.stringify(pidFile)}`,
teardownTimeoutMs: 2000,
});
try {
const archive = await ctx.client.archiveWorkspace(workspaceId);
expect({
error: archive.error,
workspaceActive: (await activeWorkspaceIds()).has(workspaceId),
worktreeOnDisk: existsSync(worktreePath),
}).toEqual({ error: null, workspaceActive: false, worktreeOnDisk: true });
} finally {
if (existsSync(pidFile)) {
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
if (isProcessRunning(sleepPid)) process.kill(sleepPid, "SIGKILL");
}
}
},
10000,
);
test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"repeating archive removes a residual worktree for an already-archived workspace",
async () => {
const repoDir = createGitRepo();
@@ -586,42 +717,24 @@ test.skipIf(process.platform === "win32")(
throw new Error(result.error ?? "Failed to create worktree workspace");
}
const writerStartedPath = path.join(repoDir, "writer-started");
const stopWriterPath = path.join(repoDir, "stop-writer");
const target = path.join(
workspace.workspaceDirectory,
"node_modules/react-native-svg/lib/typescript",
);
const writer = spawn(
process.execPath,
[
"-e",
`const fs=require('fs'),path=require('path');const target=${JSON.stringify(target)};const started=${JSON.stringify(writerStartedPath)};const stop=${JSON.stringify(stopWriterPath)};fs.writeFileSync(started,'started');while(!fs.existsSync(stop)){try{fs.mkdirSync(target,{recursive:true});fs.writeFileSync(path.join(target,'active'),String(Date.now()))}catch{}}`,
],
{ stdio: "ignore" },
);
const writerExit = new Promise<void>((resolve) => writer.once("exit", () => resolve()));
const directory = workspace.workspaceDirectory;
const originalMode = statSync(directory).mode & 0o777;
// Deny removal of entries such as .git until the second archive request.
chmodSync(directory, originalMode & ~0o222);
try {
await expect.poll(() => existsSync(writerStartedPath), { timeout: 10000 }).toBe(true);
const firstArchive = await ctx.client.archiveWorkspace(workspace.id);
expect(firstArchive.error).toBeNull();
expect((await activeWorkspaceIds()).has(workspace.id)).toBe(false);
expect(existsSync(workspace.workspaceDirectory)).toBe(true);
writeFileSync(stopWriterPath, "stop\n");
await writerExit;
const retry = await ctx.client.archiveWorkspace(workspace.id);
expect(retry.error).toBeNull();
expect(existsSync(workspace.workspaceDirectory)).toBe(false);
expect(existsSync(directory)).toBe(true);
} finally {
writeFileSync(stopWriterPath, "stop\n");
await writerExit;
if (existsSync(directory)) chmodSync(directory, originalMode);
}
const retry = await ctx.client.archiveWorkspace(workspace.id);
expect(retry.error).toBeNull();
expect(existsSync(directory)).toBe(false);
},
60000,
);
@@ -1,6 +1,14 @@
import { DaemonClient } from "./test-utils/daemon-client.js";
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
import {
existsSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
renameSync,
mkdirSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, expect, test } from "vitest";
@@ -125,6 +133,55 @@ test.skipIf(process.platform === "win32")(
60000,
);
test.skipIf(process.platform === "win32")(
"an undo during a teardown that never exits returns once the deadline stops it",
async () => {
const tempRoot = mkdtempSync(path.join(tmpdir(), "workspace-archive-undo-hang-"));
tempRoots.push(tempRoot);
const repoDir = path.join(tempRoot, "repo");
const pidFile = path.join(tempRoot, "sleep.pid");
execFileSync("git", ["init", "-b", "main", repoDir], { stdio: "pipe" });
git(repoDir, ["config", "user.email", "test@getpaseo.local"]);
git(repoDir, ["config", "user.name", "Paseo Test"]);
writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: `sleep 600 & echo $! > ${JSON.stringify(pidFile)}; wait`,
teardownTimeoutMs: 2000,
},
}),
);
git(repoDir, ["add", "paseo.json"]);
git(repoDir, ["-c", "commit.gpgsign=false", "commit", "-m", "hanging teardown"]);
const { workspaceId, directory, agentId } = await createWorktreeWorkspaceWithAgent(
repoDir,
"undo-during-hanging-teardown",
);
try {
const archive = ctx.client.archiveWorkspace(workspaceId);
await expect.poll(() => existsSync(pidFile), { timeout: 15000 }).toBe(true);
await Promise.all([archive, ctx.client.undoWorkspaceArchive(workspaceId)]);
expect({
workspaceActive: await isWorkspaceActive(workspaceId),
directoryExists: existsSync(directory),
agentArchived: await isAgentArchived(agentId),
}).toEqual({ workspaceActive: true, directoryExists: true, agentArchived: false });
} finally {
if (existsSync(pidFile)) {
const sleepPid = Number(readFileSync(pidFile, "utf8").trim());
try {
process.kill(sleepPid, "SIGKILL");
} catch {
// Already stopped by the teardown deadline.
}
}
}
},
30000,
);
test.skipIf(process.platform === "win32")(
"an undo after the archive finished recreates the worktree and its agents",
async () => {
@@ -14,6 +14,7 @@ import {
PaseoConfigRawSchema,
getWorktreeSetupCommands,
getWorktreeTeardownCommands,
getWorktreeTeardownTimeoutMs,
} from "./worktree.js";
import {
readPaseoConfigForEdit,
@@ -295,6 +296,34 @@ describe("paseo config file substrate", () => {
expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean", "npm run reset"]);
});
it("reads the teardown time limit and defaults to one minute", async () => {
expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000);
for (const teardownTimeoutMs of [1, 300_000, 2_147_483_647]) {
writeFileSync(
join(tempDir, "paseo.json"),
JSON.stringify({ worktree: { teardownTimeoutMs } }),
);
expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(teardownTimeoutMs);
}
});
it.each([0, -1000, 1500.5, 2_147_483_648, "90000", null, true, { ms: 90_000 }])(
"falls back to the default teardown time limit for %j and keeps the commands",
async (teardownTimeoutMs) => {
const config = { worktree: { teardown: "npm run clean", teardownTimeoutMs } };
writeFileSync(join(tempDir, "paseo.json"), JSON.stringify(config));
expect(await getWorktreeTeardownTimeoutMs(tempDir)).toBe(60_000);
expect(await getWorktreeTeardownCommands(tempDir)).toEqual(["npm run clean"]);
expect(await readPaseoConfigForEdit(tempDir)).toEqual({
ok: true,
config,
revision: await statPaseoConfigPath(tempDir),
});
},
);
it("writes pretty JSON with a trailing newline when revision matches", async () => {
writeFileSync(join(tempDir, "paseo.json"), JSON.stringify({ worktree: { setup: "old" } }));
const expectedRevision = await statPaseoConfigPath(tempDir);
@@ -5,17 +5,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const execFileMock = vi.hoisted(() => vi.fn());
const spawnProcessMock = vi.hoisted(() => vi.fn());
vi.mock("child_process", async () => {
const actual = await vi.importActual<typeof import("child_process")>("child_process");
return {
...actual,
execFile: execFileMock,
};
});
vi.mock("./spawn.js", async () => {
const actual = await vi.importActual<typeof import("./spawn.js")>("./spawn.js");
return {
@@ -42,19 +33,7 @@ describe("worktree shell selection", () => {
const originalPlatform = process.platform;
beforeEach(() => {
execFileMock.mockReset();
spawnProcessMock.mockReset();
execFileMock.mockImplementation(
(
_file: string,
_args: string[],
_options: unknown,
callback?: (error: Error | null, stdout: string, stderr: string) => void,
) => {
callback?.(null, "", "");
return {};
},
);
spawnProcessMock.mockImplementation(createSpawnChildStub);
});
@@ -94,8 +73,8 @@ describe("worktree shell selection", () => {
branchName: "main",
});
expect(execFileMock).toHaveBeenCalledTimes(1);
expect(execFileMock).toHaveBeenCalledWith(
expect(spawnProcessMock).toHaveBeenCalledTimes(1);
expect(spawnProcessMock).toHaveBeenCalledWith(
"powershell",
[
"-NoProfile",
@@ -105,11 +84,10 @@ describe("worktree shell selection", () => {
"-Command",
"Write-Output 'teardown'",
],
expect.objectContaining({ cwd: worktreePath }),
expect.any(Function),
expect.objectContaining({ cwd: worktreePath, shell: false }),
);
const execOptions = execFileMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv };
expect(execOptions.env?.BASH_ENV).toBeUndefined();
const spawnOptions = spawnProcessMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv };
expect(spawnOptions.env?.BASH_ENV).toBeUndefined();
} finally {
if (originalBashEnv === undefined) {
delete process.env.BASH_ENV;
@@ -190,6 +190,30 @@ describe("paseo worktree manager", () => {
});
});
it("retains bounded diagnostic text per teardown output stream", async () => {
const limit = 1024 * 1024;
writeFileSync(
join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: `node -e "process.stdout.write('x'.repeat(${2 * limit})); process.stderr.write('y'.repeat(${2 * limit}))"`,
},
}),
);
const [result] = await runWorktreeTeardownCommands({
worktreePath: repoDir,
repoRootPath: repoDir,
branchName: "main",
});
expect({
exitCode: result.exitCode,
stdoutLength: result.stdout.length,
stderrLength: result.stderr.length,
}).toEqual({ exitCode: 0, stdoutLength: limit, stderrLength: limit });
});
it("rejects paths that are not under the paseo worktrees root", async () => {
const outsidePath = join(tempDir, "outside-paseo-home");
mkdirSync(outsidePath, { recursive: true });
+43 -12
View File
@@ -146,6 +146,13 @@ export class WorktreeSetupError extends Error {
export type WorktreeTeardownCommandResult = WorktreeSetupCommandResult;
// paseo.json can change this with worktree.teardownTimeoutMs. Archive waits for teardown before it
// answers, and the app stops waiting for an archive answer after 60 seconds
// (DEFAULT_SESSION_RPC_TIMEOUT_MS in the client). A teardown that runs to this limit, or to a longer
// one, answers after the app has reported the archive as failed.
const DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS = 60_000;
const MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM = 1024 * 1024;
export class WorktreeTeardownError extends Error {
readonly results: WorktreeTeardownCommandResult[];
@@ -281,6 +288,13 @@ export async function getWorktreeTeardownCommands(repoRoot: string): Promise<str
return (await readPaseoConfigOrThrow(repoRoot))?.worktree?.teardown ?? [];
}
export async function getWorktreeTeardownTimeoutMs(repoRoot: string): Promise<number> {
return (
(await readPaseoConfigOrThrow(repoRoot))?.worktree?.teardownTimeoutMs ??
DEFAULT_WORKTREE_TEARDOWN_TIMEOUT_MS
);
}
export async function getWorktreeTerminalSpecs(
repoRoot: string,
): Promise<WorktreeTerminalConfig[]> {
@@ -449,12 +463,14 @@ async function execSetupCommandStreamed(options: {
index: number;
total: number;
signal?: AbortSignal;
maxOutputCharsPerStream?: number;
onEvent?: (event: WorktreeSetupCommandProgressEvent) => void;
}): Promise<WorktreeSetupCommandResult> {
return new Promise((resolvePromise) => {
const startedAt = Date.now();
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
const outputChunks: Record<"stdout" | "stderr", string[]> = { stdout: [], stderr: [] };
const outputLimit = options.maxOutputCharsPerStream ?? Infinity;
const remainingOutputChars = { stdout: outputLimit, stderr: outputLimit };
let settled = false;
let termination: Promise<unknown> | null = null;
@@ -463,10 +479,10 @@ async function execSetupCommandStreamed(options: {
if (!text) {
return;
}
if (stream === "stdout") {
stdoutChunks.push(text);
} else {
stderrChunks.push(text);
const retainedText = text.slice(0, remainingOutputChars[stream]);
if (retainedText) {
outputChunks[stream].push(retainedText);
remainingOutputChars[stream] -= retainedText.length;
}
options.onEvent?.({
type: "output",
@@ -485,12 +501,17 @@ async function execSetupCommandStreamed(options: {
}
settled = true;
options.signal?.removeEventListener("abort", abort);
await termination;
if (termination) {
await termination;
// A descendant can keep these pipes open after the shell exits.
child.stdout?.destroy();
child.stderr?.destroy();
}
const result: WorktreeSetupCommandResult = {
command: options.command,
cwd: options.cwd,
stdout: stdoutChunks.join(""),
stderr: stderrChunks.join(""),
stdout: outputChunks.stdout.join(""),
stderr: outputChunks.stderr.join(""),
exitCode,
durationMs: Date.now() - startedAt,
};
@@ -529,6 +550,7 @@ async function execSetupCommandStreamed(options: {
gracefulTimeoutMs: 1000,
forceTimeoutMs: 1000,
});
void finish(null);
};
if (options.signal?.aborted) {
abort();
@@ -768,17 +790,26 @@ export async function runWorktreeTeardownCommands(options: {
}),
);
// One deadline covers every command. Reaching it counts as failure and keeps the worktree.
const timeoutMs = await getWorktreeTeardownTimeoutMs(teardownCwd);
const deadline = AbortSignal.timeout(timeoutMs);
const results: WorktreeTeardownCommandResult[] = [];
for (const cmd of teardownCommands) {
const result = await execSetupCommand(cmd, {
for (const [index, cmd] of teardownCommands.entries()) {
const result = await execSetupCommandStreamed({
command: cmd,
cwd: teardownCwd,
env: teardownEnv,
index: index + 1,
total: teardownCommands.length,
signal: deadline,
maxOutputCharsPerStream: MAX_WORKTREE_TEARDOWN_OUTPUT_CHARS_PER_STREAM,
});
results.push(result);
if (result.exitCode !== 0) {
const reason = deadline.aborted ? `Timed out after ${timeoutMs / 1000}s` : result.stderr;
throw new WorktreeTeardownError(
`Worktree teardown command failed: ${cmd}\n${result.stderr}`.trim(),
`Worktree teardown command failed: ${cmd}\n${reason}`.trim(),
results,
);
}
@@ -152,92 +152,18 @@ index 8d78aea..b84d19e 100644
viewGroup: ViewGroup,
coords: FloatArray,
diff --git a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
index 629c155..2efd508 100644
index 629c155..dc0790d 100644
--- a/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
+++ b/node_modules/react-native-gesture-handler/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootHelper.kt
@@ -19,7 +19,9 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
@@ -19,6 +19,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
private val jsGestureHandler: GestureHandler?
val rootView: ViewGroup
private var shouldIntercept = false
+ private var wasIntercepting = false
private var passingTouch = false
+ private var lastTouch: MotionEvent? = null
init {
UiThreadUtil.assertOnUiThread()
@@ -47,6 +49,7 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
}
fun tearDown() {
+ clearLastTouch()
Log.i(
ReactConstants.TAG,
"[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView",
@@ -90,17 +93,46 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
override fun onCancel() {
shouldIntercept = true
- val time = SystemClock.uptimeMillis()
- val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply {
- action = MotionEvent.ACTION_CANCEL
- }
if (rootView is RootView) {
- rootView.onChildStartedNativeGesture(rootView, event)
+ val cancel = createReactCancelEvent()
+ try {
+ rootView.onChildStartedNativeGesture(rootView, cancel)
+ } finally {
+ cancel.recycle()
+ clearLastTouch()
+ }
}
- event.recycle()
}
}
+ private fun clearLastTouch() {
+ lastTouch?.recycle()
+ lastTouch = null
+ }
+
+ private fun createReactCancelEvent(): MotionEvent {
+ val now = SystemClock.uptimeMillis()
+ val touch = lastTouch ?: return MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
+ // The enclosing React root already dispatched this event before it reached the
+ // gesture handler. A POINTER_UP is still in MotionEvent but already ended in JS.
+ val lifted = if (touch.actionMasked == MotionEvent.ACTION_POINTER_UP) touch.actionIndex else -1
+ val count = touch.pointerCount - if (lifted >= 0) 1 else 0
+ val properties = Array(count) { MotionEvent.PointerProperties() }
+ val coords = Array(count) { MotionEvent.PointerCoords() }
+ var index = 0
+ for (pointer in 0 until touch.pointerCount) {
+ if (pointer == lifted) continue
+ touch.getPointerProperties(pointer, properties[index])
+ touch.getPointerCoords(pointer, coords[index])
+ index++
+ }
+ return MotionEvent.obtain(
+ touch.downTime, now, MotionEvent.ACTION_CANCEL, count, properties, coords,
+ touch.metaState, touch.buttonState, touch.xPrecision, touch.yPrecision,
+ touch.deviceId, touch.edgeFlags, touch.source, touch.flags,
+ )
+ }
+
fun requestDisallowInterceptTouchEvent() {
// If this method gets called it means that some native view is attempting to grab lock for
// touch event delivery. In that case we cancel all gesture recognizers
@@ -115,9 +147,25 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
// We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell
// if `requestDisallow` has been called as a result of a normal gesture handling process or
// as a result of one of the gesture handlers activating
+ // Keep the stream for recognizers that activate between events (e.g. long press).
+ // Once native handling begins, React no longer receives the remaining touches.
+ if (!event.isHoverAction() && (!shouldIntercept || event.actionMasked == MotionEvent.ACTION_DOWN)) {
+ clearLastTouch()
+ if (event.actionMasked != MotionEvent.ACTION_UP && event.actionMasked != MotionEvent.ACTION_CANCEL) {
+ lastTouch = MotionEvent.obtainNoHistory(event)
+ }
+ }
@@ -118,6 +119,14 @@ class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView:
passingTouch = true
orchestrator!!.onTouchEvent(event)
passingTouch = false
@@ -0,0 +1,291 @@
import { execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { copyWorktreeIncludes } from "./copy.js";
let root: string;
let source: string;
let worktree: string;
async function writeSource(files: Record<string, string>): Promise<void> {
for (const [file, contents] of Object.entries(files)) {
await mkdir(dirname(join(source, file)), { recursive: true });
await writeFile(join(source, file), contents);
}
}
// Total directories Git visits while listing files, read from its trace2 events.
async function directoriesVisited(run: () => Promise<unknown>): Promise<number> {
const trace = join(root, "trace.json");
process.env.GIT_TRACE2_EVENT = trace;
try {
await run();
} finally {
delete process.env.GIT_TRACE2_EVENT;
}
return (await readFile(trace, "utf8"))
.split("\n")
.filter(Boolean)
.map((line) => JSON.parse(line) as { event: string; key?: string; value?: string })
.filter((event) => event.event === "data" && event.key === "directories-visited")
.reduce((total, event) => total + Number(event.value), 0);
}
async function copied(): Promise<string[]> {
const result = await copyWorktreeIncludes(worktree, source);
if (result.kind !== "copied") throw new Error(`expected a copy, got ${result.kind}`);
return [...result.copied].sort();
}
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), "worktree-include-"));
source = join(root, "source");
worktree = join(root, "worktree");
await mkdir(source);
await mkdir(worktree);
execFileSync("git", ["init", "-q", source]);
});
afterEach(async () => {
await rm(root, { recursive: true, force: true });
});
describe("copyWorktreeIncludes", () => {
it("does not search inside an ignored directory that no pattern names", async () => {
await writeSource({
".gitignore": "node_modules/\n.env\n",
".worktreeinclude": ".env\n",
".env": "SECRET=root",
"apps/web/.env": "SECRET=web",
"node_modules/pkg/.env": "SECRET=package",
});
expect(await copied()).toEqual([".env", "apps/web/.env"]);
expect(existsSync(join(worktree, "node_modules"))).toBe(false);
});
it("searches inside ignored directories for a pattern that starts with **/", async () => {
await writeSource({
".gitignore": "node_modules/\n.env\n",
".worktreeinclude": "**/.env\n",
".env": "SECRET=root",
"node_modules/pkg/.env": "SECRET=package",
});
expect(await copied()).toEqual([".env", "node_modules/pkg/.env"]);
});
it("copies a file in an untracked directory once when a **/ pattern also searches it", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": "**/.env\nnew-package/.env\n",
"new-package/.env": "SECRET=new",
});
const result = await copyWorktreeIncludes(worktree, source);
expect(result).toEqual({
kind: "copied",
copied: ["new-package/.env"],
skipped: [],
});
});
it("copies a path a pattern names inside an ignored directory", async () => {
await writeSource({
".gitignore": "node_modules/\n",
".worktreeinclude": "node_modules/pkg/.env\n",
"node_modules/pkg/.env": "SECRET=package",
"node_modules/other/.env": "SECRET=other",
});
expect(await copied()).toEqual(["node_modules/pkg/.env"]);
});
it("copies an ignored directory that a pattern names", async () => {
await writeSource({
".gitignore": ".secrets/\nbuild/\n",
".worktreeinclude": ".secrets/\n",
".secrets/a.key": "a",
".secrets/nested/b.key": "b",
"build/out.js": "built",
});
expect(await copied()).toEqual([".secrets/a.key", ".secrets/nested/b.key"]);
});
it("searches inside an ignored directory for a path a pattern names", async () => {
await writeSource({
".gitignore": "config/\n",
".worktreeinclude": "config/*.local.json\n!config/production.local.json\n",
"config/dev.local.json": "dev",
"config/production.local.json": "production",
"config/defaults.json": "defaults",
});
expect(await copied()).toEqual(["config/dev.local.json"]);
expect(await readFile(join(worktree, "config/dev.local.json"), "utf8")).toBe("dev");
});
it("copies ignored files inside an untracked directory", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": ".env\n",
"new-package/.env": "SECRET=new",
});
expect(await copied()).toEqual(["new-package/.env"]);
});
it("copies nothing that is tracked or not ignored", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": ".env\nnotes.txt\n",
"notes.txt": "not ignored",
});
expect(await copied()).toEqual([]);
});
it("searches only the path a glob-free pattern names directly inside an ignored directory", async () => {
const packages: Record<string, string> = {};
for (let i = 0; i < 20; i++) packages[`node_modules/pkg${i}/lib/index.js`] = "code";
await writeSource({
".gitignore": "node_modules/\n",
".worktreeinclude": "node_modules/.cache\n",
"node_modules/.cache/state.json": "cache",
...packages,
});
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
const visited = await directoriesVisited(async () => {
result = await copyWorktreeIncludes(worktree, source);
});
expect(result).toEqual({
kind: "copied",
copied: ["node_modules/.cache/state.json"],
skipped: [],
});
expect(visited).toBeLessThan(10);
});
it.skipIf(process.platform === "win32")(
"copies includes when an ignored file is named like a Git pathspec",
async () => {
await writeSource({
".gitignore": "*.log\n.env\n",
".worktreeinclude": ".env\n",
".env": "SECRET=root",
":(oops.log": "log",
":!c.log": "log",
});
expect(await copied()).toEqual([".env"]);
},
);
it("ignores exclude patterns from the user's git template", async () => {
const template = join(root, "template");
await mkdir(join(template, "info"), { recursive: true });
await writeFile(join(template, "info", "exclude"), "*.log\n");
await writeSource({
".gitignore": "*.log\n.env\n",
".worktreeinclude": ".env\n",
".env": "SECRET=root",
"debug.log": "log",
});
process.env.GIT_TEMPLATE_DIR = template;
try {
expect(await copied()).toEqual([".env"]);
} finally {
delete process.env.GIT_TEMPLATE_DIR;
}
});
it("does not search an ignored directory deeper than a pattern without ** can reach", async () => {
const packages: Record<string, string> = {};
for (let i = 0; i < 20; i++) packages[`apps/web/node_modules/pkg${i}/lib/index.js`] = "code";
await writeSource({
".gitignore": "node_modules/\n.env\n",
".worktreeinclude": "apps/*/.env\n",
"apps/web/.env": "SECRET=web",
...packages,
});
let result: Awaited<ReturnType<typeof copyWorktreeIncludes>> | undefined;
const visited = await directoriesVisited(async () => {
result = await copyWorktreeIncludes(worktree, source);
});
expect(result).toEqual({ kind: "copied", copied: ["apps/web/.env"], skipped: [] });
expect(visited).toBeLessThan(10);
});
it("reads the first pattern after a UTF-8 byte order mark", async () => {
await writeSource({
".gitignore": "node_modules/\n",
".worktreeinclude": "\uFEFFnode_modules/.cache/\n",
"node_modules/.cache/state.json": "cache",
});
expect(await copied()).toEqual(["node_modules/.cache/state.json"]);
});
it("matches patterns case-insensitively when the source repo ignores case", async () => {
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
await writeSource({
".gitignore": ".env\nconfig/\n",
".worktreeinclude": ".ENV\nCONFIG/a.json\n",
".env": "SECRET=root",
"config/a.json": "a",
});
expect(await copied()).toEqual([".env", "config/a.json"]);
});
it("searches a pattern's path in the case it has on disk when the source repo ignores case", async () => {
execFileSync("git", ["-C", source, "config", "core.ignoreCase", "true"]);
await writeSource({
".gitignore": "Config/\nÉTÉ/\n",
".worktreeinclude": "config/a.json\nÉTÉ/sub/.env\n",
"Config/a.json": "a",
"ÉTÉ/sub/.env": "SECRET=summer",
});
expect(await copied()).toEqual(["Config/a.json", "ÉTÉ/sub/.env"]);
});
// Each searched folder is one argument to Git. Windows caps a command line at 32,767
// characters and Linux at 2 MB, so each platform gets enough folders to exceed its own
// limit, with names short enough for Windows paths.
it("searches more ignored folders than fit on one command line", async () => {
const folders = process.platform === "win32" ? 300 : 15_000;
const name = (i: number) => `${"x".repeat(150)}${i}`;
await writeSource({
".gitignore": "x*/\n.env\n",
".worktreeinclude": "**/.env\n",
[`${name(folders - 1)}/.env`]: "SECRET=last",
});
for (let i = 0; i < folders - 1; i++) await mkdir(join(source, name(i)));
await Promise.all(
Array.from({ length: folders - 1 }, (_, i) => writeFile(join(source, name(i), "a"), "")),
);
expect(await copied()).toEqual([`${name(folders - 1)}/.env`]);
}, 60_000);
it("copies ignored files inside an untracked directory a pattern names", async () => {
await writeSource({
".gitignore": ".env\n",
".worktreeinclude": "newdir/\n",
"newdir/.env": "SECRET=new",
"newdir/notes.txt": "untracked",
});
expect(await copied()).toEqual(["newdir/.env"]);
});
});
+162 -16
View File
@@ -2,7 +2,8 @@
// Copyright (c) 2026 Carlos Precioso.
import { execFile } from "node:child_process";
import { constants, existsSync } from "node:fs";
import { copyFile, mkdir } from "node:fs/promises";
import { copyFile, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { promisify } from "node:util";
@@ -22,37 +23,33 @@ async function git(cwd: string, args: string[], input?: string): Promise<string>
return stdout;
}
async function gitAllowExit1(cwd: string, args: string[], input: string): Promise<string> {
// `git check-ignore --stdin` reads each path as a pathspec, so a name such as `:(x`
// would be parsed as pathspec magic. A `./` prefix keeps every path literal.
async function checkIgnore(cwd: string, args: string[], paths: string[]): Promise<string[]> {
const input = paths.map((path) => `./${path}\0`).join("");
let output: string;
try {
return await git(cwd, args, input);
output = await git(cwd, [...args, "check-ignore", "--stdin", "-z"], input);
} catch (error) {
// `git check-ignore` exits 1 when nothing matched.
if ((error as { code?: number }).code === 1) return "";
if ((error as { code?: number }).code === 1) return [];
throw error;
}
return splitNul(output).map((path) => path.replace(/^\.\//, ""));
}
const splitNul = (s: string) => s.split("\0").filter(Boolean);
const isDirectory = (entry: string) => entry.endsWith("/");
// Copy files that match .worktreeinclude (gitignore syntax)
// AND are gitignored, so tracked files are never touched.
export async function copyWorktreeIncludes(worktree: string, source: string): Promise<CopyResult> {
if (!existsSync(join(source, INCLUDE_FILE))) return { kind: "no-include-file" };
const matches = splitNul(
await git(source, [
"ls-files",
"--others",
"--ignored",
`--exclude-from=${INCLUDE_FILE}`,
"-z",
]),
);
const matches = await findIncludedFiles(source);
if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] };
const ignored = splitNul(
await gitAllowExit1(source, ["check-ignore", "--stdin", "-z"], matches.join("\0") + "\0"),
);
const ignored = await checkIgnore(source, [], matches);
const copied: string[] = [];
const skipped: string[] = [];
@@ -69,3 +66,152 @@ export async function copyWorktreeIncludes(worktree: string, source: string): Pr
}
return { kind: "copied", copied, skipped };
}
// Git lists a directory it ignores as a whole, such as node_modules/, as one entry.
// Only directories that a pattern matches or names a path inside are searched, and
// only as deep as the pattern names, so creating a worktree does not walk every file
// in large ignored trees.
async function findIncludedFiles(source: string): Promise<string[]> {
const ignored = splitNul(
await git(source, [
"ls-files",
"--others",
"--ignored",
"--exclude-standard",
"--directory",
"-z",
]),
);
if (ignored.length === 0) return [];
const ignoreCase = await sourceIgnoresCase(source);
const patterns = parsePatterns(await readFile(join(source, INCLUDE_FILE), "utf8"));
const matched = new Set(await matchIncludePatterns(source, ignored, ignoreCase));
const files = ignored.filter((entry) => !isDirectory(entry) && matched.has(entry));
const searched = new Set<string>();
// Git also lists an untracked folder that holds ignored entries, which are listed on
// their own, so only folders Git ignores as a whole are searched.
const directories = await checkIgnore(source, [], ignored.filter(isDirectory));
for (const directory of directories) {
if (matched.has(directory)) {
searched.add(directory);
continue;
}
for (const pattern of patterns) {
const inside = searchedPathInside(pattern, directory, ignoreCase);
if (inside !== null) searched.add(inside);
}
}
if (searched.size === 0) return files;
const pathspecs = [...searched].map(
(path) => `:(${ignoreCase ? "literal,icase" : "literal"})${path}`,
);
const inside: string[] = [];
for (const batch of commandLineBatches(pathspecs)) {
const listed = await git(source, [
"ls-files",
"--others",
"--ignored",
`--exclude-from=${INCLUDE_FILE}`,
"-z",
"--",
...batch,
]);
inside.push(...splitNul(listed));
}
return [...new Set([...files, ...inside])];
}
// Windows caps a command line at 32,767 characters, so a pattern such as `**/.env` in a
// repo with many ignored folders searches them over several Git calls.
const COMMAND_LINE_BATCH_CHARS = 16_000;
function commandLineBatches(args: string[]): string[][] {
const batches: string[][] = [];
let batch: string[] = [];
let length = 0;
for (const arg of args) {
if (batch.length > 0 && length + arg.length + 1 > COMMAND_LINE_BATCH_CHARS) {
batches.push(batch);
batch = [];
length = 0;
}
batch.push(arg);
length += arg.length + 1;
}
if (batch.length > 0) batches.push(batch);
return batches;
}
// Match entries against .worktreeinclude alone, in a scratch repository where no other
// ignore rules apply. Directory entries keep their trailing slash, so directory
// patterns match them without anything on disk.
async function matchIncludePatterns(
source: string,
entries: string[],
ignoreCase: boolean,
): Promise<string[]> {
const scratch = await mkdtemp(join(tmpdir(), "paseo-worktree-include-"));
try {
// An empty template keeps the user's template `info/exclude` out of the matching.
await git(scratch, ["init", "-q", "--template="]);
return await checkIgnore(
scratch,
[
"-c",
`core.excludesFile=${join(source, INCLUDE_FILE)}`,
"-c",
`core.ignoreCase=${ignoreCase}`,
],
entries,
);
} finally {
await rm(scratch, { recursive: true, force: true });
}
}
// The scratch repository would otherwise take core.ignoreCase from the temp folder.
async function sourceIgnoresCase(source: string): Promise<boolean> {
try {
return (await git(source, ["config", "--type=bool", "core.ignoreCase"])).trim() === "true";
} catch {
// `git config` exits 1 when the key is unset.
return false;
}
}
function parsePatterns(contents: string): string[] {
// Git skips a leading UTF-8 byte order mark in exclude files.
return contents
.replace(/^\uFEFF/, "")
.split(/\r?\n/)
.map((line) => line.trimEnd())
.filter((line) => line !== "" && !line.startsWith("#") && !line.startsWith("!"));
}
// A pattern with a slash before its end is anchored to the checkout root, so it can
// name a path inside `directory` when its literal start and the directory overlap.
// Without `**`, a pattern matches paths of exactly its own depth, so a directory that
// deep or deeper can hold no match below it. Returns the narrowest path to search: the
// whole path when the pattern has no glob, else the folder before its first glob, or
// `directory` itself when the path ends above it.
function searchedPathInside(
pattern: string,
rawDirectory: string,
ignoreCase: boolean,
): string | null {
// Git folds only ASCII letters when it ignores case.
const fold = (text: string) =>
ignoreCase ? text.replace(/[A-Z]+/g, (letters) => letters.toLowerCase()) : text;
const path = fold(pattern.replace(/^\//, ""));
const directory = fold(rawDirectory);
const depth = (text: string) => text.replace(/\/$/, "").split("/").length;
if (depth(path) < 2) return null;
if (!path.includes("**") && depth(directory) >= depth(path)) return null;
const globAt = path.search(/[*?[\\]/);
const literal = globAt === -1 ? path : path.slice(0, globAt);
if (!literal.startsWith(directory) && !directory.startsWith(literal)) return null;
const searched = globAt === -1 ? literal : literal.slice(0, literal.lastIndexOf("/") + 1);
return searched.length > directory.length ? searched : directory;
}
+13
View File
@@ -122,6 +122,19 @@ Both fields accept a multiline shell script or an array of commands; commands ru
Commands run with the worktree as `cwd`. Use `$PASEO_SOURCE_CHECKOUT_PATH` to reach files in the original checkout (untracked config, local caches, etc).
Teardown commands share a one minute limit. Set `teardownTimeoutMs` to change it, in milliseconds:
```json
{
"worktree": {
"teardown": "docker compose down",
"teardownTimeoutMs": 300000
}
}
```
At the limit, Paseo tries to stop the command and its child processes and stops waiting for output. If teardown fails or reaches the limit, the workspace still archives and the worktree stays on disk. `teardownTimeoutMs` accepts whole numbers from 1 to 2147483647. Other values use the default.
## Scripts and services
`scripts` are named commands you can run inside a worktree on demand. Mark one as a _service_ and Paseo supervises it as a long-running process, assigns it a port, and routes HTTP traffic to it through the daemon's reverse proxy.
+13
View File
@@ -120,6 +120,19 @@ paseo workspace create \
命令以 worktree 作为 `cwd` 运行。使用 `$PASEO_SOURCE_CHECKOUT_PATH` 访问原始检出中的文件(未跟踪的配置、本地缓存等)。
teardown 的所有命令共用一分钟的时限。用 `teardownTimeoutMs` 修改它,单位为毫秒:
```json
{
"worktree": {
"teardown": "docker compose down",
"teardownTimeoutMs": 300000
}
}
```
达到时限后,Paseo 会尝试停止命令及其子进程,并停止等待输出。如果 teardown 失败或达到时限,工作区仍会归档,worktree 会保留在磁盘上。`teardownTimeoutMs` 接受 1 到 2147483647 之间的整数。其他值使用默认时限。
## 脚本与服务 {#scripts-and-services}
`scripts` 是可以在 worktree 中按需运行的具名命令。把其中一个标记为 _service_,Paseo 就会把它作为长时间运行的进程进行监管,为它分配端口,并通过 daemon 的反向代理把 HTTP 流量路由给它。
+2
View File
@@ -36,6 +36,8 @@ config/*.local.json
A pattern only selects files that Git already ignores. Adding a path here does not ignore it, so also configure `.gitignore` when needed. Tracked files and untracked files that Git does not ignore are excluded.
Paseo does not search inside a directory that Git ignores as a whole, such as `node_modules/`, unless a pattern names that directory or a path inside it. A bare name like `.env` matches `.env` and `apps/web/.env`, but not `node_modules/pkg/.env`. To copy from inside an ignored directory, name it in the pattern, as in `node_modules/pkg/.env` or `.secrets/`. A pattern with a glob in its first directory name, such as `**/.env` or `*/.env`, searches every ignored directory, including `node_modules/`, so name the directory instead when it is large.
## When files are copied
The built-in `worktree-include` plugin reads the file from the checkout you create the worktree from. That source can itself be another worktree. Keep the plugin enabled for copying to run.
@@ -36,6 +36,8 @@ config/*.local.json
模式只会选择 Git 已忽略的文件。在此添加路径不会使 Git 忽略该文件,需要时还应配置 `.gitignore`。已跟踪的文件和未被 Git 忽略的未跟踪文件都不会被复制。
对于被 Git 整体忽略的目录(例如 `node_modules/`),除非某个模式指明了该目录或其中的路径,否则 Paseo 不会在其中查找。像 `.env` 这样的纯文件名会匹配 `.env` 和 `apps/web/.env`,但不会匹配 `node_modules/pkg/.env`。要从被忽略的目录中复制文件,请在模式中写出该目录,例如 `node_modules/pkg/.env` 或 `.secrets/`。第一级目录名中带有通配符的模式(例如 `**/.env` 或 `*/.env`)会在所有被忽略的目录中查找,包括 `node_modules/`,因此目录较大时请直接写出目录。
## 文件复制时机 {#when-files-are-copied}
内置的 `worktree-include` 插件从用于创建 worktree 的检出读取该文件。源检出也可以是另一个 worktree。保持该插件启用才能执行复制。
+30
View File
@@ -52,6 +52,36 @@ Pick the contribution that matches the request. Each row names the registration,
| Inject launch-only MCP servers and save Codex sandbox/approval options | [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) |
| Attach a tool to selected agents | [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) |
## Develop plugins in a local folder
Develop a plugin in a local folder that you own, the same way you develop an npm package. Install
that folder by path. Paseo runs the plugin from that folder, `paseo plugin reload <id>` loads your
edits, and `paseo plugin update` does not change it.
Do not edit, build, or commit inside the installation of a Git or npm plugin. That folder is
Paseo's managed storage in the `plugins/` directory of the daemon home. `paseo plugin update`
replaces it, and `paseo plugin remove` deletes it. Both commands discard every edit and commit in
that folder.
Before you edit an installed plugin, run `paseo plugin ls <id>` and read the SOURCE column. A
`git:` source, an `npm:` source, or a registry source such as `<registry host>/owner/slug` is a
managed installation. Its DIRECTORY column shows the managed folder.
To develop a plugin that is installed from Git or npm:
1. Clone the source repository of the plugin into a folder outside the daemon home. For an npm
plugin, find the repository in its `package.json`.
2. If SOURCE ends with `:<path>`, use that subfolder of the clone as the plugin folder.
3. If the managed folder holds edits or commits, move them into the plugin folder.
4. In the plugin folder, install the dependencies and run the `build` commands from
`paseo-plugin.json`. Paseo runs `build` only for managed installations.
5. Ask the user before you remove the managed installation. `paseo plugin remove <id>` also
deletes the saved settings of the plugin.
6. Run `paseo plugin remove <id>`.
7. Run `paseo plugin install /absolute/path/to/plugin-folder --id <id>` to keep the runtime ID.
8. Edit the plugin folder, and run `paseo plugin reload <id>` after each change. If a change needs
a `build` command, run that command before `reload`.
## Create the project
Use an absolute path on the daemon machine. `init` writes files but does not install packages.