mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-18 06:15:02 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99ab18c473 | ||
|
|
3e34be1228 | ||
|
|
20d7ae6cd5 | ||
|
|
32e7df0554 |
@@ -117,10 +117,7 @@ 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. 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
|
||||
subscription on completion or cancellation. 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.
|
||||
|
||||
+3
-11
@@ -49,17 +49,9 @@ 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"` 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.
|
||||
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`.
|
||||
|
||||
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,17 +527,7 @@ 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,8 +14,6 @@ import {
|
||||
answerFreshnessCheck,
|
||||
commitTimelineTurnsWhileDisconnected,
|
||||
disconnectViewedTimeline,
|
||||
expectEmptyChatSynced,
|
||||
expectPromptAndWholeReply,
|
||||
expectResumeAnsweredWithoutFetch,
|
||||
expectResumeOverflowFallsBackToOneTail,
|
||||
hideTabAndReturn,
|
||||
@@ -24,11 +22,7 @@ import {
|
||||
restoreUnchangedViewedTimeline,
|
||||
restoreViewedTimelineHoldingCatchUp,
|
||||
restoreViewedTimelineWithHeldResponse,
|
||||
restoreViewedTimelineWithLiveRowsFirst,
|
||||
reopenWithFreshnessCheckUnanswered,
|
||||
seedStreamingReplyAgent,
|
||||
sendPromptWhileDisconnected,
|
||||
stopStreamingReply,
|
||||
waitForResumeAnswer,
|
||||
reopenAppWatchingForUpdatingToast,
|
||||
watchForUpdatingToast,
|
||||
@@ -153,27 +147,4 @@ 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,6 +1,5 @@
|
||||
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 {
|
||||
@@ -242,100 +241,3 @@ 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]);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ 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";
|
||||
@@ -86,16 +85,8 @@ 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 });
|
||||
// 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 selectFaviconStatus = useMemo(createFaviconStatusSelector, []);
|
||||
const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []);
|
||||
const status = useSessionStore(selectFaviconStatus);
|
||||
const dockBadgeCount = useSessionStore(selectMacDockBadgeCount);
|
||||
const [colorScheme, setColorScheme] = useState<ColorScheme>(getSystemColorScheme);
|
||||
|
||||
@@ -2003,9 +2003,8 @@ function WorkspaceScreenContent({
|
||||
const agent =
|
||||
useSessionStore.getState().sessions[normalizedServerId]?.agents?.get(agentId) ?? null;
|
||||
let closePolicy = resolveCloseAgentTabPolicy(agent);
|
||||
const isRunning = agent?.status === "running";
|
||||
|
||||
if (isRunning && closePolicy.kind === "archive-on-close") {
|
||||
if (closePolicy.kind === "archive-on-close" && closePolicy.confirmArchive) {
|
||||
const confirmed = await confirmDialog({
|
||||
title: t("workspace.tabs.confirmations.archiveRunningAgentTitle"),
|
||||
message: t("workspace.tabs.confirmations.archiveRunningAgentMessage"),
|
||||
|
||||
@@ -79,6 +79,7 @@ export interface Agent {
|
||||
provider: AgentProvider;
|
||||
status: AgentLifecycleStatus;
|
||||
backgroundWork?: { count: number };
|
||||
runningProviderSubagents?: { count: number };
|
||||
turn: TurnLiveness;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
|
||||
@@ -1,21 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveCloseAgentTabPolicy } from "./close-tab-policy";
|
||||
|
||||
function rootAgent(overrides: Partial<Parameters<typeof resolveCloseAgentTabPolicy>[0]> = {}) {
|
||||
return { parentAgentId: null, status: "idle" as const, ...overrides };
|
||||
}
|
||||
|
||||
describe("resolveCloseAgentTabPolicy", () => {
|
||||
it("archives root agents when their tab closes", () => {
|
||||
expect(resolveCloseAgentTabPolicy({ parentAgentId: null })).toEqual({
|
||||
it("archives an idle root agent without asking", () => {
|
||||
expect(resolveCloseAgentTabPolicy(rootAgent())).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("asks before archiving a running root agent", () => {
|
||||
expect(resolveCloseAgentTabPolicy(rootAgent({ status: "running" }))).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("asks before archiving a root agent whose turn ended while background work still runs", () => {
|
||||
expect(resolveCloseAgentTabPolicy(rootAgent({ backgroundWork: { count: 1 } }))).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("asks before archiving a root agent whose turn ended while its background subagent still runs", () => {
|
||||
expect(
|
||||
resolveCloseAgentTabPolicy(rootAgent({ runningProviderSubagents: { count: 1 } })),
|
||||
).toEqual({ kind: "archive-on-close", confirmArchive: true });
|
||||
});
|
||||
|
||||
it("keeps subagent tab close layout-only", () => {
|
||||
expect(resolveCloseAgentTabPolicy({ parentAgentId: "parent-agent" })).toEqual({
|
||||
kind: "layout-only",
|
||||
});
|
||||
expect(
|
||||
resolveCloseAgentTabPolicy(rootAgent({ parentAgentId: "parent-agent", status: "running" })),
|
||||
).toEqual({ kind: "layout-only" });
|
||||
});
|
||||
|
||||
it("preserves the existing archive fallback when the agent is missing", () => {
|
||||
expect(resolveCloseAgentTabPolicy(null)).toEqual({ kind: "archive-on-close" });
|
||||
expect(resolveCloseAgentTabPolicy(undefined)).toEqual({ kind: "archive-on-close" });
|
||||
expect(resolveCloseAgentTabPolicy(null)).toEqual({
|
||||
kind: "archive-on-close",
|
||||
confirmArchive: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
|
||||
export type CloseAgentTabPolicy = { kind: "archive-on-close" } | { kind: "layout-only" };
|
||||
export type CloseAgentTabPolicy =
|
||||
| { kind: "archive-on-close"; confirmArchive: boolean }
|
||||
| { kind: "layout-only" };
|
||||
|
||||
type CloseTabAgent = Pick<
|
||||
Agent,
|
||||
"parentAgentId" | "status" | "backgroundWork" | "runningProviderSubagents"
|
||||
>;
|
||||
|
||||
export function resolveCloseAgentTabPolicy(
|
||||
agent: Pick<Agent, "parentAgentId"> | null | undefined,
|
||||
agent: CloseTabAgent | null | undefined,
|
||||
): CloseAgentTabPolicy {
|
||||
if (agent?.parentAgentId) {
|
||||
return { kind: "layout-only" };
|
||||
}
|
||||
|
||||
return { kind: "archive-on-close" };
|
||||
return { kind: "archive-on-close", confirmArchive: agent ? hasRunningWork(agent) : false };
|
||||
}
|
||||
|
||||
// Archiving stops the agent's process, which also stops work it left running after its turn
|
||||
// ended: background subagents and background shells.
|
||||
function hasRunningWork(agent: CloseTabAgent): boolean {
|
||||
return (
|
||||
agent.status === "running" ||
|
||||
(agent.backgroundWork?.count ?? 0) > 0 ||
|
||||
(agent.runningProviderSubagents?.count ?? 0) > 0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ 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 {
|
||||
@@ -18,8 +17,6 @@ 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,
|
||||
@@ -1382,318 +1379,6 @@ 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,7 +53,6 @@ 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: {
|
||||
@@ -66,13 +65,12 @@ it.each([false, true])(
|
||||
epoch: "epoch-1",
|
||||
currentTail: tail,
|
||||
currentHead: head,
|
||||
currentCursor: cursor,
|
||||
currentCursor: undefined,
|
||||
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" },
|
||||
@@ -2850,7 +2848,7 @@ describe("processTimelineResponse", () => {
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 60, endSeq: 79 },
|
||||
currentCursor: undefined,
|
||||
});
|
||||
expect(getAssistantTexts([...live.tail, ...live.head])).toEqual([
|
||||
"First paragraph.\n\nSecond paragraph.",
|
||||
@@ -3679,7 +3677,6 @@ describe("processAgentStreamEvent", () => {
|
||||
event: makeAssistantTimelineEvent("[System Error] failed"),
|
||||
epoch: "timeline-1",
|
||||
seq: 42,
|
||||
currentCursor: { epoch: "timeline-1", startSeq: 1, endSeq: 41 },
|
||||
});
|
||||
|
||||
expect(result.head).toEqual([
|
||||
@@ -3900,24 +3897,6 @@ 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,
|
||||
@@ -4108,7 +4087,7 @@ describe("processAgentStreamEvents", () => {
|
||||
],
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 237 },
|
||||
currentCursor: undefined,
|
||||
});
|
||||
|
||||
expect(result.changedTail).toBe(false);
|
||||
@@ -4282,7 +4261,6 @@ describe("processAgentStreamEvents", () => {
|
||||
currentTail: [],
|
||||
currentHead: [],
|
||||
currentCursor: undefined,
|
||||
hasAuthoritativeBaseline: false,
|
||||
timestamp: new Date("2026-05-02T10:00:00.186Z"),
|
||||
});
|
||||
|
||||
@@ -4484,7 +4462,7 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
const scheduler = createManualScheduler();
|
||||
let currentTail: StreamItem[] = [];
|
||||
let currentHead: StreamItem[] = [];
|
||||
let currentCursor: TimelineCursor | undefined = { epoch: "epoch-1", startSeq: 1, endSeq: 1 };
|
||||
let currentCursor: TimelineCursor | undefined;
|
||||
|
||||
const queue = createAgentStreamReducerQueue({
|
||||
getSnapshot: () => ({
|
||||
@@ -4527,7 +4505,7 @@ describe("createAgentStreamReducerQueue", () => {
|
||||
expect(getAssistantTexts(currentHead)).toEqual(["This is a paragraph continues."]);
|
||||
expect(currentCursor).toEqual({
|
||||
epoch: "epoch-1",
|
||||
startSeq: 1,
|
||||
startSeq: 2,
|
||||
endSeq: 4,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -289,10 +289,7 @@ function classifySessionTimelineSeq({
|
||||
seq: number;
|
||||
}): SessionTimelineSeqDecision {
|
||||
if (!cursor) {
|
||||
// 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";
|
||||
return "init";
|
||||
}
|
||||
if (cursor.epoch !== epoch) {
|
||||
return "drop_epoch";
|
||||
@@ -1546,14 +1543,14 @@ function processTimelineSequencingGate(input: {
|
||||
return {
|
||||
...base,
|
||||
shouldApplyStreamEvent: false,
|
||||
sideEffects: [
|
||||
{
|
||||
type: "catch_up",
|
||||
cursor: currentCursor
|
||||
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
|
||||
: { epoch, endSeq: 0 },
|
||||
},
|
||||
],
|
||||
sideEffects: currentCursor
|
||||
? [
|
||||
{
|
||||
type: "catch_up",
|
||||
cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq },
|
||||
},
|
||||
]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
if (decision === "drop_epoch" && seq === 1) {
|
||||
|
||||
@@ -64,21 +64,6 @@ 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,96 +441,6 @@ 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);
|
||||
@@ -975,8 +885,7 @@ 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");
|
||||
world.cursors.set("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
initial.respond({ hasNewer: false, seq: 10 });
|
||||
initial.respond({ hasNewer: false });
|
||||
await vi.waitFor(() => expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready"));
|
||||
|
||||
world.sync.recoverGap("agent-a", { epoch: "epoch-agent-a", endSeq: 10 });
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
planTimelineCatchUpAfter,
|
||||
planTimelineCatchUpPastApplied,
|
||||
planTimelineResumeFetch,
|
||||
type ProjectedTimelineForwardFetchPlan,
|
||||
} from "./timeline-sync-plan";
|
||||
@@ -742,10 +741,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
await fetchUntilCurrent(
|
||||
agentId,
|
||||
generation,
|
||||
planTimelineCatchUpPastApplied(
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
ports.readCursor(agentId),
|
||||
),
|
||||
planTimelineCatchUpAfter(page.endCursor),
|
||||
false,
|
||||
);
|
||||
return;
|
||||
@@ -823,10 +819,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
|
||||
ensureCacheLoaded(agentId);
|
||||
return;
|
||||
}
|
||||
const applied = ports.readCursor(agentId);
|
||||
const nextRequest = request
|
||||
? planTimelineCatchUpPastApplied(request, applied)
|
||||
: planTimelineResumeFetch(applied);
|
||||
const nextRequest = request ?? planTimelineResumeFetch(ports.readCursor(agentId));
|
||||
const current = catchUps.get(agentId);
|
||||
const decision = decideCatchUp({ current, request: nextRequest, supersede });
|
||||
if (decision === "keep-and-park") {
|
||||
@@ -840,13 +833,11 @@ 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,
|
||||
nextRequest.direction === "after" && (request === undefined || applied === undefined),
|
||||
request === undefined && nextRequest.direction === "after",
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ export function projectAgentSnapshot(agent: Agent): AgentSnapshotPayload {
|
||||
lastUserMessageAt: agent.lastUserMessageAt?.toISOString() ?? null,
|
||||
status: agent.status,
|
||||
backgroundWork: agent.backgroundWork,
|
||||
runningProviderSubagents: agent.runningProviderSubagents,
|
||||
...projectActiveTurn(agent),
|
||||
capabilities: agent.capabilities,
|
||||
currentModeId: agent.currentModeId,
|
||||
@@ -116,6 +117,7 @@ export function normalizeAgentSnapshot(snapshot: AgentSnapshotPayload, serverId:
|
||||
provider: snapshot.provider,
|
||||
status: snapshot.status,
|
||||
backgroundWork: snapshot.backgroundWork,
|
||||
runningProviderSubagents: snapshot.runningProviderSubagents,
|
||||
turn,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
|
||||
@@ -73,18 +73,6 @@ 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"));
|
||||
|
||||
@@ -19,21 +19,11 @@ 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 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 {
|
||||
export function selectMacDockBadgeCount(state: WorkspaceStatusSource): 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;
|
||||
}
|
||||
}
|
||||
@@ -41,11 +31,11 @@ export function selectMacDockBadgeCount(
|
||||
}
|
||||
|
||||
/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */
|
||||
export function createMacDockBadgeCountSelector(
|
||||
options: DockBadgeOptions = {},
|
||||
): (state: WorkspaceStatusSource) => number | undefined {
|
||||
export function createMacDockBadgeCountSelector(): (
|
||||
state: WorkspaceStatusSource,
|
||||
) => number | undefined {
|
||||
return memoizeOnSessionMaps<WorkspaceStatusSession, WorkspaceStatusSource, number | undefined>(
|
||||
(session) => [session.workspaces],
|
||||
(state) => selectMacDockBadgeCount(state, options),
|
||||
(session) => session.workspaces,
|
||||
selectMacDockBadgeCount,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status";
|
||||
|
||||
function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
@@ -14,21 +14,7 @@ function agent(input: Partial<Agent> & { id: string }): Agent {
|
||||
}
|
||||
|
||||
function stateWith(...agents: Agent[]) {
|
||||
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])),
|
||||
},
|
||||
},
|
||||
};
|
||||
return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } };
|
||||
}
|
||||
|
||||
describe("deriveFaviconStatus", () => {
|
||||
@@ -64,37 +50,6 @@ 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", () => {
|
||||
@@ -108,18 +63,6 @@ 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");
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { Agent, WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import type { Agent } 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 {
|
||||
@@ -17,22 +16,13 @@ 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 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 {
|
||||
export function deriveFaviconStatus(state: FaviconAgentSource): 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;
|
||||
@@ -41,16 +31,10 @@ export function deriveFaviconStatus(
|
||||
return hasAttention || hasNeedsInput ? "attention" : "none";
|
||||
}
|
||||
|
||||
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 {
|
||||
/** A session-store selector for the favicon status that rescans only when an agent map changes. */
|
||||
export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus {
|
||||
return memoizeOnSessionMaps<FaviconAgentSession, FaviconAgentSource, FaviconStatus>(
|
||||
(session) => [session.agents, session.workspaces],
|
||||
(state) => deriveFaviconStatus(state, options),
|
||||
(session) => session.agents,
|
||||
deriveFaviconStatus,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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. `pickMaps` returns every map the selector reads from one session. Session-store writes that leave those maps alone (timeline updates, drafts) then cost
|
||||
* changed. 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>(
|
||||
pickMaps: (session: TSession) => readonly unknown[],
|
||||
pickMap: (session: TSession) => unknown,
|
||||
derive: (state: TState) => TResult,
|
||||
): (state: TState) => TResult {
|
||||
let previousMaps: unknown[] | null = null;
|
||||
let previousResult: TResult;
|
||||
return (state) => {
|
||||
const maps = Object.values(state.sessions).flatMap((session) =>
|
||||
session ? pickMaps(session) : [undefined],
|
||||
const maps = Object.values(state.sessions).map((session) =>
|
||||
session ? pickMap(session) : undefined,
|
||||
);
|
||||
if (
|
||||
previousMaps &&
|
||||
|
||||
@@ -4,8 +4,6 @@ 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]);
|
||||
}
|
||||
@@ -13,10 +11,6 @@ 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 {
|
||||
@@ -274,24 +268,6 @@ 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, nativeImage } from "electron";
|
||||
import { ipcMain } 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, hasPaintedPixels } from "./service.js";
|
||||
import { BrowserTabClosedError, executeAutomationCommand } from "./service.js";
|
||||
import { BrowserSnapshotEngine } from "./snapshot-engine.js";
|
||||
import {
|
||||
listRegisteredPaseoBrowserIds,
|
||||
@@ -133,7 +133,6 @@ 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();
|
||||
@@ -183,9 +182,6 @@ 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,7 +22,6 @@ 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 {
|
||||
@@ -32,14 +31,8 @@ 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();
|
||||
@@ -84,7 +77,6 @@ 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 },
|
||||
@@ -199,11 +191,6 @@ 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;
|
||||
}
|
||||
@@ -231,10 +218,6 @@ 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") {
|
||||
@@ -2052,56 +2035,6 @@ 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,7 +36,6 @@ 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;
|
||||
@@ -53,22 +52,6 @@ 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 {
|
||||
@@ -1365,18 +1348,11 @@ async function executeFullPageScreenshot(
|
||||
const metrics = await getCdpLayoutMetrics(target.contents);
|
||||
width = metrics.contentWidth;
|
||||
height = metrics.contentHeight;
|
||||
const result = (await sendDebugCommand("Page.captureScreenshot", {
|
||||
return (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)) {
|
||||
|
||||
@@ -921,6 +921,8 @@ export const AgentSnapshotPayloadSchema = z.object({
|
||||
lastUserMessageAt: z.string().nullable(),
|
||||
status: AgentStatusSchema,
|
||||
backgroundWork: z.object({ count: z.number().int().nonnegative() }).optional(),
|
||||
/** Provider subagents of this agent still running. Absent when none run or on older daemons. */
|
||||
runningProviderSubagents: z.object({ count: z.number().int().nonnegative() }).optional(),
|
||||
activeTurn: AgentActiveTurnPayloadSchema.nullable().optional(),
|
||||
capabilities: AgentCapabilityFlagsSchema,
|
||||
currentModeId: z.string().nullable(),
|
||||
|
||||
@@ -47,9 +47,6 @@ 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(),
|
||||
})
|
||||
@@ -82,20 +79,9 @@ 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: [] });
|
||||
|
||||
@@ -1456,6 +1456,12 @@ export class AgentManager {
|
||||
return this.backgroundWork.summary(agentId);
|
||||
}
|
||||
|
||||
/** Undefined when none of the agent's provider subagents is running. */
|
||||
getRunningProviderSubagentSummary(agentId: string): { count: number } | undefined {
|
||||
const count = this.providerSubagents.countRunning(agentId);
|
||||
return count > 0 ? { count } : undefined;
|
||||
}
|
||||
|
||||
private clearBackgroundWork(agentId: string): void {
|
||||
const items = this.backgroundWork.clear(agentId);
|
||||
if (items) this.dispatch({ type: "background_work", agentId, items });
|
||||
@@ -2132,7 +2138,7 @@ export class AgentManager {
|
||||
!this.foregroundMutationTails.has(agent.id) &&
|
||||
!this.replacementMutationTails.has(agent.id) &&
|
||||
!this.sessionEventTails.has(agent.id) &&
|
||||
!this.providerSubagents.list(agent.id).some((child) => child.status === "running")
|
||||
this.providerSubagents.countRunning(agent.id) === 0
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -137,6 +137,14 @@ export class ProviderSubagentStore {
|
||||
.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
|
||||
}
|
||||
|
||||
countRunning(parentAgentId: string): number {
|
||||
let count = 0;
|
||||
for (const subagent of this.descriptors.values()) {
|
||||
if (subagent.parentAgentId === parentAgentId && subagent.status === "running") count += 1;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
listAll(): ProviderSubagentDescriptor[] {
|
||||
return [...this.descriptors.values()];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import { createDaemonTestContext, type DaemonTestContext } from "../test-utils/index.js";
|
||||
|
||||
let ctx: DaemonTestContext;
|
||||
let cwd: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
ctx = await createDaemonTestContext();
|
||||
cwd = mkdtempSync(path.join(tmpdir(), "running-provider-subagents-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx.cleanup();
|
||||
rmSync(cwd, { recursive: true, force: true });
|
||||
}, 30_000);
|
||||
|
||||
test("an idle agent's snapshot reports the provider subagent it left running until it finishes", async () => {
|
||||
const updates: AgentSnapshotPayload[] = [];
|
||||
ctx.client.subscribeRawMessages((message) => {
|
||||
if (message.type === "agent_update" && message.payload.kind === "upsert") {
|
||||
updates.push(message.payload.agent);
|
||||
}
|
||||
});
|
||||
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
|
||||
|
||||
await ctx.client.sendMessage(agent.id, "Emit a provider child that outlives the turn");
|
||||
expect((await ctx.client.waitForFinish(agent.id, 15_000)).status).toBe("idle");
|
||||
|
||||
const idle = await ctx.client.fetchAgent({ agentId: agent.id });
|
||||
expect(idle?.agent).toMatchObject({ status: "idle", runningProviderSubagents: { count: 1 } });
|
||||
|
||||
// The child finishes after the turn: subscribers get a snapshot without the count.
|
||||
await expect
|
||||
.poll(() => {
|
||||
const latest = updates.findLast((update) => update.id === agent.id);
|
||||
return latest ? { status: latest.status, running: latest.runningProviderSubagents } : null;
|
||||
})
|
||||
.toEqual({ status: "idle", running: undefined });
|
||||
const finished = await ctx.client.fetchAgent({ agentId: agent.id });
|
||||
expect(finished?.agent.runningProviderSubagents).toBeUndefined();
|
||||
}, 60_000);
|
||||
@@ -412,6 +412,7 @@ function createSessionForTest(options: SessionForTestOptions = {}): Session {
|
||||
listAgents: vi.fn(() => []),
|
||||
listProviderSubagentActivity: vi.fn(() => []),
|
||||
getAgentBackgroundWorkSummary: () => undefined,
|
||||
getRunningProviderSubagentSummary: () => undefined,
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
...options.agentManager,
|
||||
}),
|
||||
|
||||
@@ -2258,8 +2258,11 @@ export class Session {
|
||||
private forwardProviderSubagent(event: ProviderSubagentManagerEvent): void {
|
||||
const parentAgentId =
|
||||
event.type === "upsert" ? event.subagent.parentAgentId : event.parentAgentId;
|
||||
if (this.agentManager.getAgent(parentAgentId)?.internal) return;
|
||||
this.emitProviderSubagentWorkspaceUpdate(event);
|
||||
const parent = this.agentManager.getAgent(parentAgentId);
|
||||
if (parent?.internal) return;
|
||||
// The parent's snapshot carries its running subagent count, and forwarding it also
|
||||
// refreshes the parent's workspace.
|
||||
if (event.type !== "timeline" && parent) void this.agentUpdates.forwardLiveAgent(parent);
|
||||
this.forwardProviderSubagentUpdate(event);
|
||||
}
|
||||
|
||||
@@ -2275,24 +2278,6 @@ export class Session {
|
||||
if (agent) void this.agentUpdates.forwardLiveAgent(agent);
|
||||
}
|
||||
|
||||
private emitProviderSubagentWorkspaceUpdate(event: ProviderSubagentManagerEvent): void {
|
||||
if (event.type === "timeline") {
|
||||
return;
|
||||
}
|
||||
const parentAgentId =
|
||||
event.type === "upsert" ? event.subagent.parentAgentId : event.parentAgentId;
|
||||
const parent = this.agentManager.getAgent(parentAgentId);
|
||||
if (!parent?.workspaceId) {
|
||||
return;
|
||||
}
|
||||
void this.emitWorkspaceUpdateForWorkspaceId(parent.workspaceId).catch((error) => {
|
||||
this.sessionLogger.error(
|
||||
{ err: error, parentAgentId, workspaceId: parent.workspaceId },
|
||||
"Failed to emit provider subagent workspace update",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private buildAgentStreamPayload(
|
||||
event: Extract<AgentManagerEvent, { type: "agent_stream" }>,
|
||||
serializedEvent: Extract<SessionOutboundMessage, { type: "agent_stream" }>["payload"]["event"],
|
||||
@@ -2308,6 +2293,9 @@ export class Session {
|
||||
|
||||
private async enrichAgentPayload(payload: AgentSnapshotPayload): Promise<AgentSnapshotPayload> {
|
||||
payload.backgroundWork = this.agentManager.getAgentBackgroundWorkSummary(payload.id);
|
||||
payload.runningProviderSubagents = this.agentManager.getRunningProviderSubagentSummary(
|
||||
payload.id,
|
||||
);
|
||||
const storedRecord = await this.agentStorage.get(payload.id);
|
||||
payload.title = storedRecord?.title ?? null;
|
||||
payload.archivedAt = storedRecord?.archivedAt ?? null;
|
||||
|
||||
@@ -589,6 +589,27 @@ class FakeAgentSession implements AgentSession {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider child that keeps running after the turn completes, then finishes on its own a
|
||||
* moment later, the way a Claude background subagent does.
|
||||
*/
|
||||
private async emitProviderChildOutlivingTurn(): Promise<void> {
|
||||
const child = (status: "running" | "completed"): AgentStreamEvent => ({
|
||||
type: "provider_subagent",
|
||||
provider: this.providerName,
|
||||
event: { type: "upsert", id: "outliving-child", title: "Outliving child", status },
|
||||
});
|
||||
await this.emitEvent(child("running"));
|
||||
await this.emitEvent({
|
||||
type: "turn_completed",
|
||||
provider: this.providerName,
|
||||
usage: { inputTokens: 1, outputTokens: 1 },
|
||||
});
|
||||
setTimeout(() => {
|
||||
this.emitEvent(child("completed")).catch(() => undefined);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
private async emitStressTurn(stress: { count: number; coalesced: boolean }): Promise<void> {
|
||||
for (let index = 0; index < stress.count; index += 1) {
|
||||
const stressUpdate: AgentStreamEvent = {
|
||||
@@ -832,6 +853,11 @@ class FakeAgentSession implements AgentSession {
|
||||
this.notifySubscribers(child);
|
||||
}
|
||||
|
||||
if (textPrompt === "Emit a provider child that outlives the turn") {
|
||||
await this.emitProviderChildOutlivingTurn();
|
||||
return;
|
||||
}
|
||||
|
||||
if (textPrompt === "Start background work") {
|
||||
await this.emitBackgroundWorkTurn();
|
||||
return;
|
||||
|
||||
@@ -39,6 +39,7 @@ export function asAgentManager(stub: {
|
||||
getRetiredInternalAgent: () => null,
|
||||
effectiveOptionsFor: (_provider: string, own?: Record<string, unknown>) => own ?? {},
|
||||
getAgentBackgroundWorkSummary: () => undefined,
|
||||
getRunningProviderSubagentSummary: () => undefined,
|
||||
...stub,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -118,6 +118,10 @@ class InMemoryAgentManager {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
getRunningProviderSubagentSummary() {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
fetchTimeline(_agentId: string, options?: AgentTimelineFetchOptions) {
|
||||
return this.timeline.fetch("agent-1", options);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import { execFile, execFileSync } from "node:child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { execFile, execFileSync, spawn } from "node:child_process";
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -577,130 +569,7 @@ 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();
|
||||
@@ -717,24 +586,42 @@ test.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
throw new Error(result.error ?? "Failed to create worktree workspace");
|
||||
}
|
||||
|
||||
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);
|
||||
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()));
|
||||
|
||||
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(directory)).toBe(true);
|
||||
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);
|
||||
} finally {
|
||||
if (existsSync(directory)) chmodSync(directory, originalMode);
|
||||
writeFileSync(stopWriterPath, "stop\n");
|
||||
await writerExit;
|
||||
}
|
||||
|
||||
const retry = await ctx.client.archiveWorkspace(workspace.id);
|
||||
|
||||
expect(retry.error).toBeNull();
|
||||
expect(existsSync(directory)).toBe(false);
|
||||
},
|
||||
60000,
|
||||
);
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
import { DaemonClient } from "./test-utils/daemon-client.js";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import {
|
||||
existsSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
renameSync,
|
||||
mkdirSync,
|
||||
} from "node:fs";
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
@@ -133,55 +125,6 @@ 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,7 +14,6 @@ import {
|
||||
PaseoConfigRawSchema,
|
||||
getWorktreeSetupCommands,
|
||||
getWorktreeTeardownCommands,
|
||||
getWorktreeTeardownTimeoutMs,
|
||||
} from "./worktree.js";
|
||||
import {
|
||||
readPaseoConfigForEdit,
|
||||
@@ -296,34 +295,6 @@ 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,8 +5,17 @@ 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 {
|
||||
@@ -33,7 +42,19 @@ 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);
|
||||
});
|
||||
|
||||
@@ -73,8 +94,8 @@ describe("worktree shell selection", () => {
|
||||
branchName: "main",
|
||||
});
|
||||
|
||||
expect(spawnProcessMock).toHaveBeenCalledTimes(1);
|
||||
expect(spawnProcessMock).toHaveBeenCalledWith(
|
||||
expect(execFileMock).toHaveBeenCalledTimes(1);
|
||||
expect(execFileMock).toHaveBeenCalledWith(
|
||||
"powershell",
|
||||
[
|
||||
"-NoProfile",
|
||||
@@ -84,10 +105,11 @@ describe("worktree shell selection", () => {
|
||||
"-Command",
|
||||
"Write-Output 'teardown'",
|
||||
],
|
||||
expect.objectContaining({ cwd: worktreePath, shell: false }),
|
||||
expect.objectContaining({ cwd: worktreePath }),
|
||||
expect.any(Function),
|
||||
);
|
||||
const spawnOptions = spawnProcessMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv };
|
||||
expect(spawnOptions.env?.BASH_ENV).toBeUndefined();
|
||||
const execOptions = execFileMock.mock.calls[0]?.[2] as { env?: NodeJS.ProcessEnv };
|
||||
expect(execOptions.env?.BASH_ENV).toBeUndefined();
|
||||
} finally {
|
||||
if (originalBashEnv === undefined) {
|
||||
delete process.env.BASH_ENV;
|
||||
|
||||
@@ -190,30 +190,6 @@ 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 });
|
||||
|
||||
@@ -146,13 +146,6 @@ 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[];
|
||||
|
||||
@@ -288,13 +281,6 @@ 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[]> {
|
||||
@@ -463,14 +449,12 @@ 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 outputChunks: Record<"stdout" | "stderr", string[]> = { stdout: [], stderr: [] };
|
||||
const outputLimit = options.maxOutputCharsPerStream ?? Infinity;
|
||||
const remainingOutputChars = { stdout: outputLimit, stderr: outputLimit };
|
||||
const stdoutChunks: string[] = [];
|
||||
const stderrChunks: string[] = [];
|
||||
let settled = false;
|
||||
let termination: Promise<unknown> | null = null;
|
||||
|
||||
@@ -479,10 +463,10 @@ async function execSetupCommandStreamed(options: {
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
const retainedText = text.slice(0, remainingOutputChars[stream]);
|
||||
if (retainedText) {
|
||||
outputChunks[stream].push(retainedText);
|
||||
remainingOutputChars[stream] -= retainedText.length;
|
||||
if (stream === "stdout") {
|
||||
stdoutChunks.push(text);
|
||||
} else {
|
||||
stderrChunks.push(text);
|
||||
}
|
||||
options.onEvent?.({
|
||||
type: "output",
|
||||
@@ -501,17 +485,12 @@ async function execSetupCommandStreamed(options: {
|
||||
}
|
||||
settled = true;
|
||||
options.signal?.removeEventListener("abort", abort);
|
||||
if (termination) {
|
||||
await termination;
|
||||
// A descendant can keep these pipes open after the shell exits.
|
||||
child.stdout?.destroy();
|
||||
child.stderr?.destroy();
|
||||
}
|
||||
await termination;
|
||||
const result: WorktreeSetupCommandResult = {
|
||||
command: options.command,
|
||||
cwd: options.cwd,
|
||||
stdout: outputChunks.stdout.join(""),
|
||||
stderr: outputChunks.stderr.join(""),
|
||||
stdout: stdoutChunks.join(""),
|
||||
stderr: stderrChunks.join(""),
|
||||
exitCode,
|
||||
durationMs: Date.now() - startedAt,
|
||||
};
|
||||
@@ -550,7 +529,6 @@ async function execSetupCommandStreamed(options: {
|
||||
gracefulTimeoutMs: 1000,
|
||||
forceTimeoutMs: 1000,
|
||||
});
|
||||
void finish(null);
|
||||
};
|
||||
if (options.signal?.aborted) {
|
||||
abort();
|
||||
@@ -790,26 +768,17 @@ 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 [index, cmd] of teardownCommands.entries()) {
|
||||
const result = await execSetupCommandStreamed({
|
||||
command: cmd,
|
||||
for (const cmd of teardownCommands) {
|
||||
const result = await execSetupCommand(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${reason}`.trim(),
|
||||
`Worktree teardown command failed: ${cmd}\n${result.stderr}`.trim(),
|
||||
results,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,291 +0,0 @@
|
||||
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"]);
|
||||
});
|
||||
});
|
||||
@@ -2,8 +2,7 @@
|
||||
// Copyright (c) 2026 Carlos Precioso.
|
||||
import { execFile } from "node:child_process";
|
||||
import { constants, existsSync } from "node:fs";
|
||||
import { copyFile, mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { copyFile, mkdir } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
@@ -23,33 +22,37 @@ async function git(cwd: string, args: string[], input?: string): Promise<string>
|
||||
return stdout;
|
||||
}
|
||||
|
||||
// `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;
|
||||
async function gitAllowExit1(cwd: string, args: string[], input: string): Promise<string> {
|
||||
try {
|
||||
output = await git(cwd, [...args, "check-ignore", "--stdin", "-z"], input);
|
||||
return await git(cwd, args, 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 = await findIncludedFiles(source);
|
||||
const matches = splitNul(
|
||||
await git(source, [
|
||||
"ls-files",
|
||||
"--others",
|
||||
"--ignored",
|
||||
`--exclude-from=${INCLUDE_FILE}`,
|
||||
"-z",
|
||||
]),
|
||||
);
|
||||
if (matches.length === 0) return { kind: "copied", copied: [], skipped: [] };
|
||||
|
||||
const ignored = await checkIgnore(source, [], matches);
|
||||
const ignored = splitNul(
|
||||
await gitAllowExit1(source, ["check-ignore", "--stdin", "-z"], matches.join("\0") + "\0"),
|
||||
);
|
||||
|
||||
const copied: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
@@ -66,152 +69,3 @@ 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;
|
||||
}
|
||||
|
||||
@@ -122,19 +122,6 @@ 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.
|
||||
|
||||
@@ -120,19 +120,6 @@ 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 流量路由给它。
|
||||
|
||||
@@ -36,8 +36,6 @@ 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,8 +36,6 @@ 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。保持该插件启用才能执行复制。
|
||||
|
||||
@@ -52,36 +52,6 @@ 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.
|
||||
|
||||
Reference in New Issue
Block a user