Compare commits

..
Author SHA1 Message Date
Mohamed Boudra e504877752 Keep pending session imports tied to their original host 2026-11-24 16:03:06 +01:00
paseo-bot[bot]andderek 096de6a1f6 fix(app): scope Import Session results to the selected host
Co-authored-by: derek <174018435+derek-geekdive@users.noreply.github.com>
2026-11-24 15:59:19 +01:00
paseo-bot[bot] 7ee7c2adbf test(server): give Worktrunk integration fixtures time to finish 2026-11-24 15:59:19 +01:00
paseo-bot[bot] 2531ba2542 fix(server): preserve timely ACP initialization errors during listing 2026-11-24 15:59:19 +01:00
paseo-bot[bot] ed21847121 fix(server): preserve timely ACP listing errors during cleanup
A provider error returned within the listing window can still be displayed while its probe shuts down.
2026-11-24 15:59:19 +01:00
paseo-bot[bot] 8ad8c40d67 fix(server): return Import Session results before probe cleanup finishes
A timely ACP listing was discarded when process shutdown crossed the listing deadline. Return the completed rows and let the adapter finish reclaiming the probe.
2026-11-24 15:59:19 +01:00
Chirag Singhal 685a4f2ad2 fix: show import provider errors and retry progress 2026-11-24 15:59:19 +01:00
paseo-bot[bot]andChirag Singhal b8516bb2c1 fix(server): keep the full Import Session deadline
Start ACP probe cleanup when the agent manager stops waiting. Keep the 90-second window for listings that still have time to finish.

Co-authored-by: Chirag Singhal <76880977+chirag127@users.noreply.github.com>
2026-11-24 15:59:19 +01:00
Chirag Singhal 0d0aa27584 fix: bound import listing and clean up ACP probes 2026-11-24 15:59:18 +01:00
Mohamed BoudraandTaras Kornichuk e06bfbb94c Redesign host picker with configurable auto-detected icons, connection type, and latency (#10702)
Supersedes #5787.

- Add best-effort daemon hardware detection (macOS ioreg/sysctl, Linux containers, WSL, device-tree boards, cloud/VM DMI, SMBIOS chassis) exposed as optional `machineKind` on `server_info` and `/api/status`.
- Add configurable per-host icons in Host Settings -> Appearance (`Auto` plus 9 icons across all 9 locales), keeping `icon` omitted while untouched for rollback compatibility and preserving unknown future icons on disk.
- Redesign `HostPicker` and `HostChooserModal` with resolved host icons, connection type (`Local`, `Tailscale`, `Relay`, `SSH`, `Direct`, `Via`) + endpoint, on-demand round-trip latency, aligned leading and content rails, and full keyboard navigation.
- Update the website host mockup to match.

Co-authored-by: Taras Kornichuk <dread9ko@gmail.com>
2026-11-24 21:52:39 +07:00
paseo-bot[bot] 7bcd598f09 test(terminal): speed up history setup for pressure recovery (#10683)
Windows timed out while the fixture printed 12,050 rows before signaling readiness. Batch the initial writes and keep the live burst and replay assertions.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-24 12:01:34 +00:00
Mohamed Boudra c626bf3707 Skip worktree teardown commands for unapproved cross-repository checkouts (#10694)
* fix(server): skip teardown commands when archiving unapproved checkouts

`archiveByScope` previously treated `assertWorkspaceAutomationAllowed` as optional and did not skip `runWorktreeTeardownCommands` when `untrustedBacking` was already true or when archiving an unrecorded worktree directory. Four callers (`CreateAgentLifecycleDispatch`, `archiveIfSafe`, `paseo-tools` `archive_workspace`, and `handlePaseoWorktreeArchiveRequest`) also omitted `assertWorkspaceAutomationAllowed`, letting `paseo.json` teardown commands run during failed agent creation cleanup, first-turn auto-archive, auto-archive on merge, MCP workspace archive, and worktree archive RPCs.

Make `assertWorkspaceAutomationAllowed` and `isCheckoutUntrusted` required on `ArchiveDependencies`, skip teardown whenever the backing checkout is untrusted, any workspace on the checkout is blocked, or no active workspace record exists, and wire the guard through all archive callers.

* fix(server): scope archive teardown check to active checkout workspaces

`isCheckoutUntrusted` scans all workspace records by path, including previously archived records, so gating teardown on it suppressed `paseo.json` teardown for a fresh approved worktree that reused a previously archived unapproved slug path.

Keep teardown approval scoped to the active workspaces sharing the backing checkout at archive start (the records being archived plus active siblings), drop the null-workspace fallback target for unrecorded worktree-scope archives so they never run teardown or flip `untrustedBacking`, and verify caller wiring reaches `assertWorkspaceAutomationAllowed` directly.

* fix(server): inherit untrustedSource when unarchiving onto an active unapproved checkout

Unarchiving a previously approved workspace onto an existing directory that currently holds an active unapproved checkout left the restored workspace without `untrustedSource`. If the unapproved sibling was archived first, the directory remained on disk and archiving the restored workspace could run teardown commands.

Inherit `untrustedSource` from active workspaces sharing the checkout root in `ensureWorkspaceRecordUnarchived`, while ignoring already-archived historical records so restoring an approved checkout onto a reused path stays approved.

* fix(server): bind automation approval state to checkout worktree metadata

Keeping `untrustedSource` only on workspace records meant a retained unapproved worktree directory could lose its teardown block if its last unapproved workspace was archived and an older approved workspace was unarchived onto that path, while scanning archived records by path blocked fresh worktrees that reused a deleted slug.

Persist `untrustedSource` on the checkout itself in `paseo/worktree.json` when creating or restoring an unapproved worktree, clear it in `clearWorkspaceAutomationBlock` when setup is approved, and read it in both `workspace-archive-service` and `workspace-provisioning-service`. Deleting the worktree removes its metadata automatically, so fresh worktrees reusing the path start clean while retained checkouts keep their block across workspace archives and restores.

* fix(server): backfill worktree metadata when archiving retained unapproved checkouts

Unapproved checkouts created before `paseo/worktree.json` stored `untrustedSource` carry their block only in the workspace record. If archive keeps the directory on disk (such as a retained sibling or nested worktree), backfilling `untrustedSource` into `paseo/worktree.json` before removal ensures the retained checkout keeps its block even after its unapproved workspace record is archived.

* fix(server): never propagate archived untrustedSource onto fresh checkouts

Both archive metadata backfill and directory workspace creation previously consulted already-archived records matching a path, allowing an old archived unapproved record to copy `untrustedSource` onto a fresh approved worktree that reused the same slug path.

Ignore `untrustedSource` on already-archived records during archive target resolution and metadata backfill (only backfill when active workspaces are being archived), and share one `resolveCheckoutUntrustedSource` rule across `createWorkspaceForDirectory` and `ensureWorkspaceRecordUnarchived` that checks `paseo/worktree.json` first and falls back only to active workspaces.

* fix(server): align unarchived workspace approval state with the live checkout

Unarchiving an old unapproved workspace onto a path already owned by an active approved checkout kept the old record's stale `untrustedSource`, causing a later re-archive of that workspace to backfill the block onto the fresh checkout's metadata.

Align `ensureWorkspaceRecordUnarchived` symmetrically with the live checkout: adopt `untrustedSource` from `paseo/worktree.json` or active workspaces on the checkout when present, and drop stale `untrustedSource` when live active workspaces own an approved checkout at that path.

* fix(server): preserve block when opening a pre-upgrade retained checkout

Opening a pre-upgrade retained checkout directory whose last unapproved workspace was already archived before this change has no active workspace on the path and no `untrustedSource` in `paseo/worktree.json`.

In `resolveCheckoutUntrustedSource`, prefer `paseo/worktree.json`, then active workspaces on the checkout when any exist (so a fresh approved worktree at a reused path stays approved), and only when zero active workspaces exist on the directory fall back to the most recently archived record for that path.

* fix(server): share one checkout approval lookup across open and unarchive

* fix(server): resolve checkout approval state only from metadata and active workspaces

* fix(server): keep archive read-only on worktree approval metadata

* fix(server): serialize setup approval with archive checkout lock and backfill retained metadata

* fix(server): fail setup approval before clearing records when worktree metadata write fails
2026-11-24 17:46:23 +07:00
189 changed files with 7691 additions and 9771 deletions
-2
View File
@@ -422,7 +422,6 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/headers/screen-header.tsx",
"packages/app/src/components/host-status-dot.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/icons/paseo-logo.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/plan-card.tsx",
@@ -554,7 +553,6 @@
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/highlighted-code-block.tsx",
"packages/app/src/components/hosts/host-filter.tsx",
"packages/app/src/components/hosts/host-picker.tsx",
"packages/app/src/components/import-session-sheet.tsx",
"packages/app/src/components/left-sidebar.tsx",
"packages/app/src/components/markdown/fence/mermaid/host.native.tsx",
-1
View File
@@ -54,7 +54,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
+3 -6
View File
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
see [owned history](timeline-sync.md#owned-history).
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
primed.
Reload releases the old runtime before resuming its durable session: an idle provider process can
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
@@ -256,8 +256,7 @@ lifecycle is separate from public workspace visibility and is not a public creat
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
children. The timeline and the provider children stay, so an archived chat reads them without its
provider; deleting the agent removes them.
children.
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
@@ -353,8 +352,6 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
-1
View File
@@ -94,7 +94,6 @@ workspace for a directory clears it. The store lives in memory and resets on dae
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
-8
View File
@@ -181,14 +181,6 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Runtime-only Agent Timelines
Agent timelines are not written to `$PASEO_HOME`. `AgentTimeline` owns each agent's history behind
a backend, and the only backend is in memory, so a daemon restart loses it and the next resume
imports provider history. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
+11 -63
View File
@@ -5,9 +5,15 @@ Agent chat delivery has two paths:
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
Pagination bounds each read, not total resident history. Streaming overhead must remain
proportional to the retained transcript. Cumulative text snapshots must be released after their
deltas have been consumed.
The daemon retains projected items in memory. Each source event advances the stream sequence,
then replaces the previous tool state or merges into the current text item. Intermediate payloads
are never retained for history or catch-up. Provider history is the durable transcript authority
and rebuilds the projection when an agent resumes.
Pagination bounds each read, not total resident history. Active and idle agents retain their
projected transcript; archive releases it and later history reads rebuild it from the provider.
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
must be released after their deltas have been consumed.
The invariants are:
@@ -26,45 +32,6 @@ bounded item is used for runtime timeline rows and live stream events. Provider
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Owned history
The daemon owns each agent's history in `AgentTimeline`
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
child's descriptor and history in a child scope of the same agent. Each source event advances the
stream sequence, then replaces the previous tool state or merges into the current text item.
Intermediate payloads are never retained for history or catch-up.
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
deleting the agent, or a provider removing one of its own children, deletes history.
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Deleting the agent deletes its history and every child's, retired ones
included.
`epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The only backend keeps everything in
memory, so a daemon restart loses the owned history: the next resume imports provider history into
a new epoch, and clients take the destructive reset below. Rewinds retired before the restart come
back if the provider history still holds them. Retained history costs memory for every loaded,
closed or archived agent until the daemon exits or the agent is deleted.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
judged from the resumed provider history. When that history proves nothing, the rewind stays open
and the agent refuses prompts with the unknown-outcome error.
## Presence is not delivery
Client heartbeat reports presence:
@@ -201,7 +168,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
that cursor are applied. Already-covered rows are not replayed.
- A true middle gap or epoch change atomically replaces stale canonical history with the
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
local submissions; it never retains two discontiguous canonical ranges.
@@ -214,24 +181,6 @@ history replay. The pending approval UI can hide that tool from presentation, bu
must retain its position. Creating a new history card on rejection places it after the prompt that
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
## Rewind retires rows
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
in the same commit. They leave the listing, keep their history, and drop late provider events.
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
a wire epoch that changes with each retirement, so they take the destructive replacement they
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
## Provider child history
Child transcripts use the same projected-page reconciliation as the main conversation. The client
@@ -396,7 +345,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
arrived first. Generic reducers and consumers do not reimplement message identity matching.
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
rows because a provider may never echo them. A known epoch change replaces history and
rows because a provider may never echo them. A known epoch change or rewind replaces history and
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
reset without an existing epoch is destructive because the client has no continuity anchor.
@@ -412,7 +361,6 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
## Relevant code
- Server owned history: `packages/server/src/server/agent/timeline/`
- Server live stream forwarding: `packages/server/src/server/session.ts`
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
@@ -13,13 +13,6 @@ import {
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
import {
closeWorkspaceAgentTab,
fetchAgentArchivedAt,
primeAdditionalPage,
resetSeededPageState,
} from "../support/helpers/archive-tab";
async function completeSubmittedTurn(
page: Page,
@@ -55,102 +48,26 @@ async function expectTurnCompletesNormally(
await expectAgentIdle(page);
}
async function openAgentOnAnotherClient(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await primeAdditionalPage(page);
await resetSeededPageState(page);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
}
/** The prompts the chat shows, in order, each exactly once. */
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect(messages).toHaveCount(prompts.length);
await expect(messages).toContainText(prompts);
}
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
const tabId = `workspace-tab-agent_${agentId}`;
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
}
async function archiveAgentByClosingTab(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await closeWorkspaceAgentTab(page, agent.agentId);
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
}
async function unarchiveAgent(page: Page): Promise<void> {
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
}
async function expectToast(page: Page, message: string): Promise<void> {
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
}
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
const UNSYNCED_RELOAD =
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
/** The prompts of the whole conversation, after scrolling up through its older pages. */
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return await messages.count();
})
.toBe(prompts.length);
await expect(messages).toContainText(prompts);
}
// A row React remounts loses this attribute; one that stays mounted keeps it.
async function markMounted(row: Locator): Promise<void> {
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
}
async function expectStillMounted(row: Locator): Promise<void> {
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
}
test.describe("Agent message rewind", () => {
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
page,
}) => {
test.setTimeout(150_000);
test.setTimeout(90_000);
const retainedPrompt = "Keep this completed turn after rewind.";
const rewoundPrompt = "Remove this completed turn after rewind.";
const nextPrompt = "Continue after the rewind.";
const preservedDraft = "Keep this human draft after rewind.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-roundtrip-",
title: "Message rewind roundtrip",
model: "ten-second-stream",
});
const otherClient = await page.context().newPage();
try {
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
await completeSubmittedTurn(page, agent, retainedPrompt);
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
await test.step("a second client opens the same chat", async () => {
await openAgentOnAnotherClient(otherClient, agent);
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
});
await markMounted(retainedMessage);
await scrollChatAwayFromBottom(page, {
deltaY: -900,
minDistanceFromBottom: 300,
@@ -159,92 +76,19 @@ test.describe("Agent message rewind", () => {
await blurComposerInput(page);
rewindCompletion.clearTimelineStreamCount();
await test.step("the rewind stays pending until the daemon answers", async () => {
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
});
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
await test.step("the rewound turn leaves without reloading the chat", async () => {
await expectPrompts(page, [retainedPrompt]);
await expectStillMounted(retainedMessage);
expect(rewindCompletion.timelineFetchCount()).toBe(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await expectPrompts(otherClient, [retainedPrompt]);
});
await test.step("the next prompt appears once on both clients", async () => {
await completeSubmittedTurn(otherClient, agent, nextPrompt);
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
await expectPrompts(page, [retainedPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the rewound conversation", async () => {
await otherClient.reload();
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
});
} finally {
await otherClient.close();
await agent.cleanup();
}
});
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
page,
}) => {
test.setTimeout(150_000);
const keptPrompt = "Keep this turn through reload and archive.";
const rewoundPrompt = "Rewind this turn before reloading.";
const nextPrompt = "Continue after the rewind, then reload.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-reload-archive-",
title: "Message rewind reload archive",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, keptPrompt);
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
await rewindConversation(page, rewound, rewoundPrompt);
await expectPrompts(page, [keptPrompt]);
await completeSubmittedTurn(page, agent, nextPrompt);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
await reloadAgentFromTabMenu(page, agent.agentId);
await expectToast(page, UNSYNCED_RELOAD);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await expectComposerVisible(page);
});
await test.step("the archived chat shows the rewound conversation", async () => {
await archiveAgentByClosingTab(page, agent);
await openAgentRoute(page, agent);
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("unarchiving keeps the rewound conversation", async () => {
await unarchiveAgent(page);
await expectToast(page, UNSYNCED_RELOAD);
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the same conversation", async () => {
await page.reload();
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
0,
);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
} finally {
await agent.cleanup();
}
@@ -4,6 +4,7 @@ import {
addConnectedHostAndReload,
chooseHostBadgeDisplay,
chooseHostColor,
chooseHostIcon,
expectHostAppearancePreview,
expectHostBadgeIconOnly,
expectHostBadgeName,
@@ -115,12 +116,21 @@ test("customizes a host badge and preserves its appearance after reload", async
expect(widths.content).toBeLessThanOrEqual(widths.client);
});
await test.step("preview a color and apply it to the sidebar badge", async () => {
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
await openHostAppearanceSettings(page, badge.serverId);
await chooseHostColor(page, "Teal");
await chooseHostIcon(page, "Laptop");
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
await leaveHostAppearanceSettings(page);
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
await page.getByTestId("sidebar-hosts-trigger").click();
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
await expect(hostRow).toBeVisible();
await expect(hostRow).toContainText("Direct");
await expect(hostRow).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/);
await expect(hostRow).not.toContainText(/agents?/i);
await page.keyboard.press("Escape");
});
await test.step("keep the icon-only preference through reload", async () => {
@@ -145,3 +155,30 @@ test("customizes a host badge and preserves its appearance after reload", async
});
});
});
base(
"activates Add host from the sidebar host picker via focus+Enter and Arrow+Enter",
async ({ page }) => {
await gotoAppShell(page);
const trigger = page.getByTestId("sidebar-hosts-trigger");
await expect(trigger).toBeVisible();
// Focus + Enter on Add host must open the Add connection dialog rather than selecting the active host.
const addConnectionDialog = page.getByRole("dialog").filter({ hasText: "Add connection" });
await trigger.click();
const addHostButton = page.getByRole("button", { name: "Add host", exact: true });
await expect(addHostButton).toBeVisible();
await addHostButton.focus();
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
await page.keyboard.press("Escape");
await expect(addConnectionDialog).toBeHidden();
// ArrowDown + Enter must also reach Add host from the host list.
await trigger.click();
await expect(addHostButton).toBeVisible();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await expect(addConnectionDialog).toBeVisible();
},
);
@@ -4,10 +4,15 @@ import { copyFile, mkdir, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { TestInfo } from "@playwright/test";
import type { FetchRecentProviderSessionsRequestMessage } from "@getpaseo/protocol/messages";
import { expect, test, type Page } from "../support/fixtures";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { addConnectedHostAndReload } from "../support/helpers/hosts";
import { ImportSessionFlow } from "../support/helpers/import-session";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import {
connectNewWorkspaceDaemonClient,
loadSessionMessageReaders,
openProjectViaDaemon,
type OpenedProject,
} from "../support/helpers/new-workspace";
@@ -20,16 +25,22 @@ const SCREENSHOT_DIRECTORY = path.join(
const claudeConfigDirectory = mkdtempSync(path.join(tmpdir(), "paseo-import-flow-claude-"));
const brokenProvider = "broken-acp";
const disabledProviders = {
codex: { enabled: false },
copilot: { enabled: false },
omp: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
antigravity: { enabled: false },
muse: { enabled: false },
};
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
codex: { enabled: false },
copilot: { enabled: false },
omp: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
...disabledProviders,
[brokenProvider]: {
extends: "acp",
label: "Broken ACP",
@@ -136,6 +147,120 @@ test("an open Import Session row keeps its age current", async ({ page }) => {
await expect(row).toContainText("4m ago");
});
test("shows listing failure details beside healthy sessions and retries the failed provider", async ({
page,
}, testInfo) => {
const frames = await loadSessionMessageReaders();
const requests: FetchRecentProviderSessionsRequestMessage[] = [];
const completed = new Set<string>();
page.on("websocket", (socket) => {
socket.on("framesent", ({ payload }) => {
const request = frames.client(payload);
if (request?.type === "fetch_recent_provider_sessions_request") {
requests.push(request);
}
});
socket.on("framereceived", ({ payload }) => {
const response = frames.server(payload);
if (response?.type === "fetch_recent_provider_sessions_response") {
completed.add(response.payload.requestId);
}
});
});
const flow = new ImportSessionFlow(page);
for (const width of [1280, 390]) {
await flow.openWorkspace(scenario.project.workspaceId, { width, height: 844 });
await flow.openGlobally();
await flow.expectProviderError("Broken ACP");
const healthySession = page.getByTestId(
`import-session-session-claude-${scenario.importSessionId}`,
);
await expect(healthySession).toBeVisible();
await page.screenshot({ path: testInfo.outputPath(`listing-failure-${width}.png`) });
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
"missing-agent-command",
);
const requestOffset = requests.length;
await flow.retryProvider(brokenProvider, "Broken ACP");
await expect
.poll(() => requests.slice(requestOffset).map((request) => request.providers))
.toEqual([[brokenProvider]]);
const retriedRequest = requests[requestOffset];
if (!retriedRequest) throw new Error("Retry did not send a provider listing request");
await expect.poll(() => completed.has(retriedRequest.requestId)).toBe(true);
await expect(page.getByTestId(`import-session-retry-${brokenProvider}`)).toBeEnabled();
await expect(page.getByTestId("import-session-provider-errors")).toContainText(
"missing-agent-command",
);
await expect(healthySession).toBeVisible();
await page.screenshot({ path: testInfo.outputPath(`listing-failure-retry-${width}.png`) });
await flow.close();
}
});
test("Import Session keeps listings tied to their host during a switch and a pending import", async ({
page,
}) => {
const secondaryHost = await startIsolatedHostDaemon("import-session-secondary", {
config: {
agents: {
providers: {
...disabledProviders,
claude: { enabled: false },
[brokenProvider]: {
extends: "acp",
label: "Broken ACP",
command: ["missing-secondary-command", "acp"],
},
},
},
},
});
try {
const gate = await installDaemonWebSocketGate(page);
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 1280, height: 844 });
await addConnectedHostAndReload(page, {
serverId: secondaryHost.serverId,
port: secondaryHost.port,
label: "Second import host",
primaryLabel: "First import host",
});
await flow.chooseHostForImport("First import host");
await expect(page.getByText(/missing-agent-command/)).toBeVisible();
await flow.close();
await flow.chooseHostForImport("Second import host");
await expect(page.getByText(/missing-secondary-command/)).toBeVisible();
await expect(page.getByText(/missing-agent-command/)).toHaveCount(0);
await flow.close();
await test.step("returning to the original host omits the session imported during the switch", async () => {
const sessionId = "fixture-root-04";
await flow.chooseHostForImport("First import host");
gate.holdNextClientRequest("import_agent_request");
await flow.startImport(sessionId);
await gate.waitForHeldClientRequest();
await flow.close();
await flow.chooseHostForImport("Second import host");
await flow.expectProviderError("Broken ACP");
gate.releaseHeldClientRequest();
await flow.expectClosed();
await flow.chooseHostForImport("First import host");
await flow.revealSession("fixture-worktree");
await flow.expectSessionUnavailable(sessionId);
await flow.close();
await flow.expectTranscript("Review fixture item 4", "Fixture response 4");
});
} finally {
await secondaryHost.close();
}
});
test("captures the compact import-session journey", async ({ page }, testInfo) => {
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 390, height: 844 });
@@ -378,7 +503,13 @@ async function seedClaudeSessions(input: {
unrelatedDirectory: string;
importSessionId: string;
}): Promise<number> {
const sessions = [
const sessions: {
cwd: string;
id: string;
title: string;
prompt: string;
answer?: string;
}[] = [
{
cwd: input.projectRoot,
id: input.importSessionId,
@@ -403,6 +534,7 @@ async function seedClaudeSessions(input: {
id: `fixture-root-${String(index + 1).padStart(2, "0")}`,
title: `Root session ${String(index + 1).padStart(2, "0")}`,
prompt: index === 7 ? "Investigate invoice rendering" : `Review fixture item ${index + 1}`,
...(index === 3 ? { answer: "Fixture response 4" } : {}),
})),
];
const newest = Date.now() - 60_000;
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 0);
await expectUserMessageCount(page, 1);
await expectComposerDraft(page, firstPrompt);
await expectComposerFocused(page);
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
await expectUserMessageVisible(page, replacementPrompt);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 2);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -254,19 +254,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, "");
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
const preservedDraft = "Keep this human draft after rewind.";
await fillComposerDraft(page, preservedDraft);
await composerLocator(page).evaluate((element) => element.blur());
await userMessage(page, replacementPrompt).hover();
await page.getByTestId("rewind-menu-trigger").last().click();
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
await selectRewindOption(page, "Rewind files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 2);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -277,7 +265,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, replacementPrompt);
await expectComposerFocused(page);
await expectUserMessageCount(page, 0);
await expectUserMessageCount(page, 1);
} finally {
await session.cleanup();
}
@@ -65,8 +65,7 @@ import {
openSettingsHostSection,
removeCurrentHostFromSettings,
openSidebarHostPicker,
sidebarHostSettingsButton,
expectStandaloneSidebarHostSettingsButton,
sidebarHostRowButton,
activateSidebarHostSettingsWithKeyboard,
bindCommandCenterToEnter,
} from "../support/helpers/settings";
@@ -192,17 +191,16 @@ test.describe("Settings sidebar scroll position", () => {
});
test.describe("Settings sidebar navigation", () => {
test("the sidebar host gear opens Overview in one click", async ({ page, withWorkspace }) => {
test("the sidebar host row opens Overview in one click", async ({ page, withWorkspace }) => {
const workspace = await withWorkspace({ prefix: "sidebar-host-settings-" });
await openWorkspace(page, workspace);
await openSidebarHostPicker(page);
await expectStandaloneSidebarHostSettingsButton(page);
await sidebarHostSettingsButton(page).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
});
test("Enter opens the focused sidebar host gear", async ({ page, withWorkspace }) => {
test("Enter opens the active sidebar host row", async ({ page, withWorkspace }) => {
await bindCommandCenterToEnter(page);
const workspace = await withWorkspace({ prefix: "keyboard-host-settings-" });
await openWorkspace(page, workspace);
@@ -566,7 +564,7 @@ test.describe("Settings — compact master-detail", () => {
await openWorkspace(page, workspace);
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await page.getByTestId("sidebar-hosts-trigger").click();
await page.getByRole("button", { name: /Open .* settings/ }).click();
await sidebarHostRowButton(page).click();
await expectAppRoute(page, buildSettingsHostSectionRoute(getServerId(), "host"));
await expect(page.getByText("Overview", { exact: true })).toBeVisible();
@@ -31,8 +31,6 @@ export interface RewindCompletionGate {
clearTimelineStreamCount(): void;
release(): void;
timelineStreamCount(): number;
/** Timeline reads this page sent since the last clear. */
timelineFetchCount(): number;
waitForDelayedResponse(): Promise<void>;
}
@@ -188,20 +186,12 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
};
}
// The rewind response and the timeline change it causes; the change removes the rewound row too.
const REWIND_COMPLETION_MESSAGES = new Set([
"agent.rewind.response",
"agent.timeline.rewind",
"agent.timeline.replacement",
]);
export async function holdRewindCompletion(
page: Page,
agentId: string,
): Promise<RewindCompletionGate> {
let released = false;
let timelineStreamCount = 0;
let timelineFetchCount = 0;
const delayedForwards: Array<() => void> = [];
let resolveDelayedResponse: (() => void) | null = null;
const delayedResponse = new Promise<void>((resolve) => {
@@ -210,16 +200,7 @@ export async function holdRewindCompletion(
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
if (
sessionMessage?.type === "fetch_agent_timeline_request" &&
sessionMessage.agentId === agentId
) {
timelineFetchCount += 1;
}
server.send(message);
});
ws.onMessage((message) => server.send(message));
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const payload = sessionMessage ? getPayload(sessionMessage) : null;
@@ -235,11 +216,11 @@ export async function holdRewindCompletion(
}
if (
!released &&
sessionMessage &&
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
(sessionMessage?.type === "agent.rewind.response" ||
sessionMessage?.type === "agent.timeline.replacement") &&
payload?.agentId === agentId
) {
// The rewind also signals completion and removes the rewound row/menu.
// The replacement also signals completion and removes the rewound row/menu.
// Hold it with the response so the pending-state assertion observes a pending rewind.
delayedForwards.push(() => ws.send(message));
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
@@ -252,7 +233,6 @@ export async function holdRewindCompletion(
return {
clearTimelineStreamCount() {
timelineStreamCount = 0;
timelineFetchCount = 0;
},
release() {
released = true;
@@ -261,7 +241,6 @@ export async function holdRewindCompletion(
}
},
timelineStreamCount: () => timelineStreamCount,
timelineFetchCount: () => timelineFetchCount,
waitForDelayedResponse: () => delayedResponse,
};
}
+10 -1
View File
@@ -132,7 +132,10 @@ export async function waitForConnectedHost(
): Promise<void> {
await page.getByTestId("sidebar-hosts-trigger").click();
const host = page.getByTestId(`sidebar-host-row-${input.serverId}`);
await expect(host).toContainText(input.endpoint, { timeout: 30_000 });
const escapedEndpoint = input.endpoint.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Local daemons render "Local" without repeating localhost:<port>; remote hosts render the endpoint.
await expect(host).toContainText(new RegExp(`${escapedEndpoint}|Local`), { timeout: 30_000 });
await expect(host).toContainText(/\d+(?:\.\d+)?(?:µs|ms|s)/, { timeout: 30_000 });
await page.keyboard.press("Escape");
await expect(host).not.toBeVisible();
}
@@ -195,6 +198,12 @@ export async function chooseHostColor(page: Page, colorName: string): Promise<vo
await expect(page.getByRole("button", { name: `Color, ${colorName}` })).toBeVisible();
}
export async function chooseHostIcon(page: Page, iconName: string): Promise<void> {
await page.getByTestId("host-appearance-icon").click();
await page.getByRole("menuitem", { name: iconName, exact: true }).click();
await expect(page.getByRole("button", { name: `Icon, ${iconName}` })).toBeVisible();
}
export async function chooseHostBadgeDisplay(
page: Page,
option: "Name" | "Icon only" | "Hidden",
@@ -137,13 +137,22 @@ export class ImportSessionFlow {
await this.expectProviderError(label);
await expect(this.page.getByRole("progressbar")).toHaveCount(0);
}
async importSession(id: string) {
async startImport(id: string) {
await this.revealSession(id);
await this.page.getByTestId(rowTestId(id)).click();
}
async importSession(id: string) {
await this.startImport(id);
await this.expectClosed();
}
async expectClosed() {
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0, {
timeout: 30_000,
});
}
async expectSessionUnavailable(id: string) {
await expect(this.page.getByTestId(rowTestId(id))).toHaveCount(0);
}
async expectTranscript(userText: string, assistantText: string) {
await expect(this.page.getByTestId("user-message").filter({ visible: true })).toContainText(
userText,
@@ -169,6 +178,13 @@ export class ImportSessionFlow {
await this.page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0);
}
async chooseHostForImport(hostLabel: string) {
const panel = await openCommandCenter(this.page);
await panel.getByTestId("command-center-input").fill("import");
await panel.getByText("Import session", { exact: true }).click();
await this.page.getByRole("dialog").getByRole("button", { name: hostLabel }).click();
await this.expectScope(`Sessions on ${hostLabel}`);
}
async expectCommandCenterMatch() {
const panel = await openCommandCenter(this.page);
await panel.getByTestId("command-center-input").fill("import");
+4 -14
View File
@@ -16,8 +16,8 @@ export async function openSidebarHostPicker(page: Page) {
await page.getByRole("button", { name: "Hosts", exact: true }).click();
}
export function sidebarHostSettingsButton(page: Page) {
return page.getByRole("button", { name: `Open ${TEST_HOST_LABEL} settings`, exact: true });
export function sidebarHostRowButton(page: Page) {
return page.getByTestId(`sidebar-host-row-${getServerId()}`);
}
export async function bindCommandCenterToEnter(page: Page) {
@@ -32,20 +32,10 @@ export async function bindCommandCenterToEnter(page: Page) {
});
}
export async function expectStandaloneSidebarHostSettingsButton(page: Page) {
const gear = sidebarHostSettingsButton(page);
await expect(gear).toBeVisible();
expect(await gear.evaluate((button) => button.parentElement?.closest("button") === null)).toBe(
true,
);
}
export async function activateSidebarHostSettingsWithKeyboard(page: Page) {
const host = page.getByRole("button", { name: TEST_HOST_LABEL, exact: true });
const host = sidebarHostRowButton(page);
await expect(host).toBeVisible();
await expect(host).toBeFocused();
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Tab");
await expect(sidebarHostSettingsButton(page)).toBeFocused();
await page.keyboard.press("Enter");
}
@@ -56,7 +56,6 @@ export function ChatFind({
agentId,
serverId,
epoch,
rewindSeq,
items,
viewportRef,
revealLoadedMessage,
@@ -96,8 +95,8 @@ export function ChatFind({
);
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
useEffect(() => {
model.updateHistory(epoch, items, rewindSeq);
}, [model, epoch, items, rewindSeq]);
model.updateHistory(epoch, items);
}, [model, epoch, items]);
useEffect(() => () => model.close(), [model]);
useEffect(() => {
if (!active) model.close();
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
kind: "assistant_message",
text,
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch", seq },
};
}
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
source.map((item, index) => ({
event: { type: "timeline" as const, provider: "claude" as const, item },
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
timelineCursor: { epoch: "epoch", seq: index + 1 },
})),
{ source: "canonical" },
);
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
},
async load(_epoch, seq) {
loaded.push(seq);
model.updateHistory("epoch", history, null);
model.updateHistory("epoch", history);
},
async reveal(_id, _query, occurrence) {
revealed.push(occurrence);
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
},
clear() {},
});
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => calls).toEqual(["search"]);
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
};
const model = new ChatFindModel(operations);
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -207,160 +207,24 @@ it("reports a search result that outlived its epoch as a changed history", async
clear() {},
});
try {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch-2", [message(1)], null);
model.updateHistory("epoch-2", [message(1)]);
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
} finally {
model.close();
}
});
it("reports results that a rewind took messages from as a changed history", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 2, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
// Another client rewinds the turn holding the match; the epoch stays.
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a search still receiving pages when a rewind lands between them", async () => {
let pages = 0;
let releaseSecondPage!: () => void;
const secondPage = new Promise<void>((resolve) => {
releaseSecondPage = resolve;
});
const model = new ChatFindModel({
async search(_query, cursor) {
pages += 1;
if (cursor === undefined)
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
await secondPage;
return response([{ seq: 1, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => pages).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
releaseSecondPage();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it.each([
["Next", "next"],
["Previous", "previous"],
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model[step]();
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a pending Next when a rewind lands before it reveals", async () => {
let reveals = 0;
let revealSecond!: () => void;
const secondReveal = new Promise<void>((resolve) => {
revealSecond = resolve;
});
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
reveals += 1;
if (reveals > 1) await secondReveal;
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.next();
await expect.poll(() => reveals).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
revealSecond();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it("can load a search location before the initial chat history has arrived", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 1, role: "assistant" }]);
},
async load() {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
},
async reveal() {
return { count: 1, occurrence: 0 };
@@ -368,7 +232,7 @@ it("can load a search location before the initial chat history has arrived", asy
clear() {},
});
try {
model.updateHistory(null, [], null);
model.updateHistory(null, []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -396,7 +260,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -433,7 +297,7 @@ it("counts one match per message from a host that reports no counts", async () =
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -76,10 +76,6 @@ export class ChatFindModel {
private items: StreamItem[] = [];
private epoch: string | null = null;
private resultEpoch: string | null = null;
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
private rewindSeq: number | null = null;
/** The latest rewind when the current result set's search started; undefined until a search starts. */
private searchedRewindSeq: number | null | undefined = undefined;
private locations: Location[] = [];
private resolved = new Map<Location, Target>();
private current = -1;
@@ -117,7 +113,6 @@ export class ChatFindModel {
this.cancel();
this.locations = [];
this.resultEpoch = null;
this.searchedRewindSeq = undefined;
this.resolved.clear();
this.current = -1;
this.inMessage = { occurrence: 0, count: 0 };
@@ -149,7 +144,6 @@ export class ChatFindModel {
});
}
private async search(signal: AbortSignal) {
this.searchedRewindSeq = this.rewindSeq;
try {
let cursor: number | undefined;
do {
@@ -174,14 +168,15 @@ export class ChatFindModel {
this.fail(error, signal);
}
}
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
if ((replaced || rewound) && this.state.open) {
updateHistory(epoch: string | null, items: StreamItem[]) {
if (
this.resultEpoch !== null &&
epoch !== null &&
epoch !== this.resultEpoch &&
this.state.open
) {
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
}
this.rewindSeq = rewindSeq;
this.epoch = epoch;
this.items = items;
this.historyListeners.forEach((listener) => listener());
@@ -9,8 +9,6 @@ export interface ChatFindProps {
agentId: string;
serverId: string;
epoch: string | null;
/** The sequence number of the latest rewind applied to this history, if any. */
rewindSeq: number | null;
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "live prompt",
timestamp: new Date(seq),
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch-1", seq },
});
rerender({ tail: [loadedPrompt(2)] });
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
kind: "assistant_message",
text: "chunk",
timestamp: new Date(),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
timelineEpoch: "epoch-1",
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "Replaced conversation",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-2", seq: 1 },
},
],
timelineEpoch: "epoch-2",
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
];
const { result, rerender } = renderHook(
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
};
const { result, rerender } = renderHook(
({ tail, mountedHistoryMessageIds }) =>
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
};
const revealLoadedMessage = vi.fn();
revealLoadedMessage.mockReturnValue(false);
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
const source = harness.source();
const live = source.head[0];
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
const present = createStreamPresentation();
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
const repointed = rows(
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
{
id: streamed[0]!.id,
text: "Streamed answer",
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42 },
},
]);
});
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
messageId: "provider-message",
clientMessageId: "client-message",
turnId: "turn-1",
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch", seq: 12 },
});
const presentMessage = () =>
present({
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
const failedTurn = {
...assistantMessage("assistant-error", 2),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("includes the provider message id with a supported timeline cursor", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("falls back to the provider message id when timeline cursors are unsupported", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -1,13 +1,7 @@
import type { StreamItem } from "@/types/stream";
/** The daemon's timeline cursor; the row's anchor stays in the client. */
interface TimelineBoundaryCursor {
epoch: string;
seq: number;
}
import type { StreamItem, TimelinePosition } from "@/types/stream";
export type AssistantTurnForkBoundary =
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
| { boundaryCursor?: undefined; boundaryMessageId: string };
export function resolveAssistantTurnForkBoundary(input: {
@@ -21,7 +15,7 @@ export function resolveAssistantTurnForkBoundary(input: {
}
if (input.supportsTimelineCursor && item.timelineCursor) {
return {
boundaryCursor: { epoch: item.timelineCursor.epoch, seq: item.timelineCursor.seq },
boundaryCursor: item.timelineCursor,
...(item.messageId ? { boundaryMessageId: item.messageId } : {}),
};
}
@@ -140,7 +140,7 @@ describe("collapseTurns", () => {
it("stands at its host's timeline position, taking a new row when that position lands", () => {
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
const cursor = { epoch: "epoch-1", seq: 7 };
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
-5
View File
@@ -408,10 +408,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const timelineEpoch = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
);
const timelineRewindSeq = useSessionStore((state) => {
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
});
const isTimelineDetached = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
);
@@ -1170,7 +1166,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
agentId={agentId}
serverId={resolvedServerId}
epoch={timelineEpoch}
rewindSeq={timelineRewindSeq}
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedMessage}
@@ -7,7 +7,6 @@ import { FOOTER_HEIGHT } from "@/constants/layout";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { KeyboardTranslateView } from "@/keyboard/shift";
import { Button } from "@/components/ui/button";
import { useToast } from "@/contexts/toast-context";
import type { Theme } from "@/styles/theme";
import { toErrorMessage } from "@/utils/error-messages";
@@ -20,7 +19,6 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
const toast = useToast();
const [isUnarchiving, setIsUnarchiving] = useState(false);
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
@@ -29,15 +27,12 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
setIsUnarchiving(true);
setUnarchiveError(null);
try {
const refreshed = await client.refreshAgent(agentId);
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), { variant: "warning" });
}
await client.refreshAgent(agentId);
} catch (error) {
setUnarchiveError(toErrorMessage(error));
setIsUnarchiving(false);
}
}, [client, isConnected, isUnarchiving, agentId, toast, t]);
}, [client, isConnected, isUnarchiving, agentId]);
return (
<KeyboardTranslateView style={styles.container}>
+304 -136
View File
@@ -1,11 +1,28 @@
import { useCallback, useMemo, type ReactElement, type ReactNode } from "react";
import { Pressable, View } from "react-native";
import { Plus, Server, Settings } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
useCallback,
useEffect,
useMemo,
useState,
type ReactElement,
type ReactNode,
} from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Check, Plus, Server } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HostStatusDot } from "@/components/host-status-dot";
import { Combobox, ComboboxItem, type ComboboxProps } from "@/components/ui/combobox";
import { Combobox, type ComboboxProps } from "@/components/ui/combobox";
import { PressHighlight } from "@/components/ui/press-highlight";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, type ActiveConnection } from "@/runtime/host-runtime";
import { defaultHostAppearance, resolveHostIcon, type HostAppearance } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import {
getHostRuntimeStore,
useHostRuntimeConnectionStatus,
useHosts,
} from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { orderHostsLocalFirst } from "@/types/host-connection";
import {
ADD_HOST_OPTION_ID,
@@ -22,7 +39,16 @@ export {
};
const SEARCHABLE_THRESHOLD = 10;
const DEFAULT_DESKTOP_MIN_WIDTH = 328;
const LEADING_RAIL_SIZE = 16;
const HOST_ROW_ICON_SIZE = 14;
type RenderHostOption = NonNullable<ComboboxProps["renderOption"]>;
const ThemedCheck = withUnistyles(Check);
const ThemedPlus = withUnistyles(Plus);
const ThemedServer = withUnistyles(Server);
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
export interface HostPickerHost {
serverId: string;
label: string;
@@ -36,122 +62,166 @@ export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElem
);
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
// Socket/pipe transports have no host:port — their endpoint is a filesystem
// path, so they read as "Local". TCP and relay show the address being used.
function formatActiveConnectionLabel(connection: ActiveConnection): string {
if (connection.type === "directSocket" || connection.type === "directPipe") {
return "Local";
}
return formatConnectionEndpoint(connection.endpoint);
}
export interface HostPickerOptionProps {
serverId: string;
label: string;
showActiveConnection: boolean;
appearance: HostAppearance;
selected?: boolean;
active: boolean;
onPress: () => void;
onOpenHostSettings?: (serverId: string) => void;
testID?: string;
}
export function HostPickerOption({
serverId,
label,
showActiveConnection,
appearance,
selected,
active,
onPress,
onOpenHostSettings,
testID,
}: HostPickerOptionProps): ReactElement {
const { theme } = useUnistyles();
const activeConnection = useHostRuntimeSnapshot(serverId)?.activeConnection ?? null;
const connectionLabel =
showActiveConnection && activeConnection
? formatActiveConnectionLabel(activeConnection)
: undefined;
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
const handleSettingsPress = useCallback(() => {
onOpenHostSettings?.(serverId);
}, [onOpenHostSettings, serverId]);
const trailingAction = useMemo(() => {
if (!onOpenHostSettings) return undefined;
return (
<Pressable
onPress={handleSettingsPress}
style={styles.settingsAction}
accessibilityRole="button"
accessibilityLabel={`Open ${label} settings`}
>
<Settings size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
);
}, [
handleSettingsPress,
label,
onOpenHostSettings,
theme.colors.foregroundMuted,
theme.iconSize.sm,
]);
const status = useHostRuntimeConnectionStatus(serverId);
const detectedMachineKind = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const isOffline = status === "offline" || status === "error";
return (
<ComboboxItem
label={label}
description={connectionLabel}
leadingSlot={leadingSlot}
trailingAction={trailingAction}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.hostRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<HostStatusDot serverId={serverId} />
</View>
<View style={styles.hostBody}>
<View style={styles.hostHeaderRow}>
<HostIconGlyph
icon={resolvedIcon}
color={appearance.color}
size={HOST_ROW_ICON_SIZE}
style={styles.hostGlyph}
/>
<Text style={[styles.hostName, isOffline && styles.hostNameMuted]} numberOfLines={1}>
{label}
</Text>
</View>
<HostConnectionLine serverId={serverId} />
</View>
<View style={styles.hostTrailing}>
<HostLatencyLabel serverId={serverId} />
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</View>
</PressHighlight>
</View>
);
}
const SYSTEM_HOST_PICKER_OPTION_LABELS: Record<"add" | "all" | "enableBuiltInDaemon", string> = {
add: "Add host",
all: "All hosts",
enableBuiltInDaemon: "Enable built-in daemon",
};
function SystemHostPickerOption({
function AllHostsOption({
active,
selected,
onPress,
kind,
testID,
}: {
active: boolean;
selected?: boolean;
onPress: () => void;
kind: "add" | "all" | "enableBuiltInDaemon";
testID?: string;
}): ReactElement {
const { theme } = useUnistyles();
const Icon = kind === "add" ? Plus : Server;
const label = SYSTEM_HOST_PICKER_OPTION_LABELS[kind];
const leadingSlot = useMemo(
() => <Icon size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />,
[Icon, theme.colors.foregroundMuted, theme.iconSize.sm],
);
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = t("sidebar.display.hostFilter.all");
return (
<ComboboxItem
label={label}
leadingSlot={leadingSlot}
selected={selected}
active={active}
onPress={onPress}
testID={testID}
/>
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
{selected ? <ThemedCheck size={ICON_SIZE.sm} uniProps={mutedIconMapping} /> : null}
</PressHighlight>
</View>
);
}
function ActionOptionRow({
kind,
active,
showDivider,
onPress,
testID,
}: {
kind: "add" | "enableBuiltInDaemon";
active: boolean;
showDivider: boolean;
onPress: () => void;
testID?: string;
}): ReactElement {
const { t } = useTranslation();
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const label = kind === "add" ? t("settings.addHost") : t("settings.enableBuiltInDaemon");
return (
<View>
{showDivider ? <View style={styles.actionSectionDivider} /> : null}
<View
style={styles.rowEnvelope}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<PressHighlight
testID={testID}
onPress={onPress}
highlightStyle={styles.rowHighlighted}
style={[styles.actionRow, (hovered || active) && styles.rowHighlighted]}
accessibilityRole="button"
accessibilityLabel={label}
>
<View style={styles.leadingRailSlot}>
{kind === "add" ? (
<ThemedPlus size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
) : (
<ThemedServer size={LEADING_RAIL_SIZE} uniProps={mutedIconMapping} />
)}
</View>
<Text style={styles.actionLabel} numberOfLines={1}>
{label}
</Text>
</PressHighlight>
</View>
</View>
);
}
@@ -168,7 +238,6 @@ export interface HostPickerProps {
includeEnableBuiltInDaemon?: boolean;
onEnableBuiltInDaemon?: () => void;
showActiveConnection?: boolean;
onOpenHostSettings?: (serverId: string) => void;
searchable?: boolean;
title?: string;
desktopPlacement?: ComboboxProps["desktopPlacement"];
@@ -190,74 +259,85 @@ export function HostPicker({
onAddHost,
includeEnableBuiltInDaemon,
onEnableBuiltInDaemon,
showActiveConnection,
onOpenHostSettings,
searchable,
title,
desktopPlacement = "bottom-start",
desktopMinWidth,
desktopMinWidth = DEFAULT_DESKTOP_MIN_WIDTH,
addHostTestID,
hostOptionTestID,
children,
}: HostPickerProps): ReactElement {
const { t } = useTranslation();
const localServerId = useLocalDaemonServerId();
const allHostProfiles = useHosts();
const orderedHosts = useMemo(
() => orderHostsLocalFirst(hosts, localServerId),
[hosts, localServerId],
);
const appearanceByServerId = useMemo(() => {
const map = new Map<string, HostAppearance>();
for (const profile of allHostProfiles) {
map.set(profile.serverId, profile.appearance);
}
return map;
}, [allHostProfiles]);
useEffect(() => {
if (!open) return;
getHostRuntimeStore().refreshActiveLatencies(orderedHosts.map((host) => host.serverId));
}, [open, orderedHosts]);
const options = useMemo(() => {
const hostOptions = orderedHosts.map((host) => ({ id: host.serverId, label: host.label }));
if (includeAllHost) hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: "All hosts" });
if (includeAddHost) hostOptions.push({ id: ADD_HOST_OPTION_ID, label: "Add host" });
if (includeEnableBuiltInDaemon)
if (includeAllHost) {
hostOptions.unshift({ id: ALL_HOSTS_OPTION_ID, label: t("sidebar.display.hostFilter.all") });
}
if (includeAddHost) {
hostOptions.push({ id: ADD_HOST_OPTION_ID, label: t("settings.addHost") });
}
if (includeEnableBuiltInDaemon) {
hostOptions.push({
id: ENABLE_BUILT_IN_DAEMON_OPTION_ID,
label: "Enable built-in daemon",
label: t("settings.enableBuiltInDaemon"),
});
}
return hostOptions;
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon]);
}, [orderedHosts, includeAllHost, includeAddHost, includeEnableBuiltInDaemon, t]);
let firstActionOptionId: string | null = null;
if (includeAddHost) {
firstActionOptionId = ADD_HOST_OPTION_ID;
} else if (includeEnableBuiltInDaemon) {
firstActionOptionId = ENABLE_BUILT_IN_DAEMON_OPTION_ID;
}
const isSearchable = searchable === true && orderedHosts.length > SEARCHABLE_THRESHOLD;
const resolvedTitle = title ?? t("sidebar.actions.hosts");
const handleSelect = useCallback(
(id: string) => {
if (id === ADD_HOST_OPTION_ID) {
onOpenChange(false);
onAddHost?.();
} else if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onEnableBuiltInDaemon?.();
} else {
onSelect(id);
return;
}
if (id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
onOpenChange(false);
onEnableBuiltInDaemon?.();
return;
}
onSelect(id);
onOpenChange(false);
},
[onAddHost, onEnableBuiltInDaemon, onOpenChange, onSelect],
);
const handleOpenHostSettings = useCallback(
(serverId: string) => {
onOpenHostSettings?.(serverId);
onOpenChange(false);
},
[onOpenHostSettings, onOpenChange],
);
const renderOption = useCallback<RenderHostOption>(
({ option, selected, active, onPress }) => {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption
kind="add"
active={active}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ALL_HOSTS_OPTION_ID) {
return (
<SystemHostPickerOption
kind="all"
<AllHostsOption
active={active}
selected={selected}
onPress={onPress}
@@ -265,30 +345,48 @@ export function HostPicker({
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
if (option.id === ADD_HOST_OPTION_ID) {
return (
<SystemHostPickerOption kind="enableBuiltInDaemon" active={active} onPress={onPress} />
<ActionOptionRow
kind="add"
active={active}
showDivider={firstActionOptionId === ADD_HOST_OPTION_ID && orderedHosts.length > 0}
onPress={onPress}
testID={addHostTestID}
/>
);
}
if (option.id === ENABLE_BUILT_IN_DAEMON_OPTION_ID) {
return (
<ActionOptionRow
kind="enableBuiltInDaemon"
active={active}
showDivider={
firstActionOptionId === ENABLE_BUILT_IN_DAEMON_OPTION_ID && orderedHosts.length > 0
}
onPress={onPress}
/>
);
}
const appearance = appearanceByServerId.get(option.id) ?? defaultHostAppearance();
return (
<HostPickerOption
serverId={option.id}
label={option.label}
showActiveConnection={showActiveConnection === true}
appearance={appearance}
selected={selected}
active={active}
onPress={onPress}
onOpenHostSettings={onOpenHostSettings ? handleOpenHostSettings : undefined}
testID={hostOptionTestID?.(option.id)}
/>
);
},
[
addHostTestID,
appearanceByServerId,
firstActionOptionId,
hostOptionTestID,
onOpenHostSettings,
showActiveConnection,
handleOpenHostSettings,
orderedHosts.length,
],
);
@@ -301,8 +399,8 @@ export function HostPicker({
onSelect={handleSelect}
renderOption={renderOption}
searchable={isSearchable}
searchPlaceholder="Search hosts"
title={title ?? "Host"}
searchPlaceholder={t("sidebar.host.searchPlaceholder")}
title={resolvedTitle}
open={open}
onOpenChange={onOpenChange}
anchorRef={anchorRef}
@@ -314,16 +412,86 @@ export function HostPicker({
}
const styles = StyleSheet.create((theme) => ({
settingsAction: {
flex: 1,
justifyContent: "center",
paddingLeft: theme.spacing[1],
paddingRight: theme.spacing[3],
},
statusDotSlot: {
width: theme.iconSize.sm,
height: theme.iconSize.sm,
alignItems: "center",
justifyContent: "center",
},
rowEnvelope: {
position: "relative",
},
// Shared leading rail: the status dot on host rows and the '+' / All hosts glyph share one
// centered 16px column aligned to the first line's 18px line-height.
leadingRailSlot: {
width: LEADING_RAIL_SIZE,
height: 18,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
hostRow: {
flexDirection: "row",
alignItems: "flex-start",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
rowHighlighted: {
backgroundColor: theme.colors.surface1,
},
hostBody: {
flex: 1,
minWidth: 0,
gap: 2,
},
hostHeaderRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
hostGlyph: {
flexShrink: 0,
},
hostName: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
hostNameMuted: {
color: theme.colors.foregroundMuted,
},
hostTrailing: {
flexDirection: "row",
alignItems: "center",
height: 18,
gap: theme.spacing[2],
flexShrink: 0,
},
actionSectionDivider: {
height: theme.borderWidth[1],
backgroundColor: theme.colors.border,
marginVertical: theme.spacing[1],
},
actionRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
marginHorizontal: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
},
actionLabel: {
flex: 1,
minWidth: 0,
fontSize: theme.fontSize.base,
lineHeight: 18,
color: theme.colors.foreground,
},
}));
@@ -0,0 +1,32 @@
import Svg, { Circle } from "react-native-svg";
const TAILSCALE_DOTS = [3, 12, 21].flatMap((cy, row) =>
[3, 12, 21].map((cx, column) => ({
cx,
cy,
// The Tailscale mark is a 3x3 dot grid with a solid T (middle row + bottom center).
solid: row === 1 || (row === 2 && column === 1),
})),
);
export interface TailscaleIconProps {
size?: number;
color?: string;
}
export function TailscaleIcon({ size = 12, color = "currentColor" }: TailscaleIconProps) {
return (
<Svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
{TAILSCALE_DOTS.map((dot) => (
<Circle
key={`${dot.cx}:${dot.cy}`}
cx={dot.cx}
cy={dot.cy}
r={3}
fill={color}
opacity={dot.solid ? 1 : 0.3}
/>
))}
</Svg>
);
}
@@ -184,7 +184,9 @@ describe("collectProviderErrorRows", () => {
[settled(undefined, { isError: true }), settled({ entries: [] })],
new Map([["claude", "Claude Code"]]),
);
expect(rows).toEqual([{ provider: "claude", label: "Claude Code" }]);
expect(rows).toEqual([
{ provider: "claude", label: "Claude Code", message: null, retrying: false },
]);
});
it("returns a row for a provider the daemon reported as failed in a good response", () => {
@@ -198,7 +200,9 @@ describe("collectProviderErrorRows", () => {
],
new Map([["codex", "Codex"]]),
);
expect(rows).toEqual([{ provider: "codex", label: "Codex" }]);
expect(rows).toEqual([
{ provider: "codex", label: "Codex", message: "timed out", retrying: false },
]);
});
it("uses provider id when the label map has no entry", () => {
@@ -207,7 +211,43 @@ describe("collectProviderErrorRows", () => {
[settled(undefined, { isError: true })],
new Map(),
);
expect(rows).toEqual([{ provider: "codex", label: "codex" }]);
expect(rows).toEqual([{ provider: "codex", label: "codex", message: null, retrying: false }]);
});
it("shows the current request failure instead of an older provider error", () => {
const query = {
...settled(
{ entries: [], providerErrors: [{ provider: "codex", message: "old provider failure" }] },
{ isError: true },
),
error: new Error(" Connection closed. Reconnect the host and retry. "),
};
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
{
provider: "codex",
label: "codex",
message: "Connection closed. Reconnect the host and retry.",
retrying: false,
},
]);
});
it("keeps the provider failure visible while its retry is in flight", () => {
const query = {
...settled({
entries: [],
providerErrors: [{ provider: "codex", message: "Run codex login and retry." }],
}),
isFetching: true,
};
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
{
provider: "codex",
label: "codex",
message: "Run codex login and retry.",
retrying: true,
},
]);
});
});
@@ -39,6 +39,8 @@ export interface SessionsQueryResult {
}
| undefined;
isError: boolean;
error?: Error | null;
isFetching?: boolean;
isLoading: boolean;
isPending: boolean;
isPlaceholderData?: boolean;
@@ -120,6 +122,8 @@ export function hasMoreSessions(
export interface ProviderErrorRow {
provider: string;
label: string;
message: string | null;
retrying: boolean;
}
/**
@@ -140,7 +144,15 @@ export function collectProviderErrorRows(
if (!query || provider === undefined) continue;
const failed = query.isError || (query.data?.providerErrors?.length ?? 0) > 0;
if (!failed) continue;
rows.push({ provider, label: providerLabelById.get(provider) ?? provider });
const failure = query.data?.providerErrors?.find((error) => error.provider === provider);
const failureMessage = query.isError ? query.error?.message : failure?.message;
const message = failureMessage?.trim() || null;
rows.push({
provider,
label: providerLabelById.get(provider) ?? provider,
message,
retrying: query.isFetching === true,
});
}
return rows;
}
@@ -79,15 +79,19 @@ type RecentSessionsResponse = Awaited<
type SessionsQueryKey = ReadonlyArray<string | number | null>;
function buildSessionsQueryRoot(serverId: string | null, cwd: string | null) {
return ["recent-provider-sessions", serverId, cwd] as const;
}
function buildSessionsQueryKey(input: {
serverId: string | null;
cwd: string | null;
query: string;
limit: number;
provider?: string;
}): SessionsQueryKey {
return [
"recent-provider-sessions",
input.cwd,
...buildSessionsQueryRoot(input.serverId, input.cwd),
input.query,
input.limit,
...(input.provider === undefined ? [] : [input.provider]),
@@ -101,6 +105,7 @@ interface SessionsQueryConfig {
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
refetchOnMount: true;
placeholderData: () => RecentSessionsResponse | undefined;
queryFn: () => Promise<RecentSessionsResponse>;
}
@@ -110,20 +115,23 @@ function buildSessionsQueriesConfig(args: {
providersToFetch: AgentProvider[] | null;
visible: boolean;
client: RecentProviderSessionsClient | null;
serverId: string | null;
cwd: string | null;
query: string;
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { queryClient, providersToFetch, visible, client, cwd, query, limit } = args;
const { queryClient, providersToFetch, visible, client, serverId, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
queryKey: buildSessionsQueryKey({ serverId, cwd, query, limit, provider }),
enabled,
retry: false as const,
// An import can invalidate an inactive host. Refresh its listing when observed again.
refetchOnMount: true as const,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
@@ -131,7 +139,7 @@ function buildSessionsQueriesConfig(args: {
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ cwd, query, limit: previousLimit, provider }),
buildSessionsQueryKey({ serverId, cwd, query, limit: previousLimit, provider }),
),
queryFn: async () => {
if (!client) {
@@ -217,13 +225,21 @@ function ProviderErrorBannerRow({
const handleRetry = useCallback(() => onRetry(row.provider), [onRetry, row.provider]);
return (
<View style={styles.errorRow}>
<Text style={styles.errorText}>
{t("importSession.status.failedProvider", { provider: row.label })}
</Text>
<View style={styles.errorContent}>
<Text style={styles.errorText}>
{t("importSession.status.failedProvider", { provider: row.label })}
</Text>
{row.message ? (
<Text style={styles.errorDetail} selectable>
{row.message}
</Text>
) : null}
</View>
<Button
variant="ghost"
size="sm"
onPress={handleRetry}
loading={row.retrying}
testID={`import-session-retry-${row.provider}`}
>
{t("common.actions.retry")}
@@ -529,7 +545,10 @@ export function ImportSessionSheet({
[snapshotEntries],
);
const sessionsQueryRoot = useMemo(() => ["recent-provider-sessions", scopeCwd], [scopeCwd]);
const sessionsQueryRoot = useMemo(
() => buildSessionsQueryRoot(serverId, scopeCwd),
[serverId, scopeCwd],
);
const queriesConfig = useMemo(
() =>
@@ -538,12 +557,13 @@ export function ImportSessionSheet({
providersToFetch,
visible,
client,
serverId,
cwd: scopeCwd,
query,
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[queryClient, providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
[queryClient, providersToFetch, visible, client, serverId, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
@@ -682,19 +702,17 @@ export function ImportSessionSheet({
cwd: entry.cwd,
...(target.workspaceId ? { workspaceId: target.workspaceId } : {}),
});
return { agent, target };
},
onSuccess: ({ agent, target }) => {
// A pending import keeps the listing and navigation from the host it was sent to.
void queryClient.invalidateQueries({
queryKey: sessionsQueryRoot,
refetchType: "none",
});
onClose();
if (target.crossWorkspace) {
onImported?.(agent);
} else {
onImportedAgent?.(agent.id);
}
void queryClient.invalidateQueries({
queryKey: sessionsQueryRoot,
refetchType: "none",
});
},
});
@@ -725,10 +743,16 @@ export function ImportSessionSheet({
const handleRetryProvider = useCallback(
(provider: string) => {
void queryClient.refetchQueries({
queryKey: buildSessionsQueryKey({ cwd: scopeCwd, query, limit: pageLimit, provider }),
queryKey: buildSessionsQueryKey({
serverId,
cwd: scopeCwd,
query,
limit: pageLimit,
provider,
}),
});
},
[pageLimit, query, queryClient, scopeCwd],
[pageLimit, query, queryClient, scopeCwd, serverId],
);
const handleShowAll = useCallback(() => setIsShowingAllDirectories(true), []);
@@ -1071,6 +1095,12 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[2],
paddingVertical: theme.spacing[1],
},
errorContent: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
errorText: {
flexShrink: 1,
@@ -1078,6 +1108,10 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.palette.red[300],
fontSize: theme.fontSize.sm,
},
errorDetail: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
emptyState: {
alignItems: "center",
justifyContent: "center",
+2 -2
View File
@@ -388,10 +388,10 @@ function SidebarHostPicker({
includeAddHost
onAddHost={onAddHost}
showActiveConnection
onOpenHostSettings={onOpenHostSettings}
searchable
title={label}
desktopPlacement="top-start"
desktopMinWidth={240}
desktopMinWidth={328}
addHostTestID="sidebar-host-add"
hostOptionTestID={sidebarHostOptionTestID}
>
@@ -9,7 +9,6 @@ import { useRewindComposerRestore } from "./composer-restore";
import { useSessionStore } from "@/stores/session-store";
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { hostSupportsFeature } from "@/runtime/host-features";
interface UseRewindAgentMutationInput {
serverId?: string;
@@ -43,16 +42,7 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
await input.client.rewindAgent(input.agentId, input.messageId, mode);
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10. A daemon with
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
// and this client has to read it again.
const appliesLive =
input.serverId !== undefined &&
hostSupportsFeature(
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
"timelineRewindOperations",
);
if (mode !== "files" && !appliesLive) {
if (mode !== "files") {
const cursor = input.serverId
? useSessionStore
.getState()
+60 -14
View File
@@ -73,6 +73,9 @@ export { buildDesktopFrameStyle } from "./combobox-frame-style";
const IS_WEB = isWeb;
const TRAILING_ACTION_DATASET = { comboboxTrailingAction: true };
const FOOTER_DATASET = { comboboxFooter: true };
const FOCUSED_COMBOBOX_ACTION_SELECTOR =
'[data-combobox-trailing-action] button, [data-combobox-trailing-action] [role="button"], [data-combobox-footer] button, [data-combobox-footer] [role="button"]';
export type ComboboxOption = ComboboxOptionModel;
export type ComboboxDesktopPlacement = "top-start" | "bottom-start";
@@ -402,6 +405,7 @@ export function ComboboxEmpty({ children }: { children: ReactNode }): ReactEleme
type RenderOptionFn = NonNullable<ComboboxProps["renderOption"]>;
interface OptionRowProps {
index: number;
option: ComboboxOption;
selected: boolean;
active: boolean;
@@ -409,20 +413,27 @@ interface OptionRowProps {
renderOption: RenderOptionFn | undefined;
}
function OptionRow({ option, selected, active, onSelect, renderOption }: OptionRowProps) {
function OptionRow({ index, option, selected, active, onSelect, renderOption }: OptionRowProps) {
const handlePress = useCallback(() => onSelect(option.id), [onSelect, option.id]);
const optionDataset = useMemo(() => ({ comboboxOptionIndex: String(index) }), [index]);
if (renderOption) {
return <View>{renderOption({ option, selected, active, onPress: handlePress })}</View>;
return (
<View dataSet={optionDataset}>
{renderOption({ option, selected, active, onPress: handlePress })}
</View>
);
}
return (
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
<View dataSet={optionDataset}>
<ComboboxItem
label={option.label}
description={option.description}
kind={option.kind}
selected={selected}
active={active}
onPress={handlePress}
/>
</View>
);
}
@@ -451,6 +462,7 @@ function OptionsList({
{options.map((opt, index) => (
<OptionRow
key={opt.id}
index={index}
option={opt}
selected={opt.id === value}
active={index === activeIndex}
@@ -952,8 +964,9 @@ function dispatchDesktopKey(
return true;
}
if (key === "Enter") {
// Consume the shortcut but keep the browser's default button activation.
if (isWeb && document.activeElement?.matches("[data-combobox-trailing-action] button")) {
// Consume the shortcut but keep the browser's default button activation when the user moved
// keyboard focus onto a trailing action or footer button inside the combobox.
if (isWeb && document.activeElement?.matches(FOCUSED_COMBOBOX_ACTION_SELECTOR)) {
return true;
}
if (input.orderedVisibleOptions.length === 0) return false;
@@ -1127,7 +1140,12 @@ function ComboboxSheetFrame({ footer, children }: { footer?: ReactNode; children
[safeAreaBottom],
);
const footerView = useMemo(
() => (footer ? <View style={footerStyle}>{footer}</View> : undefined),
() =>
footer ? (
<View style={footerStyle} dataSet={FOOTER_DATASET}>
{footer}
</View>
) : undefined,
[footer, footerStyle],
);
return (
@@ -1341,7 +1359,11 @@ function DesktopComboboxBody(props: DesktopBodyProps): ReactElement | null {
renderOption={props.renderOption}
/>
)}
{props.footer ? <View style={styles.footer}>{props.footer}</View> : null}
{props.footer ? (
<View style={styles.footer} dataSet={FOOTER_DATASET}>
{props.footer}
</View>
) : null}
</FloatingSurface>
</View>
</OverlayLayerProvider>
@@ -1597,6 +1619,30 @@ export function Combobox({
setActiveIndex,
);
// Keep activeIndex aligned when a keyboard user Tabs onto a specific option button on web.
useEffect(() => {
if (!IS_WEB || !isOpen || isMobile) return;
const handleFocusIn = (event: FocusEvent) => {
const target = event.target;
if (!(target instanceof Element)) return;
const optionEl = target.closest("[data-combobox-option-index]");
if (!optionEl) return;
const nextIndex = Number.parseInt(
optionEl.getAttribute("data-combobox-option-index") ?? "",
10,
);
if (
Number.isInteger(nextIndex) &&
nextIndex >= 0 &&
nextIndex < orderedVisibleOptions.length
) {
setActiveIndex(nextIndex);
}
};
document.addEventListener("focusin", handleFocusIn);
return () => document.removeEventListener("focusin", handleFocusIn);
}, [isMobile, isOpen, orderedVisibleOptions.length]);
const handleSelect = useCallback(
(id: string) => {
onSelect(id);
@@ -385,16 +385,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
console.warn("[Session] timeline replacement refresh failed", { serverId, error });
});
};
const onRewind = (message: SessionOutboundMessage) => {
if (message.type !== "agent.timeline.rewind") return;
const { agentId, epoch, seq, retireFromSeq } = message.payload;
sync.applyStreamEvent(agentId, {
event: { type: "rewind", retireFromSeq },
seq,
epoch,
timestamp: new Date(),
});
};
const sync = getHostRuntimeStore().createViewedTimelineOwner(serverId, {
canCheckFreshness: () =>
client.getLastServerInfoMessage()?.features?.timelineFreshnessCheck === true,
@@ -405,7 +395,6 @@ function SessionProviderInternal({ children, serverId, client }: SessionProvider
update: (message) => {
if (message.type === "agent_stream") onStream(message);
else if (message.type === "agent.timeline.replacement") onReplacement(message);
else if (message.type === "agent.timeline.rewind") onRewind(message);
},
});
return observation;
@@ -166,7 +166,7 @@ describe("ensureAgentIsInitialized", () => {
kind: "assistant_message",
id: "canonical-item",
text: "Canonical before restart",
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
timestamp: new Date("2026-07-27T10:00:00.000Z"),
},
],
+94 -8
View File
@@ -4,6 +4,7 @@ import {
defaultHostAppearance,
normalizeStoredHostAppearance,
resolveHostBadgeDisplay,
resolveHostIcon,
selectHostBadges,
} from "@/hosts/appearance";
@@ -16,7 +17,7 @@ function host(
}
describe("normalizeStoredHostAppearance", () => {
it("defaults when the stored registry predates the field or holds junk", () => {
it("defaults without writing an icon field so untouched records stay downgrade-safe", () => {
const expected = { color: "none", badgeDisplay: null };
expect(normalizeStoredHostAppearance(undefined)).toEqual(expected);
expect(normalizeStoredHostAppearance(null)).toEqual(expected);
@@ -24,13 +25,79 @@ describe("normalizeStoredHostAppearance", () => {
expect(normalizeStoredHostAppearance({})).toEqual(expected);
expect(normalizeStoredHostAppearance({ color: "chartreuse" })).toEqual(expected);
expect(normalizeStoredHostAppearance({ badgeDisplay: "loud" })).toEqual(expected);
expect("icon" in defaultHostAppearance()).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" })).toEqual({
it("preserves an unknown stored icon on disk while falling back at render time", () => {
const normalized = normalizeStoredHostAppearance({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(normalized).toEqual({
color: "teal",
icon: "spaceship",
badgeDisplay: "icon",
});
expect(resolveHostIcon({ appearance: normalized })).toBe("server");
expect(resolveHostIcon({ appearance: normalized, detectedMachineKind: "laptop" })).toBe(
"laptop",
);
});
it("keeps icon absent on stored entries that predate host icons", () => {
const normalized = normalizeStoredHostAppearance({ color: "teal", badgeDisplay: "icon" });
expect(normalized).toEqual({
color: "teal",
badgeDisplay: "icon",
});
expect("icon" in normalized).toBe(false);
});
it("round-trips a value the user actually chose", () => {
expect(
normalizeStoredHostAppearance({ color: "teal", icon: "laptop", badgeDisplay: "icon" }),
).toEqual({
color: "teal",
icon: "laptop",
badgeDisplay: "icon",
});
});
});
describe("resolveHostIcon", () => {
it("prefers an explicit user icon over daemon auto-detection", () => {
expect(
resolveHostIcon({
appearance: { color: "none", icon: "workstation", badgeDisplay: null },
detectedMachineKind: "laptop",
}),
).toBe("workstation");
});
it("uses the daemon-detected machine kind while the user icon is auto (null)", () => {
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "laptop",
}),
).toBe("laptop");
expect(
resolveHostIcon({
appearance: defaultHostAppearance(),
detectedMachineKind: "container",
}),
).toBe("container");
});
it("falls back to server when the detected machine kind is absent or unknown", () => {
expect(resolveHostIcon({ appearance: defaultHostAppearance() })).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: null }),
).toBe("server");
expect(
resolveHostIcon({ appearance: defaultHostAppearance(), detectedMachineKind: "future-kind" }),
).toBe("server");
});
});
@@ -50,13 +117,13 @@ describe("resolveHostBadgeDisplay", () => {
it("prefers an explicit choice over either default", () => {
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "icon" },
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
isLocalHost: true,
}),
).toBe("icon");
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "hidden" },
appearance: { color: "none", icon: "server", badgeDisplay: "hidden" },
isLocalHost: false,
}),
).toBe("hidden");
@@ -72,7 +139,7 @@ describe("resolveHostBadgeDisplay", () => {
).toBeNull();
expect(
resolveHostBadgeDisplay({
appearance: { color: "none", badgeDisplay: "icon" },
appearance: { color: "none", icon: "server", badgeDisplay: "icon" },
isLocalHost: false,
localHostResolutionPending: true,
}),
@@ -93,7 +160,7 @@ describe("selectHostBadges", () => {
it("omits a host the user hid and keeps its sibling", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha", { color: "none", badgeDisplay: "hidden" }),
host("alpha", "Alpha", { color: "none", icon: "server", badgeDisplay: "hidden" }),
host("beta", "Beta"),
],
localServerId: null,
@@ -104,13 +171,14 @@ describe("selectHostBadges", () => {
serverId: "beta",
label: "Beta",
color: "none",
icon: "server",
showLabel: true,
});
});
it("keeps an icon-only host in the map without its label", () => {
const badges = selectHostBadges({
hosts: [host("alpha", "Alpha", { color: "teal", badgeDisplay: "icon" })],
hosts: [host("alpha", "Alpha", { color: "teal", icon: "mini", badgeDisplay: "icon" })],
localServerId: null,
enabled: true,
});
@@ -118,6 +186,7 @@ describe("selectHostBadges", () => {
serverId: "alpha",
label: "Alpha",
color: "teal",
icon: "mini",
showLabel: false,
});
});
@@ -150,4 +219,21 @@ describe("selectHostBadges", () => {
});
expect(badges.size).toBe(0);
});
it("applies daemon-detected machine kind for auto icons while respecting explicit overrides", () => {
const badges = selectHostBadges({
hosts: [
host("alpha", "Alpha"),
host("beta", "Beta", { color: "sky", icon: "workstation", badgeDisplay: "name" }),
],
localServerId: null,
detectedMachineKindByServerId: new Map([
["alpha", "laptop"],
["beta", "cloud"],
]),
enabled: true,
});
expect(badges.get("alpha")?.icon).toBe("laptop");
expect(badges.get("beta")?.icon).toBe("workstation");
});
});
+65 -4
View File
@@ -6,25 +6,69 @@ export type HostColor = "none" | IdentityColorName;
export const HOST_COLORS: readonly HostColor[] = ["none", ...IDENTITY_COLOR_NAMES];
export const HOST_ICONS = [
"server",
"laptop",
"desktop",
"mini",
"workstation",
"cloud",
"container",
"board",
"terminal",
] as const;
export type HostIcon = (typeof HOST_ICONS)[number];
export const DEFAULT_HOST_ICON: HostIcon = "server";
const HOST_ICON_SET = new Set<string>(HOST_ICONS);
export function normalizeDetectedHostIcon(value: string | null | undefined): HostIcon | null {
const trimmed = value?.trim();
if (trimmed && HOST_ICON_SET.has(trimmed)) {
return trimmed as HostIcon;
}
return null;
}
export type HostBadgeDisplay = "name" | "icon" | "hidden";
export const HOST_BADGE_DISPLAYS: readonly HostBadgeDisplay[] = ["name", "icon", "hidden"];
/**
* Per-device host presentation. `badgeDisplay` is null while the user has not chosen,
* because the default differs by host (local hides, remote shows) and local-ness is only
* knowable from a desktop-only async query — never at parse time.
* Per-device host presentation.
* - `icon` is omitted while untouched ("Auto") so existing records stay byte-for-byte compatible
* with older builds whose stored appearance schema is strict. An unknown icon string written by
* a newer build is preserved on disk and falls back at render time via `resolveHostIcon`.
* - `badgeDisplay` is null while untouched so runtime defaults apply (hidden for local / name for
* remote) without baking runtime facts at parse time.
*/
export interface HostAppearance {
color: HostColor;
icon?: string;
badgeDisplay: HostBadgeDisplay | null;
}
export const HostAppearanceSchema: z.ZodType<HostAppearance> = z.strictObject({
const StoredHostAppearanceSchema = z.strictObject({
color: z.enum(["none", ...IDENTITY_COLOR_NAMES]),
// Optional loose string on disk so untouched hosts stay readable after a downgrade and an icon
// added by a newer build survives read/write instead of being dropped or overwritten.
icon: z.string().nullable().optional(),
badgeDisplay: z.enum(["name", "icon", "hidden"]).nullable(),
});
export const HostAppearanceSchema = StoredHostAppearanceSchema.transform(
(value): HostAppearance => {
const icon = value.icon?.trim();
return {
color: value.color,
...(icon ? { icon } : {}),
badgeDisplay: value.badgeDisplay,
};
},
);
export function defaultHostAppearance(): HostAppearance {
return { color: "none", badgeDisplay: null };
}
@@ -34,6 +78,17 @@ export function normalizeStoredHostAppearance(value: unknown): HostAppearance {
return result.success ? result.data : defaultHostAppearance();
}
export function resolveHostIcon(input: {
appearance: HostAppearance;
detectedMachineKind?: string | null;
}): HostIcon {
return (
normalizeDetectedHostIcon(input.appearance.icon) ??
normalizeDetectedHostIcon(input.detectedMachineKind) ??
DEFAULT_HOST_ICON
);
}
export function resolveHostBadgeDisplay(input: {
appearance: HostAppearance;
isLocalHost: boolean;
@@ -52,6 +107,7 @@ export interface HostBadgeModel {
serverId: string;
label: string;
color: HostColor;
icon: HostIcon;
showLabel: boolean;
}
@@ -66,6 +122,7 @@ export function selectHostBadges(input: {
hosts: readonly HostAppearanceSource[];
localServerId: string | null;
localHostResolutionPending?: boolean;
detectedMachineKindByServerId?: ReadonlyMap<string, string | null>;
enabled: boolean;
}): ReadonlyMap<string, HostBadgeModel> {
const badges = new Map<string, HostBadgeModel>();
@@ -85,6 +142,10 @@ export function selectHostBadges(input: {
serverId: host.serverId,
label: host.label.trim() || host.serverId,
color: host.appearance.color,
icon: resolveHostIcon({
appearance: host.appearance,
detectedMachineKind: input.detectedMachineKindByServerId?.get(host.serverId) ?? null,
}),
showLabel: display === "name",
});
}
@@ -0,0 +1,134 @@
import { describe, expect, it } from "vitest";
import {
describeActiveConnection,
describeHostConnection,
formatConnectionEndpoint,
isTailscaleEndpoint,
} from "./connection-display";
describe("isTailscaleEndpoint", () => {
it("recognizes MagicDNS .ts.net hostnames with or without ports", () => {
expect(isTailscaleEndpoint("mac-mini.tail123.ts.net:6767")).toBe(true);
expect(isTailscaleEndpoint("Mac-Mini.Tail123.TS.NET:443")).toBe(true);
expect(isTailscaleEndpoint("devbox.tailnet.ts.net")).toBe(true);
expect(isTailscaleEndpoint(".ts.net")).toBe(false);
});
it("recognizes Tailscale IPv4 CGNAT (100.64.0.0/10) and IPv6 ULA addresses", () => {
expect(isTailscaleEndpoint("100.64.0.1:6767")).toBe(true);
expect(isTailscaleEndpoint("100.100.42.9:6767")).toBe(true);
expect(isTailscaleEndpoint("100.127.255.254:6767")).toBe(true);
expect(isTailscaleEndpoint("100.63.255.255:6767")).toBe(false);
expect(isTailscaleEndpoint("100.128.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("[fd7a:115c:a1e0::1]:6767")).toBe(true);
});
it("does not misclassify LAN, localhost, or ordinary domains", () => {
expect(isTailscaleEndpoint("localhost:6767")).toBe(false);
expect(isTailscaleEndpoint("127.0.0.1:6767")).toBe(false);
expect(isTailscaleEndpoint("192.168.1.25:6767")).toBe(false);
expect(isTailscaleEndpoint("relay.paseo.sh:443")).toBe(false);
expect(isTailscaleEndpoint("not-ts.net.example.com:6767")).toBe(false);
});
});
describe("describeActiveConnection", () => {
it("describes local socket and pipe connections without exposing paths", () => {
expect(
describeActiveConnection({
type: "directSocket",
endpoint: "/tmp/paseo.sock",
display: "socket",
}),
).toEqual({ kind: "local" });
expect(
describeActiveConnection({
type: "directPipe",
endpoint: "\\\\.\\pipe\\paseo",
display: "pipe",
}),
).toEqual({ kind: "local" });
});
it("describes loopback TCP on the local host as local, and remote loopback as direct", () => {
const loopback = {
type: "directTcp",
endpoint: "localhost:6767",
display: "localhost:6767",
} as const;
expect(describeActiveConnection(loopback, { isLocalHost: true })).toEqual({ kind: "local" });
expect(describeActiveConnection(loopback, { isLocalHost: false })).toEqual({
kind: "direct",
endpoint: "localhost:6767",
});
});
it("strips standard web ports on relay, tailscale, and direct connections", () => {
expect(
describeActiveConnection({ type: "relay", endpoint: "relay.paseo.sh:443", display: "relay" }),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
display: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeActiveConnection({
type: "directTcp",
endpoint: "devbox.example.com:443",
display: "devbox.example.com:443",
}),
).toEqual({ kind: "direct", endpoint: "devbox.example.com" });
});
it("preserves SSH and routed targets", () => {
expect(
describeActiveConnection({
type: "remoteSsh",
endpoint: "mo@workstation",
display: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
expect(
describeActiveConnection({
type: "routed",
endpoint: "srv_origin",
display: "via srv_origin",
}),
).toEqual({ kind: "routed", endpoint: "srv_origin" });
});
it("strips default HTTP/HTTPS ports only", () => {
expect(formatConnectionEndpoint("relay.paseo.sh:443")).toBe("relay.paseo.sh");
expect(formatConnectionEndpoint("example.com:80")).toBe("example.com");
expect(formatConnectionEndpoint("127.0.0.1:6767")).toBe("127.0.0.1:6767");
});
it("describes configured host connections before an active connection is online", () => {
expect(
describeHostConnection({
id: "direct:mac-mini.tail123.ts.net:6767",
type: "directTcp",
endpoint: "mac-mini.tail123.ts.net:6767",
}),
).toEqual({ kind: "tailscale", endpoint: "mac-mini.tail123.ts.net:6767" });
expect(
describeHostConnection({
id: "relay:wss:relay.paseo.sh:443",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
useTls: true,
daemonPublicKeyB64: "key",
}),
).toEqual({ kind: "relay", endpoint: "relay.paseo.sh" });
expect(
describeHostConnection({
id: "ssh:mo%40workstation::",
type: "remoteSsh",
host: "mo@workstation",
}),
).toEqual({ kind: "ssh", endpoint: "mo@workstation" });
});
});
@@ -0,0 +1,120 @@
import type { ActiveConnection } from "@/runtime/host-runtime";
import type { HostConnection } from "@/types/host-connection";
export type HostConnectionKind = "local" | "relay" | "tailscale" | "ssh" | "direct" | "routed";
export interface HostConnectionDisplay {
kind: HostConnectionKind;
/** Address shown beside the connection kind. Omitted for local transports. */
endpoint?: string;
}
// Standard secure/plain web ports carry no information in the host display, so
// "relay.paseo.sh:443" reads as "relay.paseo.sh" while "127.0.0.1:6767" is kept.
export function formatConnectionEndpoint(endpoint: string): string {
return endpoint.replace(/:(?:443|80)$/, "");
}
function extractEndpointHost(endpoint: string): string {
const trimmed = endpoint.trim().toLowerCase();
if (!trimmed) return "";
const withoutScheme = trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//, "");
const authority = withoutScheme.split("/")[0] ?? "";
const hostPort = authority.includes("@")
? authority.slice(authority.lastIndexOf("@") + 1)
: authority;
if (hostPort.startsWith("[")) {
const closeBracket = hostPort.indexOf("]");
return closeBracket > 1 ? hostPort.slice(1, closeBracket) : hostPort;
}
const firstColon = hostPort.indexOf(":");
const lastColon = hostPort.lastIndexOf(":");
if (firstColon !== -1 && firstColon === lastColon) {
return hostPort.slice(0, firstColon);
}
return hostPort;
}
function isTailscaleIpv4(host: string): boolean {
const parts = host.split(".");
if (parts.length !== 4) return false;
const octets = parts.map((part) => (/^\d+$/.test(part) ? Number(part) : Number.NaN));
if (octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) {
return false;
}
// Tailscale assigns addresses from the RFC 6598 CGNAT range 100.64.0.0/10.
return octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127;
}
function isTailscaleIpv6(host: string): boolean {
return host.startsWith("fd7a:115c:a1e0:");
}
export function isTailscaleEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
if (!host) return false;
if (host.endsWith(".ts.net") && host.length > ".ts.net".length) {
return true;
}
return isTailscaleIpv4(host) || isTailscaleIpv6(host);
}
export function isLoopbackEndpoint(endpoint: string): boolean {
const host = extractEndpointHost(endpoint);
return host === "localhost" || host === "127.0.0.1" || host === "::1";
}
export function describeActiveConnection(
connection: ActiveConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.endpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.endpoint };
case "routed":
return { kind: "routed", endpoint: connection.endpoint };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
export function describeHostConnection(
connection: HostConnection,
options?: { isLocalHost?: boolean },
): HostConnectionDisplay {
switch (connection.type) {
case "directSocket":
case "directPipe":
return { kind: "local" };
case "relay":
return { kind: "relay", endpoint: formatConnectionEndpoint(connection.relayEndpoint) };
case "remoteSsh":
return { kind: "ssh", endpoint: connection.host };
case "routed":
return { kind: "routed", endpoint: connection.originServerId };
case "directTcp": {
if (options?.isLocalHost && isLoopbackEndpoint(connection.endpoint)) {
return { kind: "local" };
}
if (isTailscaleEndpoint(connection.endpoint)) {
return { kind: "tailscale", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
return { kind: "direct", endpoint: formatConnectionEndpoint(connection.endpoint) };
}
}
}
+8 -29
View File
@@ -1,9 +1,8 @@
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Server } from "lucide-react-native";
import { HOST_COLORS, type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { StyleSheet } from "react-native-unistyles";
import { type HostBadgeModel, type HostColor } from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
/**
* The glyph size the badge draws at. Rows that place the badge alongside their own glyphs
@@ -11,30 +10,9 @@ import type { Theme } from "@/styles/theme";
*/
export const HOST_BADGE_ICON_SIZE = 12;
const ThemedServer = withUnistyles(Server);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable mapping per host color for the life of the module — a fresh `uniProps` identity
// on every render makes withUnistyles re-subscribe each pass. The scheme is read inside the
// mapping rather than baked in, so a theme change repaints the glyph without a React render.
//
// Glyph and label share one color, so a badge reads as one object rather than a colored icon
// with an unrelated grey word beside it.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
/**
* Which machine something lives on, drawn the same way everywhere it appears: a server glyph
* and, when the host is configured to show one, its name — both in the host's identity color.
* Which machine something lives on, drawn the same way everywhere it appears: the host's device
* glyph and, when the host is configured to show one, its name — both in the host's identity color.
*
* A hostname is the least interesting thing on any line that carries it and the only one whose
* length nobody chose, so the badge yields space before its neighbours rather than alongside
@@ -47,10 +25,11 @@ export function HostBadge({ badge }: { badge: HostBadgeModel }) {
testID={`host-badge-${badge.serverId}`}
accessibilityLabel={badge.label}
>
<ThemedServer
<HostIconGlyph
icon={badge.icon}
color={badge.color}
size={HOST_BADGE_ICON_SIZE}
style={styles.icon}
uniProps={HOST_ICON_MAPPINGS[badge.color]}
/>
{badge.showLabel ? (
<Text style={[styles.label, labelColorStyle(badge.color)]} numberOfLines={1}>
+66 -27
View File
@@ -7,14 +7,16 @@ import {
EditingTextInput as TextInput,
type EditingTextInputHandle,
} from "@/components/ui/text-input";
import { Server } from "lucide-react-native";
import { create } from "zustand";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
import { HostStatusDot } from "@/components/host-status-dot";
import { isWeb } from "@/constants/platform";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { resolveHostIcon } from "@/hosts/appearance";
import { HostConnectionLine, HostIconGlyph, HostLatencyLabel } from "@/hosts/host-icon";
import { OverlayLayerProvider, useGlobalOverlayLayer } from "@/lib/overlay-root";
import { useHosts } from "@/runtime/host-runtime";
import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { orderHostsLocalFirst, type HostProfile } from "@/types/host-connection";
type HostFilter = (host: HostProfile) => boolean;
@@ -101,36 +103,52 @@ function HostChooserRow({
active: boolean;
onChooseHost: (serverId: string) => void;
}) {
const { theme } = useUnistyles();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const [hovered, setHovered] = useState(false);
const handlePointerEnter = useCallback(() => setHovered(true), []);
const handlePointerLeave = useCallback(() => setHovered(false), []);
const handlePress = useCallback(() => onChooseHost(host.serverId), [host.serverId, onChooseHost]);
const rowStyle = useCallback(
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
({ pressed }: PressableStateCallbackType) => [
styles.row,
(active || hovered || pressed) && styles.rowActive,
],
[active],
[active, hovered],
);
return (
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDotSlot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
<Text style={styles.rowSubtitle} numberOfLines={1}>
{host.serverId}
</Text>
</View>
<Server size={theme.iconSize.sm} color={theme.colors.foregroundMuted} />
</Pressable>
<View onPointerEnter={handlePointerEnter} onPointerLeave={handlePointerLeave}>
<Pressable
accessibilityRole="button"
onPress={handlePress}
style={rowStyle}
testID={`host-chooser-row-${host.serverId}`}
>
<View style={styles.rowIconSlot}>
<HostStatusDot serverId={host.serverId} />
</View>
<View style={styles.rowText}>
<View style={styles.rowHeader}>
<HostIconGlyph
icon={resolvedIcon}
color={host.appearance.color}
size={14}
style={styles.rowGlyph}
/>
<Text style={styles.rowTitle} numberOfLines={1}>
{host.label}
</Text>
</View>
<HostConnectionLine serverId={host.serverId} />
</View>
<View style={styles.rowTrailing}>
<HostLatencyLabel serverId={host.serverId} />
</View>
</Pressable>
</View>
);
}
@@ -161,6 +179,7 @@ export function HostChooserModal() {
useEffect(() => {
if (!request) return;
getHostRuntimeStore().refreshActiveLatencies(request.serverIds);
inputRef.current?.replaceText("");
setQuery("");
setActiveIndex(0);
@@ -328,7 +347,7 @@ const styles = StyleSheet.create((theme) => ({
},
row: {
flexDirection: "row",
alignItems: "center",
alignItems: "flex-start",
gap: theme.spacing[3],
minHeight: 56,
paddingHorizontal: theme.spacing[4],
@@ -337,19 +356,39 @@ const styles = StyleSheet.create((theme) => ({
rowActive: {
backgroundColor: theme.colors.surface1,
},
rowTrailing: {
flexDirection: "row",
alignItems: "center",
height: 20,
flexShrink: 0,
},
rowIconSlot: {
width: 18,
width: 16,
height: 20,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
rowText: {
flex: 1,
minWidth: 0,
gap: theme.spacing[1],
},
rowHeader: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
rowGlyph: {
flexShrink: 0,
},
rowTitle: {
flex: 1,
minWidth: 0,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
lineHeight: 20,
},
rowSubtitle: {
color: theme.colors.foregroundMuted,
@@ -0,0 +1,77 @@
import type { ReactElement } from "react";
import type { StyleProp, ViewStyle } from "react-native";
import {
Cloud,
Computer,
Container,
Cpu,
Laptop,
Monitor,
PcCase,
Server,
Terminal,
} from "lucide-react-native";
import { withUnistyles } from "react-native-unistyles";
import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance";
import { identityForeground } from "@/styles/identity-colors";
import type { Theme } from "@/styles/theme";
const ThemedServer = withUnistyles(Server);
const ThemedLaptop = withUnistyles(Laptop);
const ThemedMonitor = withUnistyles(Monitor);
const ThemedComputer = withUnistyles(Computer);
const ThemedPcCase = withUnistyles(PcCase);
const ThemedCloud = withUnistyles(Cloud);
const ThemedContainer = withUnistyles(Container);
const ThemedCpu = withUnistyles(Cpu);
const ThemedTerminal = withUnistyles(Terminal);
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
// One stable uniProps mapping per host color for the life of the module — a fresh identity on
// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the
// mapping keeps theme switches off React's render path.
const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }> = (() => {
const byColor = {} as Record<HostColor, (theme: Theme) => { color: string }>;
for (const color of HOST_COLORS) {
byColor[color] =
color === "none"
? mutedMapping
: (theme: Theme) => ({ color: identityForeground(color, theme.colorScheme) });
}
return byColor;
})();
export function HostIconGlyph({
icon = DEFAULT_HOST_ICON,
color = "none",
size = 16,
style,
}: {
icon?: HostIcon;
color?: HostColor;
size?: number;
style?: StyleProp<ViewStyle>;
}): ReactElement {
const uniProps = HOST_ICON_MAPPINGS[color];
switch (icon) {
case "laptop":
return <ThemedLaptop size={size} style={style} uniProps={uniProps} />;
case "desktop":
return <ThemedMonitor size={size} style={style} uniProps={uniProps} />;
case "mini":
return <ThemedComputer size={size} style={style} uniProps={uniProps} />;
case "workstation":
return <ThemedPcCase size={size} style={style} uniProps={uniProps} />;
case "cloud":
return <ThemedCloud size={size} style={style} uniProps={uniProps} />;
case "container":
return <ThemedContainer size={size} style={style} uniProps={uniProps} />;
case "board":
return <ThemedCpu size={size} style={style} uniProps={uniProps} />;
case "terminal":
return <ThemedTerminal size={size} style={style} uniProps={uniProps} />;
case "server":
return <ThemedServer size={size} style={style} uniProps={uniProps} />;
}
}
+215
View File
@@ -0,0 +1,215 @@
import { useMemo, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { Globe, Monitor, Network, Terminal, Waypoints } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TailscaleIcon } from "@/components/icons/tailscale-icon";
import {
describeActiveConnection,
describeHostConnection,
type HostConnectionKind,
} from "@/hosts/connection-display";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import type { HostProfile } from "@/types/host-connection";
import { formatLatency } from "@/utils/latency";
export { HostIconGlyph };
const CONNECTION_GLYPH_SIZE = 11;
const ThemedMonitor = withUnistyles(Monitor);
const ThemedTerminal = withUnistyles(Terminal);
const ThemedGlobe = withUnistyles(Globe);
const ThemedNetwork = withUnistyles(Network);
const ThemedWaypoints = withUnistyles(Waypoints);
const ThemedTailscale = withUnistyles(TailscaleIcon);
const extraMutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted });
function ConnectionKindGlyph({ kind }: { kind: HostConnectionKind }): ReactElement {
switch (kind) {
case "local":
return (
<ThemedMonitor
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "relay":
return (
<ThemedGlobe
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "tailscale":
return <ThemedTailscale size={CONNECTION_GLYPH_SIZE} uniProps={extraMutedMapping} />;
case "ssh":
return (
<ThemedTerminal
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "routed":
return (
<ThemedWaypoints
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
case "direct":
return (
<ThemedNetwork
size={CONNECTION_GLYPH_SIZE}
style={styles.linkIcon}
uniProps={extraMutedMapping}
/>
);
}
}
function resolvePreferredConnection(host: HostProfile | undefined) {
if (!host || host.connections.length === 0) return null;
if (host.preferredConnectionId) {
const preferred = host.connections.find(
(connection) => connection.id === host.preferredConnectionId,
);
if (preferred) return preferred;
}
return host.connections[0] ?? null;
}
export function HostConnectionLine({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const localServerId = useLocalDaemonServerId();
const hosts = useHosts();
const activeConnection = snapshot?.activeConnection ?? null;
const hostProfile = useMemo(
() => hosts.find((candidate) => candidate.serverId === serverId),
[hosts, serverId],
);
const fallbackConnection = useMemo(
() => (activeConnection ? null : resolvePreferredConnection(hostProfile)),
[activeConnection, hostProfile],
);
const described = useMemo(() => {
const options = { isLocalHost: serverId === localServerId };
if (activeConnection) {
return describeActiveConnection(activeConnection, options);
}
if (fallbackConnection) {
return describeHostConnection(fallbackConnection, options);
}
return null;
}, [activeConnection, fallbackConnection, localServerId, serverId]);
if (!described) {
return null;
}
const endpoint =
described.kind === "routed" && described.endpoint
? (hosts.find((host) => host.serverId === described.endpoint)?.label ?? described.endpoint)
: described.endpoint;
return (
<View style={styles.connectionRow}>
<View style={styles.linkIconSlot}>
<ConnectionKindGlyph kind={described.kind} />
</View>
<Text style={styles.connectionKind} numberOfLines={1}>
{t(`settings.host.connectionKinds.${described.kind}`)}
</Text>
{endpoint ? (
<Text style={styles.connectionEndpoint} numberOfLines={1}>
{endpoint}
</Text>
) : null}
</View>
);
}
export function HostLatencyLabel({ serverId }: { serverId: string }): ReactElement | null {
const { t } = useTranslation();
const snapshot = useHostRuntimeSnapshot(serverId);
const status = snapshot?.connectionStatus;
const activeConnectionId = snapshot?.activeConnectionId;
const activeProbe = activeConnectionId
? snapshot?.probeByConnectionId.get(activeConnectionId)
: undefined;
const latencyMs =
status === "online" && activeProbe?.status === "available" ? activeProbe.latencyMs : null;
if (latencyMs !== null) {
return (
<Text style={styles.latency} numberOfLines={1}>
{formatLatency(latencyMs)}
</Text>
);
}
if (status === "offline" || status === "error") {
return (
<Text style={styles.statusText} numberOfLines={1}>
{t("common.connectionStatus.offline")}
</Text>
);
}
return null;
}
const styles = StyleSheet.create((theme) => ({
connectionRow: {
flexDirection: "row",
alignItems: "center",
gap: 6,
minWidth: 0,
},
// Matches the 14px host icon width on the row above so connection text aligns on the same rail.
linkIconSlot: {
width: 14,
alignItems: "center",
justifyContent: "center",
flexShrink: 0,
},
linkIcon: {
flexShrink: 0,
},
connectionKind: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
flexShrink: 0,
},
connectionEndpoint: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 1,
minWidth: 0,
},
latency: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundMuted,
fontVariant: ["tabular-nums"],
flexShrink: 0,
},
statusText: {
fontSize: theme.fontSize.sm,
lineHeight: 16,
color: theme.colors.foregroundExtraMuted,
flexShrink: 0,
},
}));
+24 -11
View File
@@ -1,11 +1,13 @@
import { useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { useHosts } from "@/runtime/host-runtime";
import { useLocalDaemonServerId, useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { selectHostBadges, type HostBadgeModel } from "@/hosts/appearance";
import { useSessionStore } from "@/stores/session-store";
/**
* Every host's badge, resolved from the three things that decide one: the host registry, which
* host is local, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* Every host's badge, resolved from the host registry, local-host detection, daemon-reported
* machine kind, and each host's own appearance. `enabled` is the caller's own "off" — a surface
* that has its own reason to hide badges passes false rather than filtering the result, so the
* per-host setting stays the only thing that decides name vs icon vs hidden.
*/
@@ -17,14 +19,25 @@ export function useHostBadges({
const hosts = useHosts();
const localServerId = useLocalDaemonServerId();
const localDaemon = useLocalDaemonServerIdState();
return useMemo(
() =>
selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
enabled,
}),
[hosts, localDaemon.status, localServerId, enabled],
const detectedMachineKinds = useSessionStore(
useShallow((state) => {
const result: Record<string, string | null> = {};
for (const host of hosts) {
result[host.serverId] = state.sessions[host.serverId]?.serverInfo?.machineKind ?? null;
}
return result;
}),
);
return useMemo(() => {
const detectedMachineKindByServerId = new Map<string, string | null>(
Object.entries(detectedMachineKinds),
);
return selectHostBadges({
hosts,
localServerId,
localHostResolutionPending: localDaemon.status !== "resolved",
detectedMachineKindByServerId,
enabled,
});
}, [hosts, localDaemon.status, localServerId, detectedMachineKinds, enabled]);
}
+25 -2
View File
@@ -738,8 +738,6 @@ export const ar: TranslationResources = {
resumeCommandUnavailable: "أمر الاستئناف غير متوفر",
reloadingAgent: "وكيل إعادة التحميل...",
reloadedAgent: "وكيل إعادة تحميل",
reloadedAgentHistoryDiverged:
"تمت إعادة تحميل الوكيل، لكن سجل المزوّد لا يطابق هذه المحادثة، لذا لم تتم مزامنته",
failedToReloadAgent: "فشل في إعادة تحميل الوكيل",
failedToCloseAgent: "فشل في إغلاق الوكيل",
},
@@ -2843,6 +2841,23 @@ export const ar: TranslationResources = {
name: {
label: "الاسم",
},
icon: {
label: "الأيقونة",
accessibilityLabel: "الأيقونة، {{value}}",
auto: "تلقائي",
autoDetected: "تلقائي ({{icon}})",
options: {
server: "خادم",
laptop: "حاسوب محمول",
desktop: "حاسوب مكتبي",
mini: "حاسوب مصغّر",
workstation: "محطة عمل",
cloud: "سحابي",
container: "حاوية",
board: "حاسوب أحادي اللوحة",
terminal: "طرفية",
},
},
color: {
label: "اللون",
accessibilityLabel: "اللون، {{value}}",
@@ -2879,6 +2894,14 @@ export const ar: TranslationResources = {
local: "محلي",
remoteSsh: "SSH عن بُعد",
},
connectionKinds: {
local: "محلي",
relay: "تتابع",
tailscale: "Tailscale",
ssh: "SSH",
direct: "مباشر",
routed: "عبر",
},
connections: {
title: "اتصالات",
removeTitle: "إزالة الاتصال",
+25 -2
View File
@@ -737,8 +737,6 @@ export const en = {
resumeCommandUnavailable: "Resume command not available",
reloadingAgent: "Reloading agent...",
reloadedAgent: "Reloaded agent",
reloadedAgentHistoryDiverged:
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced",
failedToReloadAgent: "Failed to reload agent",
failedToCloseAgent: "Failed to close agent",
},
@@ -2938,6 +2936,23 @@ export const en = {
name: {
label: "Name",
},
icon: {
label: "Icon",
accessibilityLabel: "Icon, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Server",
laptop: "Laptop",
desktop: "Desktop",
mini: "Mini",
workstation: "Workstation",
cloud: "Cloud",
container: "Container",
board: "Single-board PC",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2974,6 +2989,14 @@ export const en = {
local: "Local",
remoteSsh: "Remote SSH",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connections",
removeTitle: "Remove connection",
+25 -2
View File
@@ -745,8 +745,6 @@ export const es: TranslationResources = {
resumeCommandUnavailable: "Comando de reanudación no disponible",
reloadingAgent: "Agente de recarga...",
reloadedAgent: "Agente recargado",
reloadedAgentHistoryDiverged:
"Agente recargado, pero el historial del proveedor no coincide con este chat, así que no se sincronizó",
failedToReloadAgent: "No se pudo recargar el agente",
failedToCloseAgent: "No se pudo cerrar el agente",
},
@@ -2867,6 +2865,23 @@ export const es: TranslationResources = {
name: {
label: "Nombre",
},
icon: {
label: "Icono",
accessibilityLabel: "Icono, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Portátil",
desktop: "Escritorio",
mini: "Mini",
workstation: "Estación de trabajo",
cloud: "Nube",
container: "Contenedor",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Color",
accessibilityLabel: "Color, {{value}}",
@@ -2903,6 +2918,14 @@ export const es: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relé",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Directo",
routed: "Vía",
},
connections: {
title: "Conexiones",
removeTitle: "Quitar conexión",
+25 -2
View File
@@ -745,8 +745,6 @@ export const fr: TranslationResources = {
resumeCommandUnavailable: "Commande de reprise indisponible",
reloadingAgent: "Rechargement de l’agent…",
reloadedAgent: "Agent rechargé",
reloadedAgentHistoryDiverged:
"Agent rechargé, mais l’historique du fournisseur ne correspond pas à cette conversation, il n’a donc pas été synchronisé",
failedToReloadAgent: "Impossible de recharger l’agent",
failedToCloseAgent: "Impossible de fermer l’agent",
},
@@ -2869,6 +2867,23 @@ export const fr: TranslationResources = {
name: {
label: "Nom",
},
icon: {
label: "Icône",
accessibilityLabel: "Icône, {{value}}",
auto: "Auto",
autoDetected: "Auto ({{icon}})",
options: {
server: "Serveur",
laptop: "Portable",
desktop: "Bureau",
mini: "Mini",
workstation: "Station de travail",
cloud: "Cloud",
container: "Conteneur",
board: "Ordinateur monocarte",
terminal: "Terminal",
},
},
color: {
label: "Couleur",
accessibilityLabel: "Couleur, {{value}}",
@@ -2905,6 +2920,14 @@ export const fr: TranslationResources = {
local: "Local",
remoteSsh: "SSH distant",
},
connectionKinds: {
local: "Local",
relay: "Relais",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direct",
routed: "Via",
},
connections: {
title: "Connexions",
removeTitle: "Supprimer la connexion",
+25 -2
View File
@@ -745,8 +745,6 @@ export const ja: TranslationResources = {
resumeCommandUnavailable: "再開コマンドが利用できません",
reloadingAgent: "エージェントを再読み込み中...",
reloadedAgent: "エージェントを再読み込みしました",
reloadedAgentHistoryDiverged:
"エージェントを再読み込みしましたが、プロバイダーの履歴がこのチャットと一致しないため同期しませんでした",
failedToReloadAgent: "エージェントの再読み込みに失敗しました",
failedToCloseAgent: "エージェントを閉じられませんでした",
},
@@ -2835,6 +2833,23 @@ export const ja: TranslationResources = {
name: {
label: "名前",
},
icon: {
label: "アイコン",
accessibilityLabel: "アイコン、{{value}}",
auto: "自動",
autoDetected: "自動 ({{icon}})",
options: {
server: "サーバー",
laptop: "ノート PC",
desktop: "デスクトップ",
mini: "ミニ PC",
workstation: "ワークステーション",
cloud: "クラウド",
container: "コンテナ",
board: "シングルボード PC",
terminal: "ターミナル",
},
},
color: {
label: "色",
accessibilityLabel: "色、{{value}}",
@@ -2871,6 +2886,14 @@ export const ja: TranslationResources = {
local: "ローカル",
remoteSsh: "リモート SSH",
},
connectionKinds: {
local: "ローカル",
relay: "リレー",
tailscale: "Tailscale",
ssh: "SSH",
direct: "ダイレクト",
routed: "経由",
},
connections: {
title: "接続",
removeTitle: "接続を削除",
+25 -2
View File
@@ -740,8 +740,6 @@ export const ko: TranslationResources = {
resumeCommandUnavailable: "재개 명령을 사용할 수 없습니다",
reloadingAgent: "에이전트 다시 로드 중...",
reloadedAgent: "에이전트를 다시 로드했습니다",
reloadedAgentHistoryDiverged:
"에이전트를 다시 로드했지만 제공자 기록이 이 채팅과 일치하지 않아 동기화하지 않았습니다",
failedToReloadAgent: "에이전트를 다시 로드하지 못했습니다",
failedToCloseAgent: "에이전트를 닫지 못했습니다",
},
@@ -2821,6 +2819,23 @@ export const ko: TranslationResources = {
name: {
label: "이름",
},
icon: {
label: "아이콘",
accessibilityLabel: "아이콘, {{value}}",
auto: "자동",
autoDetected: "자동 ({{icon}})",
options: {
server: "서버",
laptop: "노트북",
desktop: "데스크톱",
mini: "미니",
workstation: "워크스테이션",
cloud: "클라우드",
container: "컨테이너",
board: "싱글보드 PC",
terminal: "터미널",
},
},
color: {
label: "색상",
accessibilityLabel: "색상, {{value}}",
@@ -2857,6 +2872,14 @@ export const ko: TranslationResources = {
local: "로컬",
remoteSsh: "원격 SSH",
},
connectionKinds: {
local: "로컬",
relay: "릴레이",
tailscale: "Tailscale",
ssh: "SSH",
direct: "직접 연결",
routed: "경유",
},
connections: {
title: "연결",
removeTitle: "연결 제거",
+25 -2
View File
@@ -743,8 +743,6 @@ export const ptBR: TranslationResources = {
resumeCommandUnavailable: "Comando de retomada indisponível",
reloadingAgent: "Recarregando agente...",
reloadedAgent: "Agente recarregado",
reloadedAgentHistoryDiverged:
"Agente recarregado, mas o histórico do provedor não corresponde a este chat, então não foi sincronizado",
failedToReloadAgent: "Falha ao recarregar agente",
failedToCloseAgent: "Falha ao fechar agente",
},
@@ -2848,6 +2846,23 @@ export const ptBR: TranslationResources = {
name: {
label: "Nome",
},
icon: {
label: "Ícone",
accessibilityLabel: "Ícone, {{value}}",
auto: "Automático",
autoDetected: "Automático ({{icon}})",
options: {
server: "Servidor",
laptop: "Notebook",
desktop: "Desktop",
mini: "Mini",
workstation: "Estação de trabalho",
cloud: "Nuvem",
container: "Contêiner",
board: "PC de placa única",
terminal: "Terminal",
},
},
color: {
label: "Cor",
accessibilityLabel: "Cor, {{value}}",
@@ -2884,6 +2899,14 @@ export const ptBR: TranslationResources = {
local: "Local",
remoteSsh: "SSH remoto",
},
connectionKinds: {
local: "Local",
relay: "Relay",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Direto",
routed: "Via",
},
connections: {
title: "Conexões",
removeTitle: "Remover conexão",
+25 -2
View File
@@ -746,8 +746,6 @@ export const ru: TranslationResources = {
resumeCommandUnavailable: "Команда возобновления недоступна",
reloadingAgent: "Перезагрузка агента...",
reloadedAgent: "Агент перезагружен",
reloadedAgentHistoryDiverged:
"Агент перезагружен, но история провайдера не совпадает с этим чатом, поэтому она не синхронизирована",
failedToReloadAgent: "Не удалось перезагрузить агента",
failedToCloseAgent: "Не удалось закрыть агента",
},
@@ -2856,6 +2854,23 @@ export const ru: TranslationResources = {
name: {
label: "Имя",
},
icon: {
label: "Значок",
accessibilityLabel: "Значок, {{value}}",
auto: "Авто",
autoDetected: "Авто ({{icon}})",
options: {
server: "Сервер",
laptop: "Ноутбук",
desktop: "Компьютер",
mini: "Мини-ПК",
workstation: "Рабочая станция",
cloud: "Облако",
container: "Контейнер",
board: "Одноплатный ПК",
terminal: "Терминал",
},
},
color: {
label: "Цвет",
accessibilityLabel: "Цвет, {{value}}",
@@ -2892,6 +2907,14 @@ export const ru: TranslationResources = {
local: "Локальный",
remoteSsh: "Удалённый SSH",
},
connectionKinds: {
local: "Локальный",
relay: "Ретранслятор",
tailscale: "Tailscale",
ssh: "SSH",
direct: "Прямой",
routed: "Через",
},
connections: {
title: "Подключения",
removeTitle: "Удалить подключение",
+25 -2
View File
@@ -738,8 +738,6 @@ export const zhCN: TranslationResources = {
resumeCommandUnavailable: "恢复命令不可用",
reloadingAgent: "正在重新加载 Agent...",
reloadedAgent: "已重新加载 Agent",
reloadedAgentHistoryDiverged:
"已重新加载 Agent,但提供方的历史记录与此对话不一致,因此未同步",
failedToReloadAgent: "重新加载 Agent 失败",
failedToCloseAgent: "关闭 Agent 失败",
},
@@ -2777,6 +2775,23 @@ export const zhCN: TranslationResources = {
name: {
label: "名称",
},
icon: {
label: "图标",
accessibilityLabel: "图标,{{value}}",
auto: "自动",
autoDetected: "自动 ({{icon}})",
options: {
server: "服务器",
laptop: "笔记本电脑",
desktop: "台式机",
mini: "迷你主机",
workstation: "工作站",
cloud: "云端",
container: "容器",
board: "单板机",
terminal: "终端",
},
},
color: {
label: "颜色",
accessibilityLabel: "颜色,{{value}}",
@@ -2813,6 +2828,14 @@ export const zhCN: TranslationResources = {
local: "本地",
remoteSsh: "远程 SSH",
},
connectionKinds: {
local: "本地",
relay: "中继",
tailscale: "Tailscale",
ssh: "SSH",
direct: "直连",
routed: "经由",
},
connections: {
title: "连接",
removeTitle: "移除连接",
@@ -91,7 +91,7 @@ describe("AgentDirectoryReplica", () => {
id: "reply",
text: "server history",
timestamp: new Date(),
timelineCursor: { epoch: "e", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "e", seq: 1 },
},
],
head: [],
+175 -6
View File
@@ -1114,6 +1114,106 @@ describe("HostRuntimeController", () => {
expect(activeClient.latencyMeasurements()).toEqual([]);
});
it("measures active latency on demand when an online host has no sample yet", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const controller = new HostRuntimeController({
host: makeHost({
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
preferredConnectionId: "direct:lan:6767",
}),
deps: makeDeps({ "direct:lan:6767": 14 }, []),
});
await controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "pending",
latencyMs: null,
});
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
});
it("keeps an on-demand active latency sample when a slower probe on another connection finishes", async () => {
useHostRuntimeClock();
const initialClient = new FakeDaemonClient();
initialClient.setConnectionState({ status: "connected" });
initialClient.ping = async () => ({ rttMs: 14 });
const relayProbeStarted = createDeferred<void>();
const slowRelayProbe = createDeferred<{
client: DaemonClient;
serverId: string;
hostname: string | null;
}>();
const relayClient = new FakeDaemonClient();
relayClient.setConnectionState({ status: "connected" });
relayClient.ping = async () => ({ rttMs: 90 });
const controller = new HostRuntimeController({
host: makeHost(),
deps: {
...makeDeps({}, []),
connectToDaemon: async ({ host, connection }) => {
if (connection.id === "relay:relay.paseo.sh:443") {
relayProbeStarted.resolve();
return slowRelayProbe.promise;
}
return {
client: initialClient as unknown as DaemonClient,
serverId: host.serverId,
hostname: null,
};
},
},
});
// Startup runs the first probe cycle immediately; wait until the slower relay probe is in
// flight, then measure active latency on demand before the relay probe resolves.
const startPromise = controller.start({
autoProbe: false,
initialConnection: {
connectionId: "direct:lan:6767",
existingClient: initialClient as unknown as DaemonClient,
},
});
await relayProbeStarted.promise;
await controller.refreshActiveLatency();
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
slowRelayProbe.resolve({
client: relayClient as unknown as DaemonClient,
serverId: "srv_test",
hostname: null,
});
await startPromise;
expect(controller.getSnapshot().probeByConnectionId.get("direct:lan:6767")).toEqual({
status: "available",
latencyMs: 14,
});
expect(controller.getSnapshot().probeByConnectionId.get("relay:relay.paseo.sh:443")).toEqual({
status: "available",
latencyMs: 90,
});
});
it.each([12, null])(
"falls back to relay when the direct client disconnects with heartbeat RTT %s",
async (heartbeatRtt) => {
@@ -3366,7 +3466,11 @@ describe("HostRuntimeStore", () => {
store.boot();
await registryLoaded;
expect(store.getHosts()[0]?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "none",
badgeDisplay: null,
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
@@ -3391,6 +3495,7 @@ describe("HostRuntimeStore", () => {
const updated = store.getHosts()[0];
expect(updated?.appearance).toEqual({ color: "teal", badgeDisplay: null });
expect("icon" in (updated?.appearance ?? {})).toBe(false);
expect(updated?.updatedAt).not.toBe(host.updatedAt);
const persisted = await storage.getItem("@paseo:daemon-registry");
@@ -3402,10 +3507,60 @@ describe("HostRuntimeStore", () => {
store.syncHosts([]);
});
it("records a chosen host icon and resets to auto without disturbing color or badge display", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "violet", badgeDisplay: "icon" },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
await storage.setItem("@paseo:e2e", "1");
const store = createAppearanceStore(storage);
const registryLoaded = onceHostListMatches(store, () => store.isHostRegistryLoaded());
store.boot();
await registryLoaded;
const hostListChanged = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === "laptop",
);
await store.setHostIcon("srv_appearance", "laptop");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "violet",
icon: "laptop",
badgeDisplay: "icon",
});
const resetToAuto = onceHostListMatches(
store,
() => store.getHosts()[0]?.appearance.icon === undefined,
);
await store.setHostIcon("srv_appearance", null);
await resetToAuto;
expect(store.getHosts()[0]?.appearance).toEqual({
color: "violet",
badgeDisplay: "icon",
});
expect("icon" in (store.getHosts()[0]?.appearance ?? {})).toBe(false);
store.syncHosts([]);
});
it("records a chosen badge display without disturbing the color", async () => {
const host = makeHost({
serverId: "srv_appearance",
appearance: { color: "amber", badgeDisplay: null },
appearance: { color: "amber", icon: "server", badgeDisplay: null },
});
const storage = createMemoryHostRuntimeStorage();
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
@@ -3423,11 +3578,16 @@ describe("HostRuntimeStore", () => {
await store.setHostBadgeDisplay("srv_appearance", "icon");
await hostListChanged;
expect(store.getHosts()[0]?.appearance).toEqual({ color: "amber", badgeDisplay: "icon" });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
const persisted = await storage.getItem("@paseo:daemon-registry");
expect(JSON.parse(persisted ?? "[]")[0].appearance).toEqual({
color: "amber",
icon: "server",
badgeDisplay: "icon",
});
@@ -3476,16 +3636,25 @@ describe("HostRuntimeStore", () => {
};
const color = store.setHostColor("srv_appearance", "teal");
const icon = store.setHostIcon("srv_appearance", "mini");
const display = store.setHostBadgeDisplay("srv_appearance", "icon");
await Promise.resolve();
expect(writeCount).toBe(1);
firstWrite.resolve();
await Promise.all([color, display]);
await Promise.all([color, icon, display]);
expect(store.getHosts()[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(store.getHosts()[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
const persistedHosts = JSON.parse((await storage.getItem("@paseo:daemon-registry")) ?? "[]");
expect(persistedHosts[0]?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(persistedHosts[0]?.appearance).toEqual({
color: "teal",
icon: "mini",
badgeDisplay: "icon",
});
store.syncHosts([]);
});
+95 -27
View File
@@ -28,7 +28,12 @@ import {
type HostProfile,
type UnreadableHostEntries,
} from "@/types/host-connection";
import { defaultHostAppearance, type HostBadgeDisplay, type HostColor } from "@/hosts/appearance";
import {
defaultHostAppearance,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import {
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
@@ -250,7 +255,6 @@ const PROBE_INACTIVE_WHILE_ONLINE_MAX_MS = 30 * 60_000;
const ACTIVE_RTT_WINDOW_MS = 60_000;
const ADAPTIVE_SWITCH_THRESHOLD_MS = 40;
const ADAPTIVE_SWITCH_MIN_IMPROVEMENT_RATIO = 0.35;
const MAX_STALE_TIMELINE_PAGE_ATTEMPTS = 3;
const ADAPTIVE_SWITCH_CONSECUTIVE_PROBES = 3;
const CONFIGURED_OVERRIDE_BOOTSTRAP_RETRY_MS = 1_000;
@@ -946,6 +950,56 @@ export class HostRuntimeController {
await this.switchToConnection(input);
}
/**
* Measures the active connection's round-trip time when the host is online and no sample has
* landed yet (for example right after connecting, before the first heartbeat interval fires).
*/
async refreshActiveLatency(): Promise<void> {
const activeConnectionId = this.snapshot.activeConnectionId;
const activeClient = this.snapshot.client;
if (
this.snapshot.connectionStatus !== "online" ||
!activeConnectionId ||
!activeClient ||
activeClient.getConnectionState().status !== "connected"
) {
return;
}
const existing = this.snapshot.probeByConnectionId.get(activeConnectionId);
if (existing?.status === "available") {
return;
}
const existingRtt = activeClient.getLastLivenessRttMs();
if (existingRtt !== null) {
this.recordActiveLatencySample(activeConnectionId, existingRtt);
return;
}
try {
const rttMs = await activeClient.measureLatency({ timeoutMs: 3_000 });
if (
this.snapshot.activeConnectionId !== activeConnectionId ||
this.snapshot.client !== activeClient ||
this.snapshot.connectionStatus !== "online"
) {
return;
}
this.recordActiveLatencySample(activeConnectionId, rttMs);
} catch {
// A latency probe never drives teardown; the heartbeat owns liveness.
}
}
private setConnectionProbe(connectionId: string, probe: ConnectionProbeState): void {
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
probeByConnectionId.set(connectionId, probe);
this.updateSnapshot({ probeByConnectionId });
}
private recordActiveLatencySample(connectionId: string, rttMs: number): void {
this.recordActiveRttSample(rttMs, performance.now());
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
}
async runProbeCycleNow(): Promise<void> {
if (this.probeCycleInFlight) {
return this.probeCycleInFlight;
@@ -1002,30 +1056,32 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const initialProbes = new Map(this.snapshot.probeByConnectionId);
for (const connection of connectionsToProbe) {
this.connectionLastProbedAt.set(connection.id, performance.now());
const existingProbe = probeByConnectionId.get(connection.id);
const existingProbe = initialProbes.get(connection.id);
const shouldPreserveActiveLatency =
isOnline && connection.id === activeConnectionId && existingProbe?.status === "available";
if (!shouldPreserveActiveLatency) {
probeByConnectionId.set(connection.id, {
initialProbes.set(connection.id, {
status: "pending",
latencyMs: null,
});
}
}
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
this.updateSnapshot({ probeByConnectionId: initialProbes });
let remaining = connectionsToProbe.length;
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
let activationLock: Promise<void> | null = null;
const publishProbeState = (): void => {
// Merge each connection result into the live snapshot map so a slow probe on another
// connection cannot overwrite a fresher sample (e.g. from refreshActiveLatency) on the active one.
const publishConnectionProbe = (connectionId: string, probe: ConnectionProbeState): void => {
if (!this.isCurrentProbeRequest(requestVersion)) {
return;
}
this.updateSnapshot({ probeByConnectionId: new Map(probeByConnectionId) });
this.setConnectionProbe(connectionId, probe);
};
const maybeActivateFirstAvailable = async (
@@ -1054,6 +1110,7 @@ export class HostRuntimeController {
return;
}
const probeByConnectionId = new Map(this.snapshot.probeByConnectionId);
const currentActiveConnectionId = this.snapshot.activeConnectionId;
if (currentActiveConnectionId) {
this.reconcileActiveProbeWithClient(currentActiveConnectionId, probeByConnectionId);
@@ -1209,11 +1266,10 @@ export class HostRuntimeController {
if (activeClient) {
if (activeClient.getConnectionState().status !== "connected") {
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
return;
}
const rttMs = activeClient.getLastLivenessRttMs();
@@ -1222,11 +1278,10 @@ export class HostRuntimeController {
}
if (rttMs !== null) {
this.recordActiveRttSample(rttMs, performance.now());
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
}
return;
}
@@ -1236,11 +1291,10 @@ export class HostRuntimeController {
return;
}
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "available",
latencyMs: rttMs,
});
publishProbeState();
} catch (error) {
if (this.isCurrentProbeRequest(requestVersion)) {
const authFailure = getConnectionAuthFailureReason(error);
@@ -1248,11 +1302,10 @@ export class HostRuntimeController {
this.authRejectedConnectionIds.add(connection.id);
probeAuthFailure = authFailure;
}
probeByConnectionId.set(connection.id, {
publishConnectionProbe(connection.id, {
status: "unavailable",
latencyMs: null,
});
publishProbeState();
}
} finally {
if (connectedClient && shouldCloseClient) {
@@ -2437,6 +2490,16 @@ export class HostRuntimeStore {
}));
}
async setHostIcon(serverId: string, icon: HostIcon | null): Promise<void> {
await this.updateHostAppearance(serverId, (host) => {
const { icon: _previousIcon, ...rest } = host.appearance;
return {
...host,
appearance: icon ? { ...rest, icon } : rest,
};
});
}
async setHostBadgeDisplay(serverId: string, badgeDisplay: HostBadgeDisplay): Promise<void> {
await this.updateHostAppearance(serverId, (host) => ({
...host,
@@ -2444,6 +2507,16 @@ export class HostRuntimeStore {
}));
}
refreshActiveLatencies(serverIds?: readonly string[]): void {
const targets = serverIds ?? this.hosts.map((host) => host.serverId);
for (const serverId of targets) {
const controller = this.controllers.get(serverId);
if (controller) {
void controller.refreshActiveLatency();
}
}
}
private updateHostAppearance(
serverId: string,
apply: (host: HostProfile) => HostProfile,
@@ -3055,19 +3128,12 @@ export class HostRuntimeStore {
const directory = this.directorySyncByServer.get(serverId);
if (!directory) throw new Error(`Unknown host runtime for serverId ${serverId}`);
const owner = useSessionStore.getState().sessions[serverId]?.viewedTimelineSync;
// A page served before a rewind this client applied is asked for again. Seqs only grow within
// an epoch, so the next page includes the rewind unless another one landed meanwhile.
for (let attempt = 1; ; attempt += 1) {
const page = await directory.fetchTimeline(agentId, request);
if (!owner || useSessionStore.getState().sessions[serverId]?.viewedTimelineSync !== owner) {
return page;
}
const page = await directory.fetchTimeline(agentId, request);
if (owner && useSessionStore.getState().sessions[serverId]?.viewedTimelineSync === owner) {
owner.flushStreamAgent(agentId);
if (owner.applyTimelineResponse(page) === "applied") return page;
if (attempt === MAX_STALE_TIMELINE_PAGE_ATTEMPTS) {
throw new Error(`Timeline page for ${agentId} stayed behind a rewind`);
}
owner.applyTimelineResponse(page);
}
return page;
}
createViewedTimelineOwner(
@@ -3304,6 +3370,7 @@ export interface HostMutations {
beginLinkPairing: () => LinkPairing;
renameHost: (serverId: string, label: string) => Promise<void>;
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
removeHost: (serverId: string) => Promise<void>;
removeConnection: (serverId: string, connectionId: string) => Promise<void>;
@@ -3319,6 +3386,7 @@ export function useHostMutations(): HostMutations {
beginLinkPairing: () => store.beginLinkPairing(),
renameHost: (serverId, label) => store.renameHost(serverId, label),
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
setHostBadgeDisplay: (serverId, badgeDisplay) =>
store.setHostBadgeDisplay(serverId, badgeDisplay),
removeHost: (serverId) => store.removeHost(serverId),
@@ -189,7 +189,7 @@ function timelineItem(text = "Cached"): StreamItem {
id: "message-1",
text,
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
};
}
@@ -840,7 +840,7 @@ describe("ReplicaCache", () => {
version: 1,
data: { passed: 4, failed: 0 },
timestamp: new Date("2026-07-18T08:02:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
};
writer.commitTimeline(SERVER_ID, "agent-1", {
agentId: "agent-1",
@@ -885,32 +885,6 @@ describe("ReplicaCache", () => {
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("keeps where each cached row started, and refetches a timeline cached without it", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
const updatedAfterItStarted: StreamItem = {
...timelineItem(),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 9 },
};
writer.commitTimeline(SERVER_ID, "agent-1", { ...timeline(), items: [updatedAfterItStarted] });
await writer.flush();
expect((await createCache(storage).readTimeline(SERVER_ID, "agent-1"))?.items).toEqual([
updatedAfterItStarted,
]);
const row = requireTimelineRow(storage);
const payload = JSON.parse(row.payload) as {
items: Array<{ timelineCursor?: Record<string, unknown> }>;
};
delete payload.items[0]?.timelineCursor?.anchorSeq;
storage.rows.set(`${row.serverId}:${row.kind}:${row.id}`, {
...row,
payload: JSON.stringify(payload),
});
expect(await createCache(storage).readTimeline(SERVER_ID, "agent-1")).toBeUndefined();
});
it("refetches old cached Markdown fragments instead of offering them as whole messages", async () => {
const storage = new MemoryStorage();
const writer = createCache(storage);
@@ -1381,7 +1355,7 @@ it("retains semantic agent messages across disk-cache reconstruction", async ()
kind: "tool_call",
id: "delivery",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch-1", seq: 12 },
payload: {
source: "agent",
data: {
@@ -22,7 +22,6 @@ import {
isUnreconciledLocalUserMessage,
type AgentToolCallData,
type StreamItem,
type TimelinePosition,
} from "@/types/stream";
import type { UnsettledTurn } from "@/timeline/turn-liveness";
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
@@ -83,15 +82,7 @@ const IsoDateSchema = z.iso.datetime();
const TimelinePositionSchema = z.strictObject({
epoch: z.string(),
seq: z.number().int().nonnegative(),
// COMPAT(timelineRewindOperations): absent on caches written before rows were anchored, added in
// v0.14.1, remove after 2027-05-10. Such a cache is not restored; the chat loads its tail instead.
anchorSeq: z.number().int().nonnegative().optional(),
});
type StoredTimelinePosition = z.infer<typeof TimelinePositionSchema>;
function isAnchored(position: StoredTimelinePosition | undefined): boolean {
return position === undefined || position.anchorSeq !== undefined;
}
const PluginTimelineDataSchema: z.ZodType<PluginTimelineData> = z.lazy(() =>
z.union([
z.null(),
@@ -432,10 +423,6 @@ function deserializeTimeline(stored: StoredTimeline | null): CachedTimeline | nu
if (!stored) {
return null;
}
// A rewind retires rows by anchor, so an unanchored row could not be retired.
if (!stored.items.every((item) => isAnchored(item.timelineCursor))) {
return null;
}
return {
agentId: stored.agentId,
items: stored.items.map(deserializeTimelineItem),
@@ -552,20 +539,11 @@ function serializeTimelineItem(item: StreamItem): StoredTimelineItem | null {
}
}
function anchoredPosition(position: StoredTimelinePosition | undefined): {
timelineCursor?: TimelinePosition;
} {
if (!position || position.anchorSeq === undefined) return {};
return {
timelineCursor: { epoch: position.epoch, seq: position.seq, anchorSeq: position.anchorSeq },
};
}
function deserializeTimelineItem(item: StoredTimelineItem): StreamItem {
if (item.kind === "plugin") {
return {
id: item.id,
...anchoredPosition(item.timelineCursor),
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
kind: item.kind,
@@ -584,7 +562,7 @@ function deserializeBuiltinTimelineItem(
): StreamItem {
const base = {
id: item.id,
...anchoredPosition(item.timelineCursor),
...(item.timelineCursor ? { timelineCursor: item.timelineCursor } : {}),
...(item.turnId ? { turnId: item.turnId } : {}),
timestamp: new Date(item.timestamp),
};
@@ -438,7 +438,7 @@ export function useNewWorkspaceForm(props: NewWorkspaceFormProps): ReactElement
searchable={false}
title={t("newWorkspace.fields.host")}
desktopPlacement="bottom-start"
desktopMinWidth={200}
desktopMinWidth={320}
hostOptionTestID={hostOptionTestID}
>
<FieldTrigger
+1 -1
View File
@@ -907,7 +907,7 @@ function HostPicker({
showActiveConnection
searchable={false}
title={t("settings.hostPicker.switchHost")}
desktopMinWidth={240}
desktopMinWidth={328}
addHostTestID="settings-add-host"
hostOptionTestID={hostOptionTestID}
>
@@ -4,7 +4,12 @@ import { useTranslation } from "react-i18next";
import { Pressable, Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { Pencil } from "lucide-react-native";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { DropdownTrigger } from "@/components/ui/dropdown-trigger";
import { AdaptiveRenameModal } from "@/components/rename-modal";
import { WorkspaceMetaRow } from "@/components/sidebar/workspace-meta-row";
@@ -13,12 +18,18 @@ import { SettingsSection } from "@/components/settings/headings/settings-section
import {
HOST_BADGE_DISPLAYS,
HOST_COLORS,
HOST_ICONS,
normalizeDetectedHostIcon,
resolveHostBadgeDisplay,
resolveHostIcon,
type HostBadgeDisplay,
type HostColor,
type HostIcon,
} from "@/hosts/appearance";
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
import { useLocalDaemonServerIdState } from "@/hooks/use-is-local-daemon";
import { useHostMutations } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { identityColor } from "@/styles/identity-colors";
import { settingsStyles } from "@/styles/settings";
import { ICON_SIZE, type Theme } from "@/styles/theme";
@@ -76,10 +87,112 @@ function colorLabel(t: TFunction, color: HostColor): string {
return t(`settings.host.appearance.color.options.${color}`);
}
function iconLabel(t: TFunction, icon: HostIcon): string {
return t(`settings.host.appearance.icon.options.${icon}`);
}
function autoIconLabel(t: TFunction, detectedIcon: HostIcon | null): string {
if (detectedIcon) {
return t("settings.host.appearance.icon.autoDetected", {
icon: iconLabel(t, detectedIcon),
});
}
return t("settings.host.appearance.icon.auto");
}
function badgeDisplayLabel(t: TFunction, display: HostBadgeDisplay): string {
return t(`settings.host.appearance.badge.options.${display}`);
}
function IconMenuItem({
icon,
color,
selected,
onChange,
}: {
icon: HostIcon;
color: HostColor;
selected: boolean;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const handleSelect = useCallback(() => onChange(icon), [icon, onChange]);
const leading = useMemo(
() => <HostIconGlyph icon={icon} color={color} size={ICON_SIZE.sm} />,
[color, icon],
);
return (
<DropdownMenuItem selected={selected} onSelect={handleSelect} leading={leading}>
{iconLabel(t, icon)}
</DropdownMenuItem>
);
}
function IconRow({
icon,
detectedIcon,
resolvedIcon,
color,
onChange,
}: {
icon: HostIcon | null;
detectedIcon: HostIcon | null;
resolvedIcon: HostIcon;
color: HostColor;
onChange: (icon: HostIcon | null) => void;
}) {
const { t } = useTranslation();
const autoLabel = autoIconLabel(t, detectedIcon);
const selectedLabel = icon ? iconLabel(t, icon) : autoLabel;
const handleSelectAuto = useCallback(() => onChange(null), [onChange]);
const triggerLeading = useMemo(
() => <HostIconGlyph icon={resolvedIcon} color={color} size={ICON_SIZE.sm} />,
[color, resolvedIcon],
);
const autoLeading = useMemo(
() => <HostIconGlyph icon={detectedIcon ?? "server"} color={color} size={ICON_SIZE.sm} />,
[color, detectedIcon],
);
return (
<View style={[settingsStyles.row, settingsStyles.rowBorder]}>
<View style={settingsStyles.rowContent}>
<Text style={settingsStyles.rowTitle}>{t("settings.host.appearance.icon.label")}</Text>
</View>
<DropdownMenu>
<DropdownTrigger
testID="host-appearance-icon"
accessibilityRole="button"
accessibilityLabel={t("settings.host.appearance.icon.accessibilityLabel", {
value: selectedLabel,
})}
leading={triggerLeading}
>
{selectedLabel}
</DropdownTrigger>
<DropdownMenuContent side="bottom" align="end" width={220}>
<DropdownMenuItem
selected={icon === null}
onSelect={handleSelectAuto}
leading={autoLeading}
>
{autoLabel}
</DropdownMenuItem>
<DropdownMenuSeparator />
{HOST_ICONS.map((option) => (
<IconMenuItem
key={option}
icon={option}
color={color}
selected={option === icon}
onChange={onChange}
/>
))}
</DropdownMenuContent>
</DropdownMenu>
</View>
);
}
function ColorSwatch({ color }: { color: HostColor }) {
const swatchStyle = useMemo(
() => [styles.swatch, color === "none" ? null : { backgroundColor: identityColor(color) }],
@@ -205,9 +318,11 @@ function BadgeDisplayMenuItem({
*/
function BadgePreview({
host,
resolvedIcon,
badgeDisplay,
}: {
host: HostProfile;
resolvedIcon: HostIcon;
badgeDisplay: HostBadgeDisplay;
}) {
const { t } = useTranslation();
@@ -219,9 +334,10 @@ function BadgePreview({
serverId: host.serverId,
label: host.label,
color: host.appearance.color,
icon: resolvedIcon,
showLabel: badgeDisplay === "name",
},
[badgeDisplay, host.serverId, host.label, host.appearance.color],
[badgeDisplay, host.serverId, host.label, host.appearance.color, resolvedIcon],
);
// The real sidebar row, so the preview can't drift from what the setting actually does.
return (
@@ -244,8 +360,14 @@ function BadgePreview({
export function HostAppearanceSection({ host }: { host: HostProfile }) {
const { t } = useTranslation();
const toast = useToast();
const { setHostColor, setHostBadgeDisplay } = useHostMutations();
const { setHostColor, setHostIcon, setHostBadgeDisplay } = useHostMutations();
const localDaemon = useLocalDaemonServerIdState();
const detectedMachineKind = useSessionStore(
(state) => state.sessions[host.serverId]?.serverInfo?.machineKind ?? null,
);
const detectedIcon = normalizeDetectedHostIcon(detectedMachineKind);
const selectedIcon = normalizeDetectedHostIcon(host.appearance.icon);
const resolvedIcon = resolveHostIcon({ appearance: host.appearance, detectedMachineKind });
const isLocalHost = localDaemon.status === "resolved" && localDaemon.serverId === host.serverId;
const badgeDisplay = resolveHostBadgeDisplay({
appearance: host.appearance,
@@ -263,6 +385,16 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
},
[host.serverId, setHostColor, t, toast],
);
const handleIconChange = useCallback(
async (icon: HostIcon | null) => {
try {
await setHostIcon(host.serverId, icon);
} catch {
toast.error(t("errors.unableToSave"));
}
},
[host.serverId, setHostIcon, t, toast],
);
const handleBadgeDisplayChange = useCallback(
async (next: HostBadgeDisplay) => {
try {
@@ -288,11 +420,18 @@ export function HostAppearanceSection({ host }: { host: HostProfile }) {
<HostRenameButton host={host} />
</View>
</View>
<IconRow
icon={selectedIcon}
detectedIcon={detectedIcon}
resolvedIcon={resolvedIcon}
color={host.appearance.color}
onChange={handleIconChange}
/>
<ColorRow color={host.appearance.color} onChange={handleColorChange} />
{badgeDisplay === null ? null : (
<>
<BadgeDisplayRow badgeDisplay={badgeDisplay} onChange={handleBadgeDisplayChange} />
<BadgePreview host={host} badgeDisplay={badgeDisplay} />
<BadgePreview host={host} resolvedIcon={resolvedIcon} badgeDisplay={badgeDisplay} />
</>
)}
</View>
@@ -2188,10 +2188,11 @@ function WorkspaceScreenContent({
toast.show(t("workspace.tabs.toasts.reloadingAgent"), { durationMs: null });
try {
const refreshed = await client.refreshAgent(agentId);
// Send the existing cursor: Reload agent keeps the history, so the server
// returns only the rows it added. When the history was imported again
// under a new epoch, the cursor reads as stale and the server resets.
await client.refreshAgent(agentId);
// Send the existing cursor so the server detects the new epoch and
// returns reset:true. Without a cursor, the server returns reset:false
// and the client takes the incremental path, where new-epoch rows are
// dropped against the stale cursor.
const sessionState = useSessionStore.getState().sessions[normalizedServerId];
const currentCursor = sessionState?.agentTimelineCursor.get(agentId);
await getHostRuntimeStore().fetchAgentTimeline(normalizedServerId, agentId, {
@@ -2200,13 +2201,7 @@ function WorkspaceScreenContent({
? { cursor: { epoch: currentCursor.epoch, seq: currentCursor.endSeq } }
: {}),
});
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
} else {
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
}
toast.show(t("workspace.tabs.toasts.reloadedAgent"), { variant: "success" });
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("workspace.tabs.toasts.failedToReloadAgent"),
+9 -32
View File
@@ -293,6 +293,7 @@ export interface DaemonServerInfo {
serverId: string;
hostname: string | null;
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
@@ -303,6 +304,7 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
serverId: serverInfo.serverId,
hostname: serverInfo.hostname ?? null,
version: serverInfo.version ?? null,
...(serverInfo.machineKind !== undefined ? { machineKind: serverInfo.machineKind } : {}),
...(serverInfo.desktopManaged !== undefined
? { desktopManaged: serverInfo.desktopManaged }
: {}),
@@ -322,12 +324,6 @@ export interface AgentTimelineCursorState {
}>;
}
/** The latest conversation rewind applied to an agent's history, by its sequence number. */
export interface AgentTimelineRewind {
epoch: string;
seq: number;
}
export type AgentTimelineState =
| { status: "cold" }
| { status: "painted"; items: StreamItem[] }
@@ -502,7 +498,6 @@ export interface SessionState {
agentTimelineUnsettledTurn: Map<string, UnsettledTurn>;
agentTimelineHasOlder: Map<string, boolean>;
agentTimelineHasNewer: Map<string, boolean>;
agentTimelineLatestRewind: Map<string, AgentTimelineRewind>;
agentTimelineOlderFetchInFlight: Map<string, boolean>;
historySyncGeneration: number;
agentHistorySyncGeneration: Map<string, number>;
@@ -622,12 +617,6 @@ interface SessionStoreActions {
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
) => void;
/** Records a rewind applied to the agent's history; an older one of the same history is ignored. */
recordAgentTimelineRewind: (
serverId: string,
agentId: string,
rewind: AgentTimelineRewind,
) => void;
setAgentTimelineOlderFetchInFlight: (
serverId: string,
state: Map<string, boolean> | ((prev: Map<string, boolean>) => Map<string, boolean>),
@@ -764,7 +753,6 @@ function createInitialSessionState(
agentTimelineUnsettledTurn: new Map(),
agentTimelineHasOlder: new Map(),
agentTimelineHasNewer: new Map(),
agentTimelineLatestRewind: new Map(),
agentTimelineOlderFetchInFlight: new Map(),
historySyncGeneration: 0,
agentHistorySyncGeneration: new Map(),
@@ -800,6 +788,7 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo: SessionState["serverInfo"] | undefined;
nextHostname: string | null;
nextVersion: string | null;
nextMachineKind: string | null;
nextDesktopManaged: boolean | undefined;
nextCapabilities: ServerCapabilities | undefined;
nextFeatures: ServerInfoStatusPayload["features"] | undefined;
@@ -809,16 +798,19 @@ function isSessionServerInfoUnchanged(input: {
currentServerInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
} = input;
const prevHostname = currentServerInfo?.hostname?.trim() || null;
const prevVersion = currentServerInfo?.version?.trim() || null;
const prevMachineKind = currentServerInfo?.machineKind?.trim() || null;
return (
currentServerInfo?.serverId === input.nextServerId &&
prevHostname === nextHostname &&
prevVersion === nextVersion &&
prevMachineKind === nextMachineKind &&
currentServerInfo?.desktopManaged === nextDesktopManaged &&
areServerCapabilitiesEqual(currentServerInfo?.capabilities, nextCapabilities) &&
areServerInfoFeaturesEqual(currentServerInfo?.features, nextFeatures)
@@ -956,6 +948,7 @@ export const useSessionStore = create<SessionStore>()(
const nextHostname = info.hostname?.trim() || null;
const nextVersion = info.version?.trim() || null;
const nextMachineKind = info.machineKind?.trim() || null;
const nextDesktopManaged = info.desktopManaged;
const nextCapabilities = info.capabilities;
const nextFeatures = info.features;
@@ -965,6 +958,7 @@ export const useSessionStore = create<SessionStore>()(
currentServerInfo: session.serverInfo,
nextHostname,
nextVersion,
nextMachineKind,
nextDesktopManaged,
nextCapabilities,
nextFeatures,
@@ -984,6 +978,7 @@ export const useSessionStore = create<SessionStore>()(
serverId: info.serverId,
hostname: nextHostname,
version: nextVersion,
...(nextMachineKind !== null ? { machineKind: nextMachineKind } : {}),
...(nextDesktopManaged !== undefined
? { desktopManaged: nextDesktopManaged }
: {}),
@@ -1406,24 +1401,6 @@ export const useSessionStore = create<SessionStore>()(
});
},
recordAgentTimelineRewind: (serverId, agentId, rewind) => {
set((prev) => {
const session = prev.sessions[serverId];
if (!session) return prev;
const current = session.agentTimelineLatestRewind.get(agentId);
if (current && current.epoch === rewind.epoch && current.seq >= rewind.seq) return prev;
const next = new Map(session.agentTimelineLatestRewind);
next.set(agentId, rewind);
return {
...prev,
sessions: {
...prev.sessions,
[serverId]: { ...session, agentTimelineLatestRewind: next },
},
};
});
},
setAgentTimelineOlderFetchInFlight: (serverId, state) => {
set((prev) => {
const session = prev.sessions[serverId];
+1 -230
View File
@@ -39,7 +39,7 @@ function item(id: string, text: string, seq: number): StreamItem {
id,
text,
timestamp: new Date("2026-08-26T10:00:00.000Z"),
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch-1", seq },
};
}
@@ -579,235 +579,6 @@ describe("viewed timeline persistence", () => {
});
});
describe("conversation rewind through the owner", () => {
const page = {
requestId: "page-1",
agentId: AGENT_ID,
agent: null,
direction: "tail",
projection: "projected",
reset: false,
epoch: "epoch-1",
error: null,
hasNewer: false,
hasOlder: false,
staleCursor: false,
gap: false,
} as const;
function entry(seq: number, type: "user_message" | "assistant_message", text: string) {
return {
seqStart: seq,
seqEnd: seq,
sourceSeqRanges: [{ startSeq: seq, endSeq: seq }],
collapsed: [],
provider: "codex",
item: { type, text },
timestamp: `2026-08-26T10:00:0${seq}.000Z`,
};
}
function texts(items: readonly StreamItem[]): string[] {
return items.flatMap((row) =>
row.kind === "user_message" || row.kind === "assistant_message" ? [row.text] : [],
);
}
function viewed(): string[] {
const session = useSessionStore.getState().sessions[SERVER_ID];
const timeline = selectAgentTimelineState(session, AGENT_ID);
const tail = timeline.status === "cold" ? [] : timeline.items;
return texts([...tail, ...(session?.agentStreamHead.get(AGENT_ID) ?? [])]);
}
function latestRewind() {
return useSessionStore.getState().sessions[SERVER_ID]?.agentTimelineLatestRewind.get(AGENT_ID);
}
it("retires B from the viewed and persisted timeline without refetching", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const commits: CachedTimeline[] = [];
const owner = createOwner({
readTimeline: async () => undefined,
commitTimeline: (_serverId, _agentId, timeline) => commits.push(timeline),
});
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
});
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: 5,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:05.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: 6,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(texts(commits.at(-1)?.items ?? [])).toEqual(["A", "reply A", "C"]);
expect(commits.at(-1)?.range).toMatchObject({ epoch: "epoch-1", endSeq: 6 });
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
it("brings a second client that loads after the rewind to the same conversation", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(6, "user_message", "C"),
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
expect(latestRewind()).toEqual({ epoch: "epoch-1", seq: 5 });
owner.dispose();
});
function liveRewindOfB(owner: ViewedTimelineOwner, retirement: { seq: number }): void {
owner.applyStreamEvent(AGENT_ID, {
event: { type: "rewind", retireFromSeq: 3 },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:06.000Z"),
});
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "codex",
item: { type: "user_message", text: "C", messageId: "c" },
} as AgentStreamEventPayload,
seq: retirement.seq + 1,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:07.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
}
/** A, reply A, B, reply B as a page served before B was rewound. */
const pageServedBeforeTheRewind: Parameters<ViewedTimelineOwner["applyTimelineResponse"]>[0] = {
...page,
direction: "before",
hasOlder: false,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
entry(3, "user_message", "B"),
entry(4, "assistant_message", "reply B"),
],
};
function loadTheEndOfB(owner: ViewedTimelineOwner): void {
owner.applyTimelineResponse({
...page,
hasOlder: true,
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { epoch: "epoch-1", seq: 5 },
endCursor: { epoch: "epoch-1", seq: 5 },
entries: [entry(5, "assistant_message", "more of B")],
});
}
it("refuses an older page served before the rewind and takes the one served after it", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
expect(viewed()).toEqual(["C"]);
const outcome = owner.applyTimelineResponse(pageServedBeforeTheRewind);
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
// Retired rows count as covered, so the page reaches the loaded start.
endCursor: { epoch: "epoch-1", seq: 4 },
entries: [entry(1, "user_message", "A"), entry(2, "assistant_message", "reply A")],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
it("refuses a prompt jump window served before the rewind", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
loadTheEndOfB(owner);
liveRewindOfB(owner, { seq: 6 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
mergeWindow: true,
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.dispose();
});
it("refuses a first page served before a rewind that reached the chat while it loaded", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
const owner = createOwner({ readTimeline: async () => undefined, commitTimeline: () => {} });
liveRewindOfB(owner, { seq: 5 });
const outcome = owner.applyTimelineResponse({
...pageServedBeforeTheRewind,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
});
expect(viewed()).toEqual(["C"]);
expect(outcome).toBe("stale");
owner.applyTimelineResponse({
...page,
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { epoch: "epoch-1", seq: 1 },
endCursor: { epoch: "epoch-1", seq: 6 },
entries: [
entry(1, "user_message", "A"),
entry(2, "assistant_message", "reply A"),
{
...entry(6, "user_message", "C"),
item: { type: "user_message", text: "C", messageId: "c" },
},
],
retirements: [{ seq: 5, retireFromSeq: 3 }],
});
expect(viewed()).toEqual(["A", "reply A", "C"]);
owner.dispose();
});
});
describe("turn boundaries", () => {
it("commits a turn's final reply before the turn stops running", () => {
useSessionStore.getState().initializeSession(SERVER_ID, null);
@@ -398,7 +398,7 @@ describe("processTimelineResponse", () => {
messageId: "provider-message",
text: "local prompt",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
turnId: "turn-1",
});
const hello = createUserMessage({
@@ -406,7 +406,7 @@ describe("processTimelineResponse", () => {
clientMessageId: "hello-client",
text: "hello",
timestamp: new Date(1500),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
turnId: "turn-1",
});
const currentTail = [canonical, makeAssistantItem("existing tail", "existing-tail"), hello];
@@ -456,7 +456,7 @@ describe("processTimelineResponse", () => {
id: "stale-history",
text: "stale history",
timestamp: new Date(1040),
timelineCursor: { epoch: "epoch-1", seq: 40, anchorSeq: 40 },
timelineCursor: { epoch: "epoch-1", seq: 40 },
},
],
currentCursor: { epoch: "epoch-1", startSeq: 1, endSeq: 40 },
@@ -484,11 +484,11 @@ describe("processTimelineResponse", () => {
const unresolved = makeSubmittedUserMessage("unresolved prompt", "client-unresolved");
const coveredLive: StreamItem = {
...makeAssistantItem("covered live", "covered-live"),
timelineCursor: { epoch: "epoch-1", seq: 235, anchorSeq: 235 },
timelineCursor: { epoch: "epoch-1", seq: 235 },
};
const newerLive: StreamItem = {
...makeAssistantItem("newer live", "newer-live"),
timelineCursor: { epoch: "epoch-1", seq: 245, anchorSeq: 245 },
timelineCursor: { epoch: "epoch-1", seq: 245 },
};
const result = processTimelineResponse({
@@ -573,7 +573,7 @@ describe("processTimelineResponse", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 40 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
}),
]);
});
@@ -745,7 +745,7 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -775,7 +775,7 @@ describe("processTimelineResponse", () => {
expect(getAgentToolCalls([...result.tail, ...result.head])).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
payload: expect.objectContaining({
data: expect.objectContaining({ callId, status: "completed" }),
}),
@@ -796,7 +796,7 @@ describe("processTimelineResponse", () => {
},
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -831,7 +831,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "todo_list")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
items: [{ text: "Verify hydration", completed: true }],
}),
]);
@@ -847,7 +847,7 @@ describe("processTimelineResponse", () => {
item: { type: "compaction", status: "completed", trigger: "auto", preTokens: 1200 },
} as AgentStreamEventPayload,
timestamp: new Date(2000),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
{ source: "canonical" },
@@ -879,7 +879,7 @@ describe("processTimelineResponse", () => {
expect([...result.tail, ...result.head].filter((item) => item.kind === "compaction")).toEqual([
expect.objectContaining({
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
status: "completed",
trigger: "auto",
preTokens: 1200,
@@ -918,7 +918,7 @@ describe("processTimelineResponse", () => {
messageId: "assistant-live",
text: " continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
],
isInitializing: true,
@@ -946,7 +946,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
});
it("keeps assistant segments separate when a live tool sits between them", () => {
@@ -963,12 +963,12 @@ describe("processTimelineResponse", () => {
}).item,
} as AgentStreamEventPayload,
timestamp: new Date(2101),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
{
event: makeAssistantTimelineEvent("after tool", messageId),
timestamp: new Date(2102),
timelineCursor: { epoch: "epoch-1", seq: 102, anchorSeq: 102 },
timelineCursor: { epoch: "epoch-1", seq: 102 },
},
],
{ source: "canonical" },
@@ -1019,7 +1019,7 @@ describe("processTimelineResponse", () => {
id: "assistant-live",
text: "canonical prefix continuation",
timestamp: new Date(2001),
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
},
],
isInitializing: true,
@@ -1038,7 +1038,7 @@ describe("processTimelineResponse", () => {
);
expect(assistants).toHaveLength(1);
expect(assistants[0]?.text).toBe("canonical prefix continuation");
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101, anchorSeq: 100 });
expect(assistants[0]?.timelineCursor).toEqual({ epoch: "epoch-1", seq: 101 });
});
it("keeps a canonical live user row newer than the bootstrap page", () => {
@@ -1060,7 +1060,7 @@ describe("processTimelineResponse", () => {
});
expect(live.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 101, anchorSeq: 101 },
timelineCursor: { epoch: "epoch-1", seq: 101 },
});
const result = processTimelineResponse({
@@ -1123,7 +1123,7 @@ describe("processTimelineResponse", () => {
kind: "user_message",
clientMessageId: "client-message-1",
messageId: "provider-message-1",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
});
});
@@ -2808,7 +2808,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
makeSubmittedUserMessage("pending submission", "pending-submission"),
],
@@ -2886,14 +2886,14 @@ describe("processTimelineResponse", () => {
id: "oldest",
text: "oldest",
timestamp: new Date(1000),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{
kind: "user_message",
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
];
@@ -2935,7 +2935,7 @@ describe("processTimelineResponse", () => {
id: "newest",
text: "newest",
timestamp: new Date(100_000),
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 100 },
},
...(lane === "tail" ? [pending] : []),
],
@@ -2976,13 +2976,9 @@ describe("processTimelineResponse", () => {
{
text: "local pending prompt",
messageId: "canonical-message",
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
},
{
text: "newest",
messageId: undefined,
timelineCursor: { epoch: "epoch-1", seq: 100, anchorSeq: 100 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
{ text: "newest", messageId: undefined, timelineCursor: { epoch: "epoch-1", seq: 100 } },
],
head: [],
acknowledgedClientMessageIds: [clientMessageId],
@@ -2996,7 +2992,7 @@ describe("processTimelineResponse", () => {
{
event: makeToolCallTimelineEvent("call-1"),
timestamp: new Date(500),
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
],
{ source: "canonical" },
@@ -3042,7 +3038,7 @@ describe("processTimelineResponse", () => {
{
callId: "call-1",
status: "completed",
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
]);
});
@@ -3054,7 +3050,7 @@ describe("processTimelineResponse", () => {
...makeAssistantItem("projected response", "loaded-assistant"),
messageId: "assistant-message",
timestamp,
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 500 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
];
const result = processTimelineResponse({
@@ -3104,7 +3100,7 @@ describe("processTimelineResponse", () => {
id: "loaded-assistant",
text: "projected response",
messageId: "assistant-message",
timelineCursor: { epoch: "epoch-1", seq: 500, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 500 },
},
]);
});
@@ -3116,7 +3112,7 @@ describe("processTimelineResponse", () => {
id: "current-200",
text: "current-200",
timestamp: new Date(3200),
timelineCursor: { epoch: "epoch-1", seq: 200, anchorSeq: 200 },
timelineCursor: { epoch: "epoch-1", seq: 200 },
},
];
const existingCursor: TimelineCursor = {
@@ -3223,7 +3219,7 @@ describe("processTimelineResponse", () => {
const currentTail = [
{
...makeAssistantItem("newer chunk", "assistant-newer"),
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3 },
},
];
const existingCursor: TimelineCursor = {
@@ -3250,7 +3246,7 @@ describe("processTimelineResponse", () => {
expect(result.tail[0]).toEqual(
expect.objectContaining({
id: "assistant-newer",
timelineCursor: { epoch: "epoch-1", seq: 3, anchorSeq: 3 },
timelineCursor: { epoch: "epoch-1", seq: 3 },
}),
);
expect(result.cursor).toEqual({
@@ -3690,7 +3686,7 @@ describe("processAgentStreamEvent", () => {
expect.objectContaining({
kind: "assistant_message",
text: "[System Error] failed",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
}),
]);
});
@@ -3937,7 +3933,7 @@ describe("processAgentStreamEvent", () => {
expect(getUserTexts(result.head)).toEqual(["live before bootstrap"]);
expect(result.head[0]).toMatchObject({
kind: "user_message",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
});
expect(result.cursorChanged).toBe(false);
expect(result.cursor).toBeNull();
@@ -3972,7 +3968,7 @@ describe("processAgentStreamEvent", () => {
clientMessageId: "client-message-1",
messageId: "provider-message-1",
text: "submitted before bootstrap",
timelineCursor: { epoch: "epoch-1", seq: 51, anchorSeq: 51 },
timelineCursor: { epoch: "epoch-1", seq: 51 },
}),
]);
});
@@ -4563,279 +4559,6 @@ describe("createAgentStreamReducerQueue", () => {
});
});
// ---------------------------------------------------------------------------
// Conversation rewind: A, B, rewind B, C
// ---------------------------------------------------------------------------
describe("conversation rewind", () => {
const rewindB = { seq: 5, retireFromSeq: 3 };
function loadAB(): { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor } {
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 1 },
endCursor: { seq: 4 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(3, "B", "user_message"),
makeTimelineEntry(4, "reply B"),
],
},
});
if (!result.cursor) throw new Error("expected a loaded range");
return { tail: result.tail, head: result.head, cursor: result.cursor };
}
function live(
state: { tail: StreamItem[]; head: StreamItem[]; cursor: TimelineCursor },
events: AgentStreamReducerEvent[],
) {
const result = processAgentStreamEvents({
events,
currentTail: state.tail,
currentHead: state.head,
currentCursor: state.cursor,
hasAuthoritativeBaseline: true,
});
return {
tail: result.tail,
head: result.head,
cursor: result.cursor ?? state.cursor,
sideEffects: result.sideEffects,
};
}
function rewindEvent(retirement: { seq: number; retireFromSeq: number }) {
return {
event: { type: "rewind" as const, retireFromSeq: retirement.retireFromSeq },
seq: retirement.seq,
epoch: "epoch-1",
timestamp: new Date(1000 + retirement.seq),
};
}
const promptC = [
makeStreamReducerEvent(makeTimelineEvent("C", "user_message"), 6),
makeStreamReducerEvent(makeTimelineEvent("reply C"), 7),
];
function conversation(state: { tail: StreamItem[]; head: StreamItem[] }) {
return [...state.tail, ...state.head].map((item) =>
item.kind === "user_message" || item.kind === "assistant_message" ? item.text : item.kind,
);
}
it("retires B in place, keeps A mounted, and shows C once", () => {
const loaded = loadAB();
const [promptA, replyA] = loaded.tail;
const rewound = live(loaded, [rewindEvent(rewindB), ...promptC]);
expect(conversation(rewound)).toEqual(["A", "reply A", "C", "reply C"]);
expect(rewound.tail[0]).toBe(promptA);
expect(rewound.tail[1]).toBe(replyA);
expect(rewound.cursor).toMatchObject({ epoch: "epoch-1", startSeq: 1, endSeq: 7 });
expect(rewound.sideEffects).toEqual([]);
});
it("ignores a duplicate rewind so C is not retired", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const replayed = live(rewound, [rewindEvent(rewindB)]);
expect(conversation(replayed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(replayed.cursor.endSeq).toBe(7);
});
it("does not let an old page resurrect B after the rewind applied", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB), ...promptC]);
const stale = processTimelineResponse({
...baseTimelineInput,
currentTail: rewound.tail,
currentHead: rewound.head,
currentCursor: rewound.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 4, nextSeq: 5 },
startCursor: { seq: 3 },
endCursor: { seq: 4 },
entries: [makeTimelineEntry(3, "B", "user_message"), makeTimelineEntry(4, "reply B")],
},
});
expect(conversation(stale)).toEqual(["A", "reply A", "C", "reply C"]);
expect(stale.cursorChanged).toBe(false);
});
it("drops a late live delivery for the retired range", () => {
const rewound = live(loadAB(), [rewindEvent(rewindB)]);
const late = live(rewound, [makeStreamReducerEvent(makeTimelineEvent("late B"), 4)]);
expect(conversation(late)).toEqual(["A", "reply A"]);
});
it("catches up through a page that only carries the retirement", () => {
const loaded = loadAB();
const caughtUp = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "after",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 5 },
endCursor: { seq: 5 },
entries: [],
retirements: [rewindB],
},
});
if (!caughtUp.cursor) throw new Error("expected a loaded range");
expect(conversation(caughtUp)).toEqual(["A", "reply A"]);
expect(caughtUp.cursor.endSeq).toBe(5);
expect(caughtUp.sideEffects).not.toContainEqual(expect.objectContaining({ type: "catch_up" }));
const continued = live({ ...caughtUp, cursor: caughtUp.cursor }, promptC);
expect(conversation(continued)).toEqual(["A", "reply A", "C", "reply C"]);
});
it("converges after reconnect from a resume page that crosses the rewind", () => {
const loaded = loadAB();
const resumed = processTimelineResponse({
...baseTimelineInput,
currentTail: loaded.tail,
currentHead: loaded.head,
currentCursor: loaded.cursor,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 7, nextSeq: 8 },
startCursor: { seq: 1 },
endCursor: { seq: 7 },
entries: [
makeTimelineEntry(1, "A", "user_message"),
makeTimelineEntry(2, "reply A"),
makeTimelineEntry(6, "C", "user_message"),
makeTimelineEntry(7, "reply C"),
],
retirements: [rewindB],
},
});
expect(conversation(resumed)).toEqual(["A", "reply A", "C", "reply C"]);
expect(resumed.tail[0]).toBe(loaded.tail[0]);
expect(resumed.cursor).toMatchObject({ endSeq: 7 });
});
it("recovers a rewind that skips past the loaded end", () => {
const loaded = loadAB();
const gapped = live(loaded, [rewindEvent({ seq: 9, retireFromSeq: 3 })]);
expect(conversation(gapped)).toEqual(["A", "reply A", "B", "reply B"]);
expect(gapped.sideEffects).toEqual([
{ type: "catch_up", cursor: { epoch: "epoch-1", endSeq: 4 } },
]);
});
it("keeps an A row whose late update carries a seq inside B's range", () => {
const loaded = loadAB();
const [promptA, replyA, ...rest] = loaded.tail;
const lateTool = hydrateStreamState(
[
{
event: makeToolCallTimelineEvent("call-a"),
timestamp: new Date(1002),
timelineCursor: { epoch: "epoch-1", seq: 4, anchorSeq: 2 },
},
],
{ source: "canonical" },
);
const state = { ...loaded, tail: [promptA, replyA, ...lateTool, ...rest] };
const rewound = live(state, [rewindEvent(rewindB)]);
expect(conversation(rewound)).toEqual(["A", "reply A", "tool_call"]);
});
it("keeps a tool that started before B when B's prompt is not loaded and the tool updated after B", () => {
const toolA = {
...makeToolCallTimelineEntry(2, "call-a", "completed", {
type: "read",
filePath: "/tmp/a.ts",
}),
seqEnd: 6,
sourceSeqRanges: [
{ startSeq: 2, endSeq: 2 },
{ startSeq: 6, endSeq: 6 },
],
};
const loaded = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 6, nextSeq: 7 },
startCursor: { seq: 1 },
endCursor: { seq: 6 },
entries: [makeTimelineEntry(1, "A", "user_message"), toolA],
},
});
if (!loaded.cursor) throw new Error("expected a loaded range");
const rewound = live({ tail: loaded.tail, head: loaded.head, cursor: loaded.cursor }, [
rewindEvent({ seq: 7, retireFromSeq: 3 }),
]);
expect(conversation(rewound)).toEqual(["A", "tool_call"]);
});
it("keeps C from the live overlay when the first page brings the retirement C followed", () => {
const overlay = processAgentStreamEvents({
events: [rewindEvent(rewindB), ...promptC],
currentTail: [],
currentHead: [],
currentCursor: undefined,
hasAuthoritativeBaseline: false,
});
const initialized = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
currentTail: overlay.tail,
currentHead: overlay.head,
payload: {
...baseTimelineInput.payload,
direction: "tail",
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
startCursor: { seq: 1 },
endCursor: { seq: 5 },
entries: [makeTimelineEntry(1, "A", "user_message"), makeTimelineEntry(2, "reply A")],
retirements: [rewindB],
},
});
expect(conversation(initialized)).toEqual(["A", "reply A", "C", "reply C"]);
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "opus" },
@@ -5093,30 +4816,4 @@ describe("turn metrics", () => {
expect(repeated.tail).toBe(first.tail);
});
it("stamps turn metrics carried on a live timeline event appended by reload", () => {
const result = processAgentStreamEvents({
events: [
makeStreamReducerEvent(makeTimelineEvent("question", "user_message"), 1),
makeStreamReducerEvent(
{
type: "timeline",
provider: "claude",
item: { type: "assistant_message", text: "Appended reply." },
turnMetrics: metrics,
},
2,
),
],
currentTail: [],
currentHead: [],
currentCursor: { epoch: "epoch-1", startSeq: 0, endSeq: 0 },
hasAuthoritativeBaseline: true,
});
expect(metricsByKind([...result.tail, ...result.head])).toEqual([
{ kind: "user_message", turnMetrics: undefined },
{ kind: "assistant_message", turnMetrics: metrics },
]);
});
});
@@ -1,13 +1,7 @@
import type { AgentMetric, AgentTimelineItem } from "@getpaseo/protocol/agent-types";
import type { AgentStreamEventPayload } from "@getpaseo/protocol/messages";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import {
advanceTimelinePosition,
type AssistantMessageItem,
type StreamItem,
type TimelinePosition,
type TodoEntry,
} from "@/types/stream";
import type { AssistantMessageItem, StreamItem, TodoEntry } from "@/types/stream";
import type { TurnLivenessTransition } from "@/timeline/turn-liveness";
import { stampTimelineTurnMetrics } from "@/timeline/turn-metrics";
import {
@@ -78,64 +72,6 @@ interface TimelineSeqRange {
endSeq: number;
}
/** A conversation rewind took the rows anchored in `[retireFromSeq, seq)` out of the conversation. */
export interface TimelineRetirement {
seq: number;
retireFromSeq: number;
}
/** The live form of a retirement; it is sequenced with the stream events around it. */
export interface TimelineRewindEvent {
type: "rewind";
retireFromSeq: number;
}
/**
* Drops the rows a retirement took out of the conversation: those anchored in
* `[retireFromSeq, seq)`. Anchors do not move on update, so an earlier row updated after the
* rewound prompt stays, and a row that started after the retirement stays. Items without a
* timeline position are local sends the daemon has not echoed and stay.
*/
function retireRewoundStreamItems(input: {
tail: StreamItem[];
head: StreamItem[];
epoch: string;
retirement: TimelineRetirement;
}): { tail: StreamItem[]; head: StreamItem[] } {
const { tail, head, epoch, retirement } = input;
const isRetired = (item: StreamItem) => {
const position = item.timelineCursor;
return (
position?.epoch === epoch &&
position.anchorSeq >= retirement.retireFromSeq &&
position.anchorSeq < retirement.seq
);
};
const nextTail = tail.filter((item) => !isRetired(item));
const nextHead = head.filter((item) => !isRetired(item));
return {
tail: nextTail.length === tail.length ? tail : nextTail,
head: nextHead.length === head.length ? head : nextHead,
};
}
/**
* Applies a page's retirements to what this client holds. The page's own entries are already
* active. Applying a retirement twice changes nothing, since its range is bounded.
*/
function retireForPage(input: {
payload: ProcessTimelineResponseInput["payload"];
tail: StreamItem[];
head: StreamItem[];
}): { tail: StreamItem[]; head: StreamItem[] } {
const { payload } = input;
let held = { tail: input.tail, head: input.head };
for (const retirement of payload.retirements ?? []) {
held = retireRewoundStreamItems({ ...held, epoch: payload.epoch, retirement });
}
return held;
}
function mergeTimelineCoverage(
current: TimelineCursor,
added: TimelineLoadedRange,
@@ -216,7 +152,6 @@ export interface ProcessTimelineResponseInput {
hasNewer: boolean;
hasOlder: boolean;
mergeWindow?: boolean;
retirements?: TimelineRetirement[];
};
currentTail: StreamItem[];
currentHead: StreamItem[];
@@ -461,7 +396,7 @@ function mergeTimelineWindow(args: {
toHydratedEvents: (units: TimelineUnit[]) => Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}>;
}): TimelinePathResult {
const { timelineUnits, payload, currentTail, currentHead, currentCursor, toHydratedEvents } =
@@ -825,7 +760,7 @@ function replaceLiveAssistantWithProjectedText(params: {
head: StreamItem[];
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}): StreamItem[] | null {
const { head, event, timestamp, timelineCursor } = params;
if (event.type !== "timeline" || event.item.type !== "assistant_message") {
@@ -844,7 +779,7 @@ function replaceLiveAssistantWithProjectedText(params: {
...current,
text: event.item.text,
timestamp,
...advanceTimelinePosition(current.timelineCursor, timelineCursor),
timelineCursor,
};
return next;
}
@@ -894,7 +829,7 @@ function reconcileOverlappingProjectedAssistant(params: {
...(messageId !== undefined ? { messageId } : {}),
text: projectedText,
timestamp: unit.timestamp,
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd, anchorSeq: unit.seq },
timelineCursor: { epoch: params.epoch, seq: unit.seqEnd },
};
const replaceMatch = (items: StreamItem[], index: number) => {
const next = [...items];
@@ -1011,8 +946,8 @@ function applyCanonicalForwardUnit(params: {
unit: TimelineUnit;
epoch: string;
}): { tail: StreamItem[]; head: StreamItem[]; acknowledgedClientMessageIds: string[] } {
const { event, timestamp, seq, seqEnd } = params.unit;
const timelineCursor: TimelinePosition = { epoch: params.epoch, seq: seqEnd, anchorSeq: seq };
const { event, timestamp, seqEnd } = params.unit;
const timelineCursor = { epoch: params.epoch, seq: seqEnd };
if (event.type === "timeline" && event.item.type === "user_message") {
const applied = applyStreamEvent({
tail: params.tail,
@@ -1211,10 +1146,10 @@ function applyAcceptedTimelinePage(input: {
});
}
const olderTail = hydrateStreamState(
acceptedUnits.map(({ event, timestamp, seq, seqEnd }) => ({
acceptedUnits.map(({ event, timestamp, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
})),
{
source: "canonical",
@@ -1246,12 +1181,7 @@ function applyTimelineIncrementalPath(args: {
let cursorChanged = false;
const sideEffects: TimelineReducerSideEffect[] = [];
// A forward page of retirements alone still advances the loaded end.
if (
timelineUnits.length === 0 &&
payload.direction !== "before" &&
(payload.retirements?.length ?? 0) === 0
) {
if (timelineUnits.length === 0 && payload.direction !== "before") {
return {
tail: currentTail,
head: currentHead,
@@ -1309,6 +1239,8 @@ export function processTimelineResponse(
): ProcessTimelineResponseOutput {
const {
payload,
currentTail,
currentHead,
currentCursor,
isInitializing,
hasActiveInitDeferred,
@@ -1322,8 +1254,8 @@ export function processTimelineResponse(
if (payload.error) {
return {
commit: "apply",
tail: input.currentTail,
head: input.currentHead,
tail: currentTail,
head: currentHead,
cursor: currentCursor,
cursorChanged: false,
older: "unchanged",
@@ -1335,13 +1267,6 @@ export function processTimelineResponse(
};
}
// Entries are already free of retired rows; the retirements apply to what this client holds.
const { tail: currentTail, head: currentHead } = retireForPage({
payload,
tail: input.currentTail,
head: input.currentHead,
});
// ------------------------------------------------------------------
// Convert entries to timeline units
// ------------------------------------------------------------------
@@ -1367,12 +1292,12 @@ export function processTimelineResponse(
): Array<{
event: AgentStreamEventPayload;
timestamp: Date;
timelineCursor: TimelinePosition;
timelineCursor: { epoch: string; seq: number };
}> =>
units.map(({ event, timestamp, seq, seqEnd }) => ({
units.map(({ event, timestamp, seqEnd }) => ({
event,
timestamp,
timelineCursor: { epoch: payload.epoch, seq: seqEnd, anchorSeq: seq },
timelineCursor: { epoch: payload.epoch, seq: seqEnd },
}));
// ------------------------------------------------------------------
@@ -1507,7 +1432,7 @@ export function processTimelineResponse(
// ---------------------------------------------------------------------------
export interface ProcessAgentStreamEventInput {
event: AgentStreamEventPayload | TimelineRewindEvent;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
currentTail: StreamItem[];
@@ -1530,7 +1455,7 @@ export interface ProcessAgentStreamEventOutput {
}
export interface AgentStreamReducerEvent {
event: AgentStreamEventPayload | TimelineRewindEvent;
event: AgentStreamEventPayload;
seq: number | undefined;
epoch: string | undefined;
timestamp: Date;
@@ -1648,70 +1573,11 @@ function processTimelineSequencingGate(input: {
};
}
/**
* Applies a live rewind in sequence with the stream. One that does not follow the loaded end is
* stale (already applied, or older than a page this client took) or leaves a gap to catch up.
*/
function processTimelineRewind(
input: ProcessAgentStreamEventInput & { event: TimelineRewindEvent },
): ProcessAgentStreamEventOutput {
const { event, seq, epoch, currentTail, currentHead, currentCursor } = input;
const unchanged: ProcessAgentStreamEventOutput = {
tail: currentTail,
head: currentHead,
changedTail: false,
changedHead: false,
cursor: null,
cursorChanged: false,
acknowledgedClientMessageIds: [],
sideEffects: [],
};
if (seq === undefined || epoch === undefined) return unchanged;
const decision =
input.hasAuthoritativeBaseline === false
? "overlay"
: classifySessionTimelineSeq({
cursor: currentCursor
? { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq }
: null,
epoch,
seq,
});
if (decision === "gap" && currentCursor) {
return {
...unchanged,
sideEffects: [
{ type: "catch_up", cursor: { epoch: currentCursor.epoch, endSeq: currentCursor.endSeq } },
],
};
}
if (decision !== "accept" && decision !== "init" && decision !== "overlay") return unchanged;
const retired = retireRewoundStreamItems({
tail: currentTail,
head: currentHead,
epoch,
retirement: { seq, retireFromSeq: event.retireFromSeq },
});
let cursor: TimelineCursor | null = null;
if (decision === "accept" && currentCursor) cursor = { ...currentCursor, endSeq: seq };
if (decision === "init") cursor = { epoch, startSeq: seq, endSeq: seq };
return {
...unchanged,
tail: retired.tail,
head: retired.head,
changedTail: retired.tail !== currentTail,
changedHead: retired.head !== currentHead,
cursor,
cursorChanged: cursor !== null,
};
}
export function processAgentStreamEvent(
input: ProcessAgentStreamEventInput,
): ProcessAgentStreamEventOutput {
const event = input.event;
if (event.type === "rewind") return processTimelineRewind({ ...input, event });
const {
event,
seq,
epoch,
currentTail,
@@ -1730,7 +1596,7 @@ export function processAgentStreamEvent(
});
const timelineCursor =
event.type === "timeline" && seq !== undefined && epoch !== undefined
? { epoch, seq, anchorSeq: seq }
? { epoch, seq }
: undefined;
// ------------------------------------------------------------------
// Apply stream event to tail/head
@@ -2044,10 +1910,6 @@ export function createSessionAgentStreamReducerQueue(
};
},
commit: (agentId, result, events) => {
for (const { event, seq, epoch } of events) {
if (event.type !== "rewind" || seq === undefined || epoch === undefined) continue;
useSessionStore.getState().recordAgentTimelineRewind(serverId, agentId, { epoch, seq });
}
if (
result.changedTail ||
result.changedHead ||
@@ -237,13 +237,6 @@ function commitProcessedTimeline(input: {
const agentId = payload.agentId;
const store = useSessionStore.getState();
if (result.commit !== "discard") {
const latestRewindSeq = Math.max(...(payload.retirements ?? []).map(({ seq }) => seq));
if (Number.isFinite(latestRewindSeq)) {
store.recordAgentTimelineRewind(serverId, agentId, {
epoch: payload.epoch,
seq: latestRewindSeq,
});
}
store.applyAgentTimelineResponseState(serverId, agentId, {
items: result.tail,
head: result.head,
@@ -464,14 +457,8 @@ export type ViewedTimelineOwnerPorts = Omit<
| "applyCurrentTimeline"
>;
/**
* `stale`: the page was served before a rewind this client already applied, so it can hold rows
* that rewind retired. Nothing was applied; request the page again.
*/
export type TimelineResponseOutcome = "applied" | "stale";
export interface ViewedTimelineOwner extends ViewedTimelineSync {
applyTimelineResponse(payload: TimelineResponsePayload): TimelineResponseOutcome;
applyTimelineResponse(payload: TimelineResponsePayload): void;
/**
* Accepts one live stream event. Content is coalesced to the next frame; a turn boundary
* commits the turn's queued content before its liveness changes, so the view never shows
@@ -481,37 +468,6 @@ export interface ViewedTimelineOwner extends ViewedTimelineSync {
flushStreamAgent(agentId: string): void;
}
/**
* The latest retirement each chat has seen, live or on a page. Tail, older and prompt-jump pages
* are served from active rows at one moment; one served before that retirement can still hold the
* rows it retired, and has no retirement to drop them with. Forward pages are sequenced against
* the loaded end instead, so they are never stale here.
*/
function createRetirementHighWater() {
const latest = new Map<string, { epoch: string; seq: number }>();
function note(agentId: string, retirement: { epoch: string; seq: number }): void {
const current = latest.get(agentId);
if (current?.epoch === retirement.epoch && current.seq >= retirement.seq) return;
latest.set(agentId, retirement);
}
return {
note,
notePage(payload: TimelineResponsePayload): void {
for (const retirement of payload.retirements ?? []) {
note(payload.agentId, { epoch: payload.epoch, seq: retirement.seq });
}
},
servedBefore(payload: TimelineResponsePayload): boolean {
const known = latest.get(payload.agentId);
return (
payload.direction !== "after" &&
known?.epoch === payload.epoch &&
payload.window.maxSeq < known.seq
);
},
};
}
export function createViewedTimelineOwner(input: {
serverId: string;
replica: TimelineReplica;
@@ -521,7 +477,6 @@ export function createViewedTimelineOwner(input: {
ports: ViewedTimelineOwnerPorts;
}): ViewedTimelineOwner {
const forcedTailReplacements = new Set<string>();
const retirements = createRetirementHighWater();
const sync = createViewedTimelineSync({
...input.ports,
fetchLatestTail: async (agentId) => {
@@ -562,8 +517,6 @@ export function createViewedTimelineOwner(input: {
return {
...sync,
applyTimelineResponse(receivedPayload) {
if (retirements.servedBefore(receivedPayload)) return "stale";
retirements.notePage(receivedPayload);
const payload = consumeForcedTimelineTailReplacement(receivedPayload, forcedTailReplacements);
const accepted = applyAuthoritativeTimelineResponse({
serverId: input.serverId,
@@ -573,12 +526,8 @@ export function createViewedTimelineOwner(input: {
drainQueuedAgentMessage: input.drainQueuedAgentMessage,
});
if (accepted) input.replica.timelineUpdated(payload.agentId);
return "applied";
},
applyStreamEvent(agentId, event) {
if (event.event.type === "rewind" && event.epoch !== undefined && event.seq !== undefined) {
retirements.note(agentId, { epoch: event.epoch, seq: event.seq });
}
streamQueue.enqueue(agentId, event);
const turnLiveness = deriveAgentStreamTurnLiveness([event]);
if (turnLiveness.length === 0) return;
+27 -5
View File
@@ -152,7 +152,7 @@ describe("normalizeStoredHostProfile", () => {
});
});
it("gives a host stored before appearance existed the default appearance", () => {
it("gives a host stored before appearance existed the default appearance without an icon key", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_old",
connections: [
@@ -161,18 +161,35 @@ describe("normalizeStoredHostProfile", () => {
});
expect(profile?.appearance).toEqual({ color: "none", badgeDisplay: null });
expect(profile && "icon" in profile.appearance).toBe(false);
});
it("loads a stored appearance the user chose", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_new",
appearance: { color: "teal", badgeDisplay: "icon" },
appearance: { color: "teal", icon: "laptop", badgeDisplay: "icon" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({ color: "teal", badgeDisplay: "icon" });
expect(profile?.appearance).toEqual({ color: "teal", icon: "laptop", badgeDisplay: "icon" });
});
it("preserves an unknown stored icon intact without dropping the saved host", () => {
const profile = normalizeStoredHostProfile({
serverId: "srv_future_icon",
appearance: { color: "violet", icon: "future-device", badgeDisplay: "name" },
connections: [
{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" },
],
});
expect(profile?.appearance).toEqual({
color: "violet",
icon: "future-device",
badgeDisplay: "name",
});
});
it("normalizes stored Remote SSH connection parameters", () => {
@@ -340,12 +357,13 @@ describe("upsertHostConnectionInProfiles", () => {
});
expect(profile.appearance).toEqual({ color: "none", badgeDisplay: null });
expect("icon" in profile.appearance).toBe(false);
});
it("keeps the appearance the user chose when the host reconnects", () => {
const existing: HostProfile = {
...makeHost("srv_known"),
appearance: { color: "amber", badgeDisplay: "hidden" },
appearance: { color: "amber", icon: "workstation", badgeDisplay: "hidden" },
connections: [],
};
@@ -355,7 +373,11 @@ describe("upsertHostConnectionInProfiles", () => {
connection,
});
expect(profile.appearance).toEqual({ color: "amber", badgeDisplay: "hidden" });
expect(profile.appearance).toEqual({
color: "amber",
icon: "workstation",
badgeDisplay: "hidden",
});
});
it("replaces a direct connection when its settings change", () => {
+3 -7
View File
@@ -1009,7 +1009,7 @@ describe("stream reducer canonical tool calls", () => {
});
it("keeps the timeline position on the whole assistant message", () => {
const timelineCursor = { epoch: "epoch-1", seq: 42, anchorSeq: 42 };
const timelineCursor = { epoch: "epoch-1", seq: 42 };
const result = applyStreamEvent({
tail: [],
head: [],
@@ -1890,7 +1890,7 @@ describe("turn lifecycle events", () => {
new Date("2025-01-01T15:03:11Z"),
{
source: "canonical",
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42 },
},
);
@@ -1902,11 +1902,7 @@ describe("turn lifecycle events", () => {
assert.strictEqual(userMessage.messageId, "provider-owned-canonical");
assert.strictEqual(userMessage.text, "Analyze this");
assert.strictEqual(userMessage.timestamp.getTime(), submittedTimestamp.getTime());
assert.deepStrictEqual(userMessage.timelineCursor, {
epoch: "epoch-1",
seq: 42,
anchorSeq: 42,
});
assert.deepStrictEqual(userMessage.timelineCursor, { epoch: "epoch-1", seq: 42 });
assert.deepStrictEqual(userMessage.images, [image]);
assert.deepStrictEqual(userMessage.attachments, [attachment]);
});
+15 -55
View File
@@ -266,7 +266,7 @@ function produceUserMessage(
...presentation,
clientMessageId: incoming.clientMessageId ?? existing.clientMessageId,
messageId: incoming.messageId ?? existing.messageId,
...advanceTimelinePosition(existing.timelineCursor, incoming.timelineCursor),
timelineCursor: incoming.timelineCursor ?? existing.timelineCursor,
});
if (
existing.id === merged.id &&
@@ -482,7 +482,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timelineCursor: retained.timelineCursor,
timestamp: retained.timestamp,
items: retained.items,
};
@@ -499,7 +499,7 @@ function mergeRetainedLifecycleItem(tail: StreamItem[], retained: StreamItem): S
const next = [...tail];
next[tailIndex] = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
timelineCursor: retained.timelineCursor,
status: "completed",
trigger: retained.trigger ?? existing.trigger,
preTokens: retained.preTokens ?? existing.preTokens,
@@ -519,10 +519,7 @@ function replaceTimelineIdentityItem(
const existing = items[index];
if (index < 0 || !existing || existing.kind !== "plugin") return null;
const next = [...items];
next[index] = {
...retained,
...advanceTimelinePosition(existing.timelineCursor, retained.timelineCursor),
};
next[index] = retained;
return next;
}
@@ -613,11 +610,7 @@ function preserveReplacementHead(
: `${tailAssistant.text}${liveAssistant.text}`;
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{
...liveAssistant,
text,
...advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor),
},
{ ...liveAssistant, text },
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -632,13 +625,7 @@ function preserveReplacementHead(
const head = [
...unreconciledHead.slice(0, liveAssistantIndex),
{
...liveAssistant,
text: tailAssistant.text,
...(liveAssistant.timelineCursor
? advanceTimelinePosition(tailAssistant.timelineCursor, liveAssistant.timelineCursor)
: {}),
},
{ ...liveAssistant, text: tailAssistant.text },
...unreconciledHead.slice(liveAssistantIndex + 1),
];
return {
@@ -737,27 +724,7 @@ export interface AssistantMessageItem {
export interface TimelinePosition {
epoch: string;
/** The latest seq that changed this row. */
seq: number;
/** The seq the row started at. Updates never move it; rewinds retire rows by it. */
anchorSeq: number;
}
/**
* The position of a row after an update: it moves to the update's seq and stays anchored where it
* started. Without an incoming position the row keeps the one it has.
*/
export function advanceTimelinePosition(
existing: TimelinePosition | undefined,
incoming: TimelinePosition | undefined,
): { timelineCursor?: TimelinePosition } {
if (!incoming) return existing ? { timelineCursor: existing } : {};
if (!existing || existing.epoch !== incoming.epoch) return { timelineCursor: incoming };
const anchorSeq = Math.min(existing.anchorSeq, incoming.anchorSeq);
if (existing.seq === incoming.seq && existing.anchorSeq === anchorSeq) {
return { timelineCursor: existing };
}
return { timelineCursor: { ...incoming, anchorSeq } };
}
export type ThoughtStatus = "loading" | "ready";
@@ -1005,7 +972,7 @@ function appendAssistantMessage(
...last,
text: `${last.text}${chunk}`,
timestamp,
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, -1), updated];
}
@@ -1023,7 +990,7 @@ function appendAssistantMessage(
...secondLast,
text: `${secondLast.text}${chunk}`,
timestamp,
...advanceTimelinePosition(secondLast.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
};
return [...state.slice(0, -2), updated, last];
}
@@ -1061,7 +1028,7 @@ function appendThought(
if (last && last.kind === "thought" && last.turnId === turnId) {
const updated: ThoughtItem = {
...last,
...advanceTimelinePosition(last.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
text: `${last.text}${chunk}`,
timestamp,
status: "loading",
@@ -1241,7 +1208,7 @@ export function mergeAgentToolCallItem(
return {
...existing,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
timestamp,
payload: {
source: "agent",
@@ -1347,11 +1314,7 @@ function appendPluginTimelineItem(
const existing = state[existingIndex];
if (!existing || existing.kind !== "plugin") return state;
const next = [...state];
next[existingIndex] = {
...nextItem,
id: existing.id,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
};
next[existingIndex] = { ...nextItem, id: existing.id };
return next;
}
@@ -1382,7 +1345,7 @@ function appendTodoList(
const next = [...state];
next[previousIndex] = {
...previous,
...advanceTimelinePosition(previous.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
items: normalizedItems,
timestamp,
};
@@ -1401,7 +1364,7 @@ function appendTodoList(
const next = [...state];
next[next.length - 1] = {
...lastItem,
...advanceTimelinePosition(lastItem.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
items: normalizedItems,
activity: { type: "created", count: normalizedItems.length },
timestamp,
@@ -1546,7 +1509,7 @@ function reduceTimelineCompaction(
if (loadingIdx >= 0 && existing && existing.kind === "compaction") {
const updated: CompactionItem = {
...existing,
...advanceTimelinePosition(existing.timelineCursor, timelineCursor),
...(timelineCursor ? { timelineCursor } : {}),
status: "completed",
trigger: item.trigger ?? existing.trigger,
preTokens: item.preTokens ?? existing.preTokens,
@@ -1671,10 +1634,7 @@ export function reduceStreamUpdate(
),
event,
);
const stamped = event.turnMetrics?.length
? stampCompletedTurnMetrics(updated, event.turnMetrics, event.turnId)
: updated;
return event.item.type === "reasoning" ? stamped : finalizeActiveThoughts(stamped);
return event.item.type === "reasoning" ? updated : finalizeActiveThoughts(updated);
}
case "turn_completed":
return stampCompletedTurnMetrics(finalizeActiveThoughts(state), event.metrics, event.turnId);
@@ -143,3 +143,11 @@ export const Minimize = StubIcon;
export const Rows2 = StubIcon;
export const Gauge = StubIcon;
export const GripVertical = StubIcon;
export const Cloud = StubIcon;
export const Computer = StubIcon;
export const Container = StubIcon;
export const Cpu = StubIcon;
export const Laptop = StubIcon;
export const Network = StubIcon;
export const PcCase = StubIcon;
export const Waypoints = StubIcon;
@@ -146,10 +146,6 @@ export async function runAttachCommand(
const unsubscribe = client.subscribeAgentTimeline(resolvedId, (message) => {
if (message.type === "agent.timeline.replacement") {
console.log("\n[Timeline replaced; earlier output is no longer current]");
} else if (message.type === "agent.timeline.rewind") {
console.log(
"\n[Conversation rewound; output since the rewound message is no longer current]",
);
} else if (message.type === "agent.timeline.subscription_restored") {
console.log("\n[Reconnected; live output resumed. Events may have been missed.]");
} else if (message.type === "agent.timeline.error") {
+1 -5
View File
@@ -408,6 +408,7 @@ async function runFollowMode({
} catch (error) {
console.warn("Warning: failed to fetch existing timeline", error);
}
// Apply filter to existing items
if (options.filter) {
existingItems = existingItems.filter((item) => matchesFilter(item, options.filter));
@@ -438,11 +439,6 @@ async function runFollowMode({
notice("\n[Timeline replaced; earlier output is no longer current]");
return;
}
if (message.type === "agent.timeline.rewind") {
writer.end();
notice("\n[Conversation rewound; output since the rewound message is no longer current]");
return;
}
if (message.type === "agent.timeline.error") {
writer.end();
-31
View File
@@ -211,37 +211,6 @@ test("SDK subscribers receive timeline replacement instead of silently losing hi
}
});
test("SDK subscribers receive a conversation rewind as a retired range", async () => {
const { createPaseoApi } = await import("./index");
const h = connection();
const received: unknown[] = [];
try {
const ready = h.client.connect();
h.open();
await ready;
const off = createPaseoApi(h.client)
.agents.ref("agent")
.timeline.subscribe((event) => received.push(event));
await off.ready;
h.receive({
type: "agent.timeline.rewind",
payload: {
agentId: "agent",
epoch: "epoch-1",
seq: 12,
retireFromSeq: 7,
subscriptionId: off.subscriptionId,
},
});
expect(received).toEqual([
{ agentId: "agent", event: { type: "rewind", epoch: "epoch-1", seq: 12, retireFromSeq: 7 } },
]);
off();
} finally {
await h.client.close();
}
});
test("local listeners create no demand before or after reconnect", async () => {
const h = connection();
try {
-1
View File
@@ -141,7 +141,6 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
[CLIENT_CAPS.compactProviderSnapshots]: true,
[CLIENT_CAPS.providerSnapshotReferences]: true,
[CLIENT_CAPS.timelineReplacementInvalidation]: true,
[CLIENT_CAPS.timelineRewindOperations]: true,
[CLIENT_CAPS.timelineNotifications]: true,
[CLIENT_CAPS.pluginTimelineItems]: true,
[CLIENT_CAPS.workspaceSetupBlocked]: true,
+1 -3
View File
@@ -246,9 +246,7 @@ export class LegacySubscriptions {
);
case "agent.timeline.set_subscription.request":
return (
(message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind") &&
(message.type === "agent_stream" || message.type === "agent.timeline.replacement") &&
(query.agentIds as string[]).includes(message.payload.agentId)
);
case "session.events.set_subscription.request":
+102 -1
View File
@@ -1131,7 +1131,6 @@ test("advertises client capabilities in hello", async () => {
all_providers: true,
selective_agent_timeline: true,
timeline_replacement_invalidation: true,
timeline_rewind_operations: true,
provider_snapshot_references: true,
explicit_event_subscriptions: true,
owned_subscriptions: true,
@@ -6561,6 +6560,108 @@ test("fetches scoped recent provider sessions", async () => {
});
});
test.each([
{
scenario: "successful rows after the default RPC deadline",
delayMs: 61_000,
payload: {
requestId: "recent-listing-deadline",
entries: [
{
providerId: "slow-acp",
providerLabel: "Slow ACP",
providerHandleId: "slow-session",
cwd: "/tmp/import-listing",
title: "Slow provider session",
firstPromptPreview: null,
lastPromptPreview: null,
lastActivityAt: "2026-04-30T12:34:56.000Z",
},
],
},
},
{
scenario: "the server's provider timeout after ninety seconds",
delayMs: 90_001,
payload: {
requestId: "recent-listing-deadline",
entries: [],
providerErrors: [
{
provider: "slow-acp",
message: "Timed out listing importable sessions for provider 'slow-acp' after 90000ms",
},
],
},
},
])("recent provider listing receives $scenario", async ({ delayMs, payload }) => {
useHeartbeatClock();
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_import_listing_deadline",
reconnect: { enabled: false },
transportFactory: () => transport.transport,
});
clients.push(client);
const connected = client.connect();
transport.triggerOpen();
await connected;
const outcome = client
.fetchRecentProviderSessions({
requestId: "recent-listing-deadline",
providers: ["slow-acp"],
limit: 1,
})
.then(
(response) => ({ status: "success", response }),
(error: unknown) => ({ status: "error", error }),
);
await vi.advanceTimersByTimeAsync(delayMs);
transport.triggerMessage(
wrapSessionMessage({ type: "fetch_recent_provider_sessions_response", payload }),
);
expect(await outcome).toEqual({ status: "success", response: payload });
expect(client.isConnected).toBe(true);
});
test("recent provider listing still expires when the daemon never answers", async () => {
useHeartbeatClock();
const transport = createMockTransport();
const client = new DaemonClient({
url: "ws://test",
clientId: "clsk_import_listing_no_response",
reconnect: { enabled: false },
transportFactory: () => transport.transport,
});
clients.push(client);
const connected = client.connect();
transport.triggerOpen();
await connected;
const errors: unknown[] = [];
const listing = client
.fetchRecentProviderSessions({ providers: ["slow-acp"] })
.catch((error: unknown) => {
errors.push(error);
});
await vi.advanceTimersByTimeAsync(90_001);
expect(errors).toEqual([]);
await vi.advanceTimersByTimeAsync(9_999);
expect(errors).toEqual([
expect.objectContaining({
name: "DaemonConnectionError",
code: "DAEMON_REQUEST_TIMEOUT",
}),
]);
await listing;
expect(client.isConnected).toBe(true);
});
test("imports an agent by provider handle id", async () => {
const logger = createMockLogger();
const mock = createMockTransport();
+3
View File
@@ -1172,6 +1172,8 @@ function toTimeoutError(error: unknown, label: string, timeoutMs: number): Error
const DEFAULT_RECONNECT_BASE_DELAY_MS = 1500;
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30000;
const DEFAULT_SESSION_RPC_TIMEOUT_MS = 60_000;
// The daemon allows 90s per provider; retain its result through the delivery margin.
const RECENT_PROVIDER_SESSIONS_TIMEOUT_MS = 100_000;
const PUSH_TOKEN_REVOCATION_TIMEOUT_MS = 2_000;
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
const DEFAULT_LIVENESS_TIMEOUT_MS = 5000;
@@ -2998,6 +3000,7 @@ export class DaemonClient {
return this.sendRequest({
requestId: resolvedRequestId,
message,
timeout: RECENT_PROVIDER_SESSIONS_TIMEOUT_MS,
options: { skipQueue: true },
select: (msg) => {
if (msg.type !== "fetch_recent_provider_sessions_response") {
+1 -21
View File
@@ -346,14 +346,6 @@ export type PaseoAgentTimelineEvent =
agentId: string;
event: { type: "replacement"; epoch: string };
}
| {
/**
* A conversation rewind removed the rows anchored in `[retireFromSeq, seq)` from the active
* history. Rows after `seq` belong to the rewound conversation.
*/
agentId: string;
event: { type: "rewind"; epoch: string; seq: number; retireFromSeq: number };
}
| {
agentId: string;
subscriptionId: string;
@@ -375,9 +367,7 @@ export interface PaseoAgentTimelineHandle {
* Delivers live events only. After reconnect, subscription_restored precedes
* subsequent updates. History may have been missed; use refetch() to request
* the range you need. No history is fetched automatically. A replacement event
* invalidates the previous epoch. A rewind event removes `[retireFromSeq, seq)`
* from the active history without changing the epoch. Subscription errors
* release this observation.
* invalidates the previous epoch. Subscription errors release this observation.
* Await the returned unsubscribe function's `ready` promise before starting
* work that must be observed. It rejects if establishment fails.
*/
@@ -1057,16 +1047,6 @@ function createAgentHandleFactory(
agentId: id,
event: { type: "replacement", epoch: message.payload.epoch },
});
case "agent.timeline.rewind":
return handler({
agentId: id,
event: {
type: "rewind",
epoch: message.payload.epoch,
seq: message.payload.seq,
retireFromSeq: message.payload.retireFromSeq,
},
});
}
}),
},
@@ -3,7 +3,7 @@ import type { OwnedSubscription, TimelineSubscription } from "../connection/inde
type TimelineUpdate = Extract<
SessionOutboundMessage,
{ type: "agent_stream" | "agent.timeline.replacement" | "agent.timeline.rewind" }
{ type: "agent_stream" | "agent.timeline.replacement" }
>;
/** Local SDK lifecycle messages; these are not additional wire RPCs. */
@@ -59,11 +59,7 @@ export function subscribeTimeline(
});
},
update: (message) => {
if (
message.type === "agent_stream" ||
message.type === "agent.timeline.replacement" ||
message.type === "agent.timeline.rewind"
)
if (message.type === "agent_stream" || message.type === "agent.timeline.replacement")
notify(message);
},
error: fail,
-5
View File
@@ -368,11 +368,6 @@ export type ProviderInput =
sessionId: string;
changes: ProviderConfigChanges;
}
/**
* Rewind to the supplied `token`. Completing the request (`request.completed`) guarantees the
* plugin rewound to that exact point (removing that prompt and everything after it for
* `"conversation"` and `"both"`).
*/
| {
type: "session.revert";
requestId: string;
@@ -39,9 +39,6 @@ export const CLIENT_CAPS = {
// COMPAT(timelineReplacementInvalidation): added in v0.5.0, remove legacy
// reconstructed timeline replay after 2027-02-21 once the client floor supports invalidation.
timelineReplacementInvalidation: "timeline_replacement_invalidation",
// COMPAT(timelineRewindOperations): added in v0.14.1, remove after 2027-05-10 once the client
// floor applies rewinds. Clients without it see a rewound history under a derived epoch.
timelineRewindOperations: "timeline_rewind_operations",
// COMPAT(timelineNotifications): added in v0.7.2. The daemon omits notification
// timeline items for older clients whose strict timeline union rejects them.
// Remove after 2027-03-03 once the supported client floor is >= v0.7.2.
+3 -29
View File
@@ -856,7 +856,6 @@ export const AgentStreamEventPayloadSchema = z.discriminatedUnion("type", [
provider: AgentProviderSchema,
item: AgentTimelineItemPayloadSchema,
turnId: z.string().optional(),
turnMetrics: z.array(AgentMetricSchema).optional(),
}),
z.object({
type: z.literal("permission_requested"),
@@ -3971,6 +3970,9 @@ export const ServerInfoStatusPayloadSchema = z
serverId: z.string().trim().min(1),
hostname: ServerInfoHostnameSchema.optional(),
version: ServerInfoVersionSchema.optional(),
// Best-effort machine kind detected by the daemon (e.g. "laptop", "mini", "cloud").
// Loose string so unknown future kinds stay parseable across versions.
machineKind: z.string().nullable().optional(),
// Authenticated producer for host registration ownership, separate from admission authority.
sourceId: z.string().optional(),
// COMPAT(sessionPermissions): optional while clients support older daemons.
@@ -4089,9 +4091,6 @@ export const ServerInfoStatusPayloadSchema = z
"terminal-grapheme-widths": z.boolean().optional(),
// COMPAT(rewind): added in v0.1.X, drop the gate when floor >= v0.1.X.
rewind: z.boolean().optional(),
// COMPAT(timelineRewindOperations): added in v0.14.1, remove gate after 2027-05-10.
// A conversation rewind arrives as `agent.timeline.rewind`, not a replacement.
timelineRewindOperations: z.boolean().optional(),
// COMPAT(agentTimelinePromptIndex): added in v0.2.X, drop the gate when floor >= v0.2.X.
agentTimelinePromptIndex: z.boolean().optional(),
// COMPAT(agentHistorySearch): added in v0.3.0, remove gate after 2027-02-07.
@@ -4295,8 +4294,6 @@ export const AgentResumedStatusPayloadSchema = z
export const AgentRefreshedStatusPayloadSchema = z
.object({
status: z.literal("agent_refreshed"),
/** The provider's history differs from the kept history, which Reload agent did not change. */
historyDiverged: z.boolean().optional(),
})
.extend(AgentStatusWithTimelineSchema.shape);
@@ -5157,12 +5154,6 @@ export const AgentTimelineEntryPayloadSchema = z.object({
turnMetrics: z.array(AgentMetricSchema).optional(),
});
/** Active rows anchored in `[retireFromSeq, seq)` left the conversation. `seq` is the retirement's own. */
export const AgentTimelineRetirementSchema = z.object({
seq: z.number().int().nonnegative(),
retireFromSeq: z.number().int().nonnegative(),
});
export const FetchAgentTimelineResponseMessageSchema = z.object({
type: z.literal("fetch_agent_timeline_response"),
payload: z.object({
@@ -5186,9 +5177,6 @@ export const FetchAgentTimelineResponseMessageSchema = z.object({
hasNewer: z.boolean(),
mergeWindow: z.boolean().optional(),
entries: z.array(AgentTimelineEntryPayloadSchema),
// COMPAT(timelineRewindOperations): added in v0.14.1. Retirements whose seq lies in the page's
// span; apply them before the entries. Sent only to clients with the capability.
retirements: z.array(AgentTimelineRetirementSchema).optional(),
error: z.string().nullable(),
}),
});
@@ -5202,18 +5190,6 @@ export const AgentTimelineReplacementMessageSchema = z.object({
}),
});
/** A conversation rewind retired active rows. Apply it when `seq` follows the loaded end. */
export const AgentTimelineRewindMessageSchema = z.object({
type: z.literal("agent.timeline.rewind"),
payload: z.object({
subscriptionId: z.string().optional(),
agentId: z.string(),
epoch: z.string(),
seq: z.number().int().nonnegative(),
retireFromSeq: z.number().int().nonnegative(),
}),
});
export const AgentTimelineSearchResponseMessageSchema = z.object({
type: z.literal("agent.timeline.search.response"),
payload: z.object({
@@ -7802,7 +7778,6 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
FetchAgentResponseMessageSchema,
FetchAgentTimelineResponseMessageSchema,
AgentTimelineReplacementMessageSchema,
AgentTimelineRewindMessageSchema,
AgentTimelineSearchResponseMessageSchema,
AgentTimelineListPromptsResponseMessageSchema,
ProviderSubagentListResponseMessageSchema,
@@ -8507,7 +8482,6 @@ export const WSHelloMessageSchema = z.object({
[CLIENT_CAPS.compactProviderSnapshots]: z.boolean().optional(),
[CLIENT_CAPS.providerSnapshotReferences]: z.boolean().optional(),
[CLIENT_CAPS.timelineReplacementInvalidation]: z.boolean().optional(),
[CLIENT_CAPS.timelineRewindOperations]: z.boolean().optional(),
[CLIENT_CAPS.timelineNotifications]: z.boolean().optional(),
[CLIENT_CAPS.backgroundAgents]: z.boolean().optional(),
[CLIENT_CAPS.browserHost]: BrowserAutomationHostCapabilitySchema.optional(),
@@ -217,64 +217,6 @@ describe("wire schema compatibility", () => {
});
});
test("rewind operations are opt-in and older fetch responses still parse", () => {
expect(
WSHelloMessageSchema.parse({
type: "hello",
clientId: "capable-client",
clientType: "mobile",
protocolVersion: 1,
capabilities: { timeline_rewind_operations: true },
}).capabilities,
).toEqual({ timeline_rewind_operations: true });
const rewind = {
type: "agent.timeline.rewind",
payload: {
subscriptionId: "sub-1",
agentId: "agent-1",
epoch: "epoch-1",
seq: 12,
retireFromSeq: 7,
},
};
expect(SessionOutboundMessageSchema.parse(rewind)).toEqual(rewind);
const page = {
requestId: "fetch-1",
agentId: "agent-1",
agent: null,
direction: "after",
projection: "projected",
epoch: "epoch-1",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 1, maxSeq: 14, nextSeq: 15 },
startCursor: { epoch: "epoch-1", seq: 13 },
endCursor: { epoch: "epoch-1", seq: 14 },
hasOlder: true,
hasNewer: false,
entries: [],
error: null,
};
const withRetirements = { ...page, retirements: [{ seq: 12, retireFromSeq: 7 }] };
expect(
SessionOutboundMessageSchema.parse({
type: "fetch_agent_timeline_response",
payload: withRetirements,
}),
).toMatchObject({ payload: { retirements: [{ seq: 12, retireFromSeq: 7 }] } });
// A daemon before rewind operations sends no retirements.
const older = SessionOutboundMessageSchema.parse({
type: "fetch_agent_timeline_response",
payload: page,
});
expect(older.type === "fetch_agent_timeline_response" && older.payload.retirements).toBe(
undefined,
);
});
test("server info strips unknown legacy features while accepting former turn identity", () => {
const parsed = ServerInfoStatusPayloadSchema.parse({
status: "server_info",
@@ -294,6 +236,34 @@ describe("wire schema compatibility", () => {
});
});
test("server info accepts optional machineKind and older clients drop it cleanly", () => {
const legacyServerInfo = z.object({
status: z.literal("server_info"),
serverId: z.string().trim().min(1),
hostname: z.string().nullable().optional(),
version: z.string().nullable().optional(),
});
const withKind = {
status: "server_info",
serverId: "macbook-server",
hostname: "mbp.local",
version: "0.9.5",
machineKind: "laptop",
};
expect(ServerInfoStatusPayloadSchema.parse(withKind).machineKind).toBe("laptop");
expect(
ServerInfoStatusPayloadSchema.parse({ ...withKind, machineKind: null }).machineKind,
).toBeNull();
expect(
ServerInfoStatusPayloadSchema.parse({
status: "server_info",
serverId: "older-server",
}).machineKind,
).toBeUndefined();
expect(legacyServerInfo.parse(withKind)).not.toHaveProperty("machineKind");
});
test("assistant timeline message ids are optional on the wire", () => {
expect(
AgentTimelineItemPayloadSchema.parse({
@@ -3,7 +3,7 @@ import { buildAgentForkContextAttachment, curateAgentActivity } from "./activity
import type { AgentTimelineItem } from "./agent-sdk-types.js";
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
import { formatAgentMessage, projectAgentMessages } from "./agent-messages/index.js";
import { AgentTimeline } from "./timeline/index.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
function toolCallItem(params: {
callId: string;
@@ -41,15 +41,12 @@ function row(seq: number, item: AgentTimelineItem): AgentTimelineRow {
}
/** Rows as the daemon hands them to a fork: projected by the timeline store. */
async function storeTimeline(items: readonly AgentTimelineItem[]) {
const store = new AgentTimeline();
const scope = { agentId: "agent-1" };
await store.create(scope);
await store.append(
scope,
items.map((item) => ({ item })),
);
return await store.fetch(scope, { limit: 0 });
function storeTimeline(items: readonly AgentTimelineItem[]) {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent-1");
for (const item of items) store.append("agent-1", item);
const { epoch, rows } = store.fetch("agent-1", { limit: 0 });
return { epoch, rows };
}
function backgroundTaskItem(input: { status: "running" | "completed"; log: string }) {
@@ -455,8 +452,8 @@ second line'`,
expect(result.attachment.text).toContain("[Assistant] Done.");
});
it("forks at a response that background work outlives, by message id", async () => {
const { rows } = await storeTimeline([
it("forks at a response that background work outlives, by message id", () => {
const { rows } = storeTimeline([
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
backgroundTaskItem({ status: "running", log: "scanning" }),
{ type: "assistant_message", text: "Audit started.", messageId: "assistant-1" },
@@ -476,8 +473,8 @@ second line'`,
expect(result.attachment.text).not.toContain("Any findings?");
});
it("forks at a response that background work outlives, by timeline cursor", async () => {
const { epoch, rows } = await storeTimeline([
it("forks at a response that background work outlives, by timeline cursor", () => {
const { epoch, rows } = storeTimeline([
{ type: "user_message", text: "Audit in the background", messageId: "user-1" },
backgroundTaskItem({ status: "running", log: "scanning" }),
{ type: "assistant_message", text: "Audit started." },
@@ -1,11 +1,11 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, test, vi } from "vitest";
import { expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager } from "./agent-manager.js";
import { AgentNotFoundError, ensureAgentLoaded, loadAgentHistory } from "./agent-loading.js";
import { ensureAgentLoaded } from "./agent-loading.js";
import { startAgentRun } from "./agent-prompt.js";
import { AgentStorage } from "./agent-storage.js";
import type {
@@ -227,109 +227,6 @@ test("reopening an agent with no resumable session keeps a metadata write that o
}
});
test("reads stored history without starting or requiring the provider, and imports history that is not stored", async () => {
const root = await mkdtemp(path.join(tmpdir(), "agent-loading-history-"));
const logger = createTestLogger();
const storage = new AgentStorage(path.join(root, "agents"), logger);
const baseClient = createTestAgentClients().codex;
if (!baseClient) {
throw new Error("expected Codex test client");
}
let resumes = 0;
const client: AgentClient = {
provider: baseClient.provider,
capabilities: baseClient.capabilities,
createSession: async (config: AgentSessionConfig, launchContext?: AgentLaunchContext) =>
await baseClient.createSession(config, launchContext),
resumeSession: async (
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
launchContext?: AgentLaunchContext,
) => {
resumes += 1;
return await baseClient.resumeSession(handle, overrides, launchContext);
},
fetchCatalog: async (options) => await baseClient.fetchCatalog(options),
isAvailable: async () => await baseClient.isAvailable(),
};
const agentId = "00000000-0000-4000-8000-000000000601";
const managers: AgentManager[] = [];
function startDaemon(): AgentManager {
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
managers.push(manager);
return manager;
}
try {
const manager = startDaemon();
const agent = await manager.createAgent({ provider: "codex", cwd: root }, agentId, {
workspaceId: "workspace-a",
});
await manager.runAgent(agent.id, "hello");
const transcript = await manager.getTimeline(agent.id);
expect(transcript.map((item) => item.type)).toContain("assistant_message");
await manager.closeAgent(agent.id);
await manager.flush();
await storage.flush();
const stored = await loadAgentHistory(agentId, {
agentManager: manager,
agentStorage: storage,
logger,
});
expect(stored).toMatchObject({ kind: "stored", record: { id: agentId } });
expect(await manager.getTimeline(agentId)).toEqual(transcript);
expect(manager.getAgent(agentId)).toBeNull();
// Stored history needs no provider, so it still reads once the provider is removed.
await expect(
loadAgentHistory(agentId, {
agentManager: manager,
agentStorage: storage,
logger,
validProviders: [],
}),
).resolves.toMatchObject({ kind: "stored", record: { id: agentId } });
expect(resumes).toBe(0);
// A restarted daemon has no history in memory; the provider's own history is imported,
// which needs the provider.
const restarted = startDaemon();
await expect(
loadAgentHistory(agentId, {
agentManager: restarted,
agentStorage: storage,
logger,
validProviders: [],
}),
).rejects.toThrow("references unavailable provider 'codex'");
const loaded = await loadAgentHistory(agentId, {
agentManager: restarted,
agentStorage: storage,
logger,
});
expect(loaded).toMatchObject({ kind: "live", agent: { id: agentId } });
expect(resumes).toBe(1);
expect((await restarted.getTimeline(agentId)).map((item) => item.type)).toEqual(
transcript.map((item) => item.type),
);
await expect(
loadAgentHistory("00000000-0000-4000-8000-000000000602", {
agentManager: restarted,
agentStorage: storage,
logger,
}),
).rejects.toBeInstanceOf(AgentNotFoundError);
} finally {
for (const manager of managers) {
await manager.closeAgent(agentId).catch(() => undefined);
await manager.flush().catch(() => undefined);
}
await storage.flush().catch(() => undefined);
await rm(root, { recursive: true, force: true });
}
});
test.each([false, true])(
"loads history after its working directory is removed (archived: %s)",
async (archived) => {
@@ -374,11 +271,11 @@ test.each([false, true])(
});
expect(loaded.id).toBe(agentId);
// The manager kept the transcript when the agent closed, so the reply the agent gave
// before the worktree went away is still readable.
const replies = (await manager.getTimeline(agentId)).filter(
(item) => item.type === "assistant_message",
);
// The transcript is replayed from the provider's persisted history, so the reply the
// agent gave before the worktree went away is still readable.
const replies = manager
.getTimeline(agentId)
.filter((item) => item.type === "assistant_message");
expect(replies.length).toBeGreaterThan(0);
expect(
replies.every((item) => item.type === "assistant_message" && item.text.length > 0),
@@ -421,7 +318,7 @@ test("timeline requests read unarchived stored history with a deleted cwd", asyn
}
}, 30000);
test("timeline reads of stored history leave the provider closed until a prompt resumes it interactively", async () => {
test("timeline reads keep runnable unarchived agents interactive for the next prompt", async () => {
const clients = createTestAgentClients();
const base = clients.codex!;
const purposes: Array<AgentResumeSessionOptions | undefined> = [];
@@ -442,8 +339,7 @@ test("timeline reads of stored history leave the provider closed until a prompt
const agent = await ctx.client.createAgent({ provider: "codex", cwd });
await ctx.daemon.daemon.agentManager.closeAgent(agent.id);
await ctx.client.fetchAgentTimeline(agent.id);
// The manager serves the stored timeline itself, so the read resumes no provider session.
expect(purposes).toEqual([]);
expect(purposes).toEqual([{ purpose: "interactive" }]);
await ctx.client.sendMessage(agent.id, "continue after opening history");
expect((await ctx.client.waitForFinish(agent.id, 15000)).status).toBe("idle");
const timeline = await ctx.client.fetchAgentTimeline(agent.id);
@@ -457,9 +353,11 @@ test("timeline reads of stored history leave the provider closed until a prompt
manager.tryRunOutOfBand(agent.id, "first prompt"),
manager.tryRunOutOfBand(agent.id, "second prompt"),
]);
// The prompt resumed once, and the concurrent prompts after the removed-cwd read share one
// resume. Every resume is interactive, so no history session needs replacing.
expect(purposes).toEqual([{ purpose: "interactive" }, { purpose: "interactive" }]);
expect(purposes).toEqual([
{ purpose: "interactive" },
{ purpose: "history" },
undefined, // Reload uses the provider's interactive default.
]);
} finally {
await ctx.cleanup();
await rm(cwd, { recursive: true, force: true });
@@ -553,13 +451,9 @@ test.each(["mode", "thinking", "rewind"])(
runtime.recordedLaunches.filter((launch) => launch.session === sessionFile),
).toHaveLength(1);
expect(manager.getAgent(agentId)?.currentModeId).toBe("full");
// The run reads its timeline before the provider starts the turn.
await vi.waitFor(() =>
expect(runtime.latestSession().prompts).toEqual([
expect.objectContaining({ message: "continue" }),
]),
);
runtime.latestSession().beginTurn();
expect(runtime.latestSession().prompts).toEqual([
expect.objectContaining({ message: "continue" }),
]);
runtime.latestSession().finishTurn();
await manager.waitForAgentEvent(agentId);
await manager.archiveAgent(agentId);
@@ -2,7 +2,7 @@ import type { Logger } from "pino";
import type { AgentProvider } from "./agent-sdk-types.js";
import type { AgentManager, ManagedAgent } from "./agent-manager.js";
import type { AgentStorage, StoredAgentRecord } from "./agent-storage.js";
import type { AgentStorage } from "./agent-storage.js";
import {
buildConfigOverrides,
extractAttention,
@@ -18,11 +18,20 @@ export class AgentNotFoundError extends Error {
}
}
const pendingAgentInitializations = new Map<string, Promise<ManagedAgent>>();
interface PendingAgentInitialization {
promise: Promise<ManagedAgent>;
options: { broadcastTimeline: boolean };
}
const pendingAgentInitializations = new Map<string, PendingAgentInitialization>();
export type AgentLoaderManager = Pick<
AgentManager,
"createAgentFromRecord" | "getAgent" | "getRegisteredProviderIds" | "resumeAgentFromPersistence"
| "createAgentFromRecord"
| "getAgent"
| "getRegisteredProviderIds"
| "hydrateTimelineFromProvider"
| "resumeAgentFromPersistence"
> &
Partial<Pick<AgentManager, "waitForAgentClose">>;
@@ -30,54 +39,11 @@ export interface EnsureAgentLoadedDeps {
agentManager: AgentLoaderManager;
agentStorage: AgentStorage;
validProviders?: Iterable<AgentProvider>;
broadcastTimeline?: boolean;
purpose?: "history" | "interactive";
logger: Logger;
}
/** The agent's history to read: from its runtime, or stored, with no provider session opened. */
export type AgentHistorySource =
| { kind: "live"; agent: ManagedAgent }
| { kind: "stored"; record: StoredAgentRecord };
export interface LoadAgentHistoryDeps extends EnsureAgentLoadedDeps {
agentManager: AgentLoaderManager & Pick<AgentManager, "hasStoredHistory">;
}
/**
* Resolves an agent for reading its history. A loaded agent is read live. A stored agent whose
* history the timeline holds is read without resuming its provider, so it reads even when its
* provider is no longer available. Otherwise the provider is resumed, which imports its history
* and requires the provider.
*/
export async function loadAgentHistory(
agentId: string,
deps: LoadAgentHistoryDeps,
): Promise<AgentHistorySource> {
const live = deps.agentManager.getAgent(agentId);
if (live) return { kind: "live", agent: live };
const record = await deps.agentStorage.get(agentId);
if (!record) throw new AgentNotFoundError(agentId);
if (await deps.agentManager.hasStoredHistory(agentId)) {
return { kind: "stored", record };
}
return { kind: "live", agent: await ensureAgentLoaded(agentId, deps) };
}
async function requireLoadableRecord(
agentId: string,
deps: EnsureAgentLoadedDeps,
): Promise<StoredAgentRecord> {
const record = await deps.agentStorage.get(agentId);
if (!record) {
throw new AgentNotFoundError(agentId);
}
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
if (!isStoredAgentProviderAvailable(record, validProviders)) {
throw new Error(`Agent ${agentId} references unavailable provider '${record.provider}'`);
}
return record;
}
export async function ensureUnarchivedAgentLoaded(
agentId: string,
deps: EnsureAgentLoadedDeps & {
@@ -109,7 +75,8 @@ export async function ensureAgentLoaded(
const inflight = pendingAgentInitializations.get(agentId);
if (inflight) {
return inflight;
inflight.options.broadcastTimeline ||= deps.broadcastTimeline === true;
return inflight.promise;
}
const existing = deps.agentManager.getAgent(agentId);
@@ -124,12 +91,24 @@ export async function ensureAgentLoaded(
const laterInflight = pendingAgentInitializations.get(agentId);
if (laterInflight) {
return laterInflight;
laterInflight.options.broadcastTimeline ||= deps.broadcastTimeline === true;
return laterInflight.promise;
}
const pendingOptions = {
broadcastTimeline: deps.broadcastTimeline === true,
};
const initPromise = (async () => {
const record = await requireLoadableRecord(agentId, deps);
const record = await deps.agentStorage.get(agentId);
if (!record) {
throw new AgentNotFoundError(agentId);
}
const validProviders = deps.validProviders ?? deps.agentManager.getRegisteredProviderIds();
if (!isStoredAgentProviderAvailable(record, validProviders)) {
throw new Error(`Agent ${agentId} references unavailable provider '${record.provider}'`);
}
const handle = toAgentPersistenceHandle(validProviders, record.persistence);
let snapshot: ManagedAgent;
@@ -151,16 +130,20 @@ export async function ensureAgentLoaded(
deps.logger.info({ agentId, provider: record.provider }, "Agent created from stored config");
}
await deps.agentManager.hydrateTimelineFromProvider(agentId, {
broadcast: () => pendingOptions.broadcastTimeline,
});
return deps.agentManager.getAgent(agentId) ?? snapshot;
})();
pendingAgentInitializations.set(agentId, initPromise);
const pending: PendingAgentInitialization = { promise: initPromise, options: pendingOptions };
pendingAgentInitializations.set(agentId, pending);
try {
return await initPromise;
} finally {
const current = pendingAgentInitializations.get(agentId);
if (current === initPromise) {
if (current === pending) {
pendingAgentInitializations.delete(agentId);
}
}
@@ -3,8 +3,6 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test, vi } from "vitest";
import pino, { type Logger } from "pino";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { AgentManager, type AgentManagerEvent } from "./agent-manager.js";
import { AGENT_STREAM_COALESCE_DEFAULT_WINDOW_MS } from "./agent-stream-coalescer.js";
@@ -15,8 +13,6 @@ import { FakeOmp } from "./providers/omp/test-utils/fake-omp.js";
import { PiRpcAgentClient } from "./providers/pi/agent.js";
import { FakePi } from "./providers/pi/test-utils/fake-pi.js";
import { projectTimelineRows } from "./timeline-projection.js";
import { AgentTimeline } from "./timeline/index.js";
import { DeferredTimelineBackend } from "./timeline/testing.js";
import type {
AgentCapabilityFlags,
AgentClient,
@@ -186,7 +182,6 @@ class TestAgentSession implements AgentSession {
class TestAgentClient implements AgentClient {
readonly capabilities = TEST_CAPABILITIES;
private sessionCounter = 0;
private history: AgentStreamEvent[] = [];
readonly sessions = new Map<string, TestAgentSession>();
constructor(readonly provider: AgentProvider = "codex") {}
@@ -200,7 +195,6 @@ class TestAgentClient implements AgentClient {
config,
`${config.provider}-session-${++this.sessionCounter}`,
);
session.setHistory(this.history);
this.sessions.set(config.cwd, session);
return session;
}
@@ -236,11 +230,6 @@ class TestAgentClient implements AgentClient {
return true;
}
/** The provider history of the sessions created from now on. */
setHistory(events: AgentStreamEvent[]): void {
this.history = [...events];
}
getSession(cwd: string): TestAgentSession {
const session = this.sessions.get(cwd);
if (!session) {
@@ -258,18 +247,13 @@ interface Harness {
cleanup: () => void;
}
function createHarness(options?: {
provider?: AgentProvider;
timeline?: AgentTimeline;
logger?: Logger;
}): Harness {
function createHarness(options?: { provider?: AgentProvider }): Harness {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-stream-coalescing-"));
const client = new TestAgentClient(options?.provider ?? "codex");
const manager = new AgentManager({
clients: { [client.provider]: client },
idFactory: createIdFactory(),
logger: options?.logger ?? createTestLogger(),
timeline: options?.timeline,
logger: createTestLogger(),
});
const events: AgentManagerEvent[] = [];
manager.subscribe((event) => events.push(event), { replayState: false });
@@ -288,20 +272,6 @@ function createIdFactory(): () => string {
return () => AGENT_IDS[index++] ?? `00000000-0000-4000-8000-${String(index).padStart(12, "0")}`;
}
/** Resumes an agent whose history Paseo does not hold, so it imports the provider's. */
async function resumeWithProviderHistory(
harness: Harness,
history: AgentStreamEvent[],
): Promise<{ agentId: string }> {
harness.client.setHistory(history);
const agent = await harness.manager.resumeAgentFromPersistence(
{ provider: harness.client.provider, sessionId: "provider-history" },
{ cwd: harness.workdir },
AGENT_IDS[0],
);
return { agentId: agent.id };
}
async function createManagedSession(
harness: Harness,
options?: { agentId?: string; provider?: AgentProvider; workdir?: string },
@@ -701,15 +671,15 @@ describe("target coalesced behavior", () => {
}
});
test("bounds tool output while importing provider history", async () => {
test("bounds tool output while hydrating provider history", async () => {
const harness = createHarness();
try {
const { agentId, session } = await createManagedSession(harness);
const output = `${"a".repeat(512 * 1024)}${"z".repeat(512 * 1024)}`;
const expectedItem = limitAgentTimelineItemContent(toolCall({ status: "completed", output }));
session.setHistory([timelineEvent(toolCall({ status: "completed", output }))]);
const { agentId } = await resumeWithProviderHistory(harness, [
timelineEvent(toolCall({ status: "completed", output })),
]);
await harness.manager.hydrateTimelineFromProvider(agentId, { force: true });
expect(getTimelineItems(await harness.manager.getTimelineRows(agentId))).toEqual([
expectedItem,
@@ -1300,81 +1270,6 @@ describe("target coalesced behavior", () => {
}
});
test.each(["turn_completed", "turn_failed", "turn_canceled"] as const)(
"%s waits for the final chunk an asynchronous timeline is still committing",
async (terminalType) => {
const harness = createHarness({ timeline: new AgentTimeline(new DeferredTimelineBackend()) });
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent(assistant("final chunk", "codex", "turn"));
session.pushEvent(terminalEvent(terminalType, "turn"));
const streamTypes = () =>
getStreamEvents(harness.events, agentId).map((event) =>
event.type === "agent_stream" ? event.event.type : event.type,
);
await expect.poll(streamTypes).toContain(terminalType);
const streamEvents = getStreamEvents(harness.events, agentId);
expect(streamEvents[0]).toMatchObject({
event: { type: "timeline", item: { type: "assistant_message", text: "final chunk" } },
seq: 1,
});
expect(streamTypes().indexOf(terminalType)).toBeGreaterThan(0);
} finally {
await harness.manager.flush();
harness.cleanup();
}
},
);
test("a final chunk the timeline fails to commit surfaces a history error after the turn", async () => {
const backend = new DeferredTimelineBackend();
const logs: Array<Record<string, unknown>> = [];
const harness = createHarness({
timeline: new AgentTimeline(backend),
logger: pino({ level: "error" }, { write: (line: string) => logs.push(JSON.parse(line)) }),
});
try {
const { agentId, session } = await createManagedSession(harness);
session.pushEvent(assistant("earlier chunk", "codex", "earlier"));
session.pushEvent(terminalEvent("turn_completed", "earlier"));
await expect.poll(() => getTimelineStreamEvents(harness.events, agentId)).toHaveLength(1);
await harness.manager.flush();
session.pushEvent({ type: "turn_started", provider: "codex", turnId: "turn" });
await expect.poll(() => harness.manager.getAgent(agentId)?.lifecycle).toBe("running");
backend.failNextAppend = true;
session.pushEvent(assistant("final chunk", "codex", "turn"));
session.pushEvent(terminalEvent("turn_completed", "turn"));
const completions = () =>
getStreamEvents(harness.events, agentId).filter(
(event) => event.type === "agent_stream" && event.event.type === "turn_completed",
);
await expect.poll(completions).toHaveLength(2);
await harness.manager.flush();
expect(harness.manager.getAgent(agentId)).toMatchObject({
lifecycle: "error",
lastError: "Conversation history could not be saved: disk full",
attention: { requiresAttention: true, attentionReason: "error" },
});
const earlier = { type: "assistant_message", text: "earlier chunk" };
expect(getTimelineStreamEvents(harness.events, agentId)).toEqual([
expect.objectContaining({ event: expect.objectContaining({ item: earlier }) }),
]);
expect(getTimelineItems(await harness.manager.getTimelineRows(agentId))).toEqual([earlier]);
expect(logs).toContainEqual(
expect.objectContaining({
msg: "Failed to record timeline item",
agentId,
err: expect.objectContaining({ message: "disk full" }),
}),
);
} finally {
harness.cleanup();
}
});
test("lifecycle paths are timer-safe", async () => {
vi.useFakeTimers();
@@ -1595,16 +1490,14 @@ describe("target coalesced behavior", () => {
}
});
test("history import projects immediately without waiting for a streaming window", async () => {
test("history hydration projects immediately without waiting for a streaming window", async () => {
vi.useFakeTimers();
const harness = createHarness();
try {
const { agentId } = await resumeWithProviderHistory(harness, [
assistant("a1"),
assistant("a2"),
reasoning("r1"),
reasoning("r2"),
]);
const { agentId, session } = await createManagedSession(harness);
session.setHistory([assistant("a1"), assistant("a2"), reasoning("r1"), reasoning("r2")]);
await harness.manager.hydrateTimelineFromProvider(agentId, { force: true });
const rows = await harness.manager.getTimelineRows(agentId);
expect(getTimelineItems(rows)).toEqual([
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -96,6 +96,7 @@ function createManagedAgent(overrides: ManagedAgentOverrides = {}): ManagedAgent
persistence: { ...basePersistence },
lastUsage: undefined,
lastError: lastErrorValue,
historyPrimed: true,
lastUserMessageAt: now,
attention: { requiresAttention: false },
};
@@ -74,7 +74,7 @@ export class AgentRunState {
*/
async waitForForegroundStart(agentId: string): Promise<void> {
const run = this.getPendingRun(agentId);
if (!run || run.start.status === "started") {
if (run?.start.status !== "pending") {
return;
}
await Promise.race([run.turnStartedPromise, run.settledPromise]);
@@ -471,7 +471,6 @@ export type AgentStreamEvent =
provider: AgentProvider;
turnId?: string;
timestamp?: string;
turnMetrics?: AgentMetric[];
}
| {
type: "permission_requested";
@@ -587,6 +586,8 @@ export interface AgentSlashCommand {
}
export interface ListImportableSessionsOptions {
/** Aborts provider work when the caller stops waiting for a listing. */
signal?: AbortSignal;
providerOptions?: ProviderOptions;
limit?: number;
/** Optional case-insensitive descriptor search text. */
@@ -639,60 +640,6 @@ export interface ImportedProviderSession {
providerSubagentEvents?: Extract<AgentStreamEvent, { type: "provider_subagent" }>[];
}
/**
* What a conversation rewind removed from the provider session. `at_target`: the target prompt and
* everything after it. `after`: the provider kept history through the prompt `retainedMessageId`
* only (null: it kept nothing), which can cut earlier than the target.
*/
export type ConversationRewindCut =
| { kind: "at_target" }
| { kind: "after"; retainedMessageId: string | null };
/**
* How a conversation rewind the provider finished ended: a cut, or `unreported` when the provider
* finished without saying what it removed. Paseo then judges it from the prompts a resumed
* session's `streamHistory` replays.
*/
export type ConversationRewindResult = ConversationRewindCut | { kind: "unreported" };
/** The provider conversation is known to be unchanged; the rewind can be abandoned. */
export class RewindNotAppliedError extends Error {
constructor(message: string, options?: { cause?: unknown }) {
super(message, options);
this.name = "RewindNotAppliedError";
}
/** Marks a failure that happened before the provider conversation could change. */
static from(error: unknown): RewindNotAppliedError {
if (error instanceof RewindNotAppliedError) return error;
return new RewindNotAppliedError(error instanceof Error ? error.message : String(error), {
cause: error,
});
}
}
/**
* The provider applied the rewind with a known cut, then failed while refreshing its local
* session state. Paseo commits the confirmed cut and lets Reload reopen the session.
*/
export class RewindAppliedError extends Error {
constructor(
readonly cut: ConversationRewindCut,
message: string,
options?: { cause?: unknown },
) {
super(message, options);
this.name = "RewindAppliedError";
}
static from(cut: ConversationRewindCut, error: unknown): RewindAppliedError {
if (error instanceof RewindAppliedError) return error;
return new RewindAppliedError(cut, error instanceof Error ? error.message : String(error), {
cause: error,
});
}
}
export interface AgentSessionConfig {
provider: AgentProvider;
cwd: string;
@@ -845,17 +792,9 @@ export interface AgentSession {
* ended, so the stored options still match what runs.
*/
applyOptions?(options: ProviderOptions): Promise<Record<string, unknown> | void>;
/**
* Rewinds the provider conversation to before the prompt `messageId`. Resolves with what the
* provider actually removed; `void` means exactly the target and everything after it. Rejects
* with `RewindNotAppliedError` only when the conversation is known to be unchanged; any other
* rejection leaves the outcome unknown, and Paseo judges it later from the prompts `streamHistory`
* replays once the session is resumed.
*/
revertConversation?(input: { messageId: string }): Promise<ConversationRewindResult | void>;
revertConversation?(input: { messageId: string }): Promise<void>;
revertFiles?(input: { messageId: string }): Promise<void>;
/** `revertConversation` plus file changes, with the same outcome contract. */
revertBoth?(input: { messageId: string }): Promise<ConversationRewindResult | void>;
revertBoth?(input: { messageId: string }): Promise<void>;
/**
* Out-of-band prompt handler. When non-null, the manager runs the returned
* handler instead of allocating a turn. The handler emits stream events
@@ -124,6 +124,7 @@ function createManagedAgent(overrides: ManagedAgentOverrides = {}): ManagedAgent
sessionId: overrides.sessionId ?? "session-123",
}),
persistence: overrides.persistence ?? null,
historyPrimed: overrides.historyPrimed ?? true,
lastUserMessageAt: overrides.lastUserMessageAt ?? core.now,
lastUsage: overrides.lastUsage,
sessionMetrics: overrides.sessionMetrics,
@@ -1,4 +1,4 @@
import type { ProjectedTimelineRow, TimelineRetirement } from "./timeline-projection.js";
import type { ProjectedTimelineRow } from "./timeline-projection.js";
import type { AgentMetric, AgentTimelineItem } from "./agent-sdk-types.js";
export interface AgentTimelineRow {
@@ -14,11 +14,6 @@ export interface AgentTimelineRow {
export interface AgentTimelineCursor {
epoch: string;
seq: number;
/**
* For a reader that cannot apply retirements: the retirement count its view reflects. The
* cursor is stale once another retirement has happened.
*/
retirementCount?: number;
}
export type AgentTimelineFetchDirection = "tail" | "before" | "after";
@@ -53,8 +48,23 @@ export interface AgentTimelineFetchResult {
startSeq: number | null;
endSeq: number | null;
rows: ProjectedTimelineRow[];
/** Retirements whose seq lies in the page's span. A client applies them before the rows. */
retirements: TimelineRetirement[];
/** Retirements of this history so far. */
retirementCount: number;
}
export interface AgentTimelineStore {
appendCommitted(
agentId: string,
item: AgentTimelineItem,
options?: { timestamp?: string; turnId?: string },
): Promise<AgentTimelineRow>;
fetchCommitted(
agentId: string,
options?: AgentTimelineFetchOptions,
): Promise<AgentTimelineFetchResult>;
getLatestCommittedSeq(agentId: string): Promise<number>;
getCommittedRows(agentId: string): Promise<AgentTimelineRow[]>;
getLastItem(agentId: string): Promise<AgentTimelineItem | null>;
getLastAssistantMessage(agentId: string): Promise<string | null>;
deleteAgent(agentId: string): Promise<void>;
bulkInsert(agentId: string, rows: readonly AgentTimelineRow[]): Promise<void>;
updateCommittedRow(agentId: string, row: AgentTimelineRow): Promise<void>;
}
@@ -0,0 +1,604 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { selectReferenceProjectedTimelinePage } from "./test-utils/timeline-page-reference.js";
import type { AgentTimelineItem } from "./agent-sdk-types.js";
import { InMemoryAgentTimelineStore } from "./agent-timeline-store.js";
describe("InMemoryAgentTimelineStore", () => {
it("resets stale forward cursors to complete available turns", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "current" });
for (let index = 0; index < 60; index++)
store.append(
"agent",
{
type: "tool_call",
callId: `call-${index}`,
name: "shell",
status: "completed",
error: null,
detail: { type: "unknown", input: null, output: null },
},
{ turnId: "run" },
);
const page = store.fetch("agent", {
direction: "after",
cursor: { epoch: "old", seq: 10 },
limit: 40,
wholeTurns: true,
});
expect(page.rows).toHaveLength(60);
expect(page).toMatchObject({
reset: true,
staleCursor: true,
startSeq: 1,
endSeq: 60,
hasOlder: false,
hasNewer: false,
});
});
it("clamps an overshooting before cursor into the bounded tail window", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent-1", {
epoch: "epoch-1",
nextSeq: 8,
rows: [
{
seq: 5,
timestamp: "2026-01-01T00:00:00.000Z",
item: { type: "assistant_message", text: "five", messageId: "five" },
},
{
seq: 6,
timestamp: "2026-01-01T00:00:01.000Z",
item: { type: "assistant_message", text: "six", messageId: "six" },
},
{
seq: 7,
timestamp: "2026-01-01T00:00:02.000Z",
item: { type: "assistant_message", text: "seven", messageId: "seven" },
},
],
});
const result = store.fetch("agent-1", {
direction: "before",
cursor: { epoch: "epoch-1", seq: 100 },
limit: 2,
});
expect(result).toMatchObject({
epoch: "epoch-1",
direction: "before",
reset: false,
staleCursor: false,
gap: false,
window: { minSeq: 5, maxSeq: 7, nextSeq: 8 },
hasOlder: true,
hasNewer: false,
rows: [
{
seq: 6,
timestamp: "2026-01-01T00:00:01.000Z",
item: { type: "assistant_message", text: "six", messageId: "six" },
},
{
seq: 7,
timestamp: "2026-01-01T00:00:02.000Z",
item: { type: "assistant_message", text: "seven", messageId: "seven" },
},
],
});
});
it("returns a bounded reset window when an after cursor is behind retained history", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent-1", {
epoch: "epoch-1",
nextSeq: 8,
rows: [
{
seq: 5,
timestamp: "2026-01-01T00:00:00.000Z",
item: { type: "assistant_message", text: "five", messageId: "five" },
},
{
seq: 6,
timestamp: "2026-01-01T00:00:01.000Z",
item: { type: "assistant_message", text: "six", messageId: "six" },
},
{
seq: 7,
timestamp: "2026-01-01T00:00:02.000Z",
item: { type: "assistant_message", text: "seven", messageId: "seven" },
},
],
});
const result = store.fetch("agent-1", {
direction: "after",
cursor: { epoch: "epoch-1", seq: 1 },
limit: 1,
});
expect(result).toMatchObject({
epoch: "epoch-1",
direction: "after",
reset: true,
staleCursor: false,
gap: true,
window: { minSeq: 5, maxSeq: 7, nextSeq: 8 },
hasOlder: true,
hasNewer: false,
rows: [
{
seq: 7,
timestamp: "2026-01-01T00:00:02.000Z",
item: { type: "assistant_message", text: "seven", messageId: "seven" },
},
],
});
});
});
describe("projected timeline retention", () => {
it("retains one full tool state while streaming every source update", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent");
for (let seq = 1; seq <= 2000; seq++) {
const item = {
type: "tool_call" as const,
callId: "child",
name: "task",
status: "running" as const,
error: null,
detail: { type: "plain_text" as const, label: "Child", text: "x".repeat(seq * 128) },
};
expect(store.append("agent", item)).toMatchObject({ seq, item });
}
const result = store.fetch("agent", { limit: 0 });
expect(result.rows).toHaveLength(1);
expect(JSON.stringify(result.rows).length).toBeLessThan(260_000);
expect(result.window.maxSeq).toBe(2000);
});
it("catches up a mid-message cursor with the complete projected message", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "e" });
store.append("agent", { type: "assistant_message", messageId: "m", text: "A" });
store.append("agent", { type: "assistant_message", messageId: "m", text: "B" });
expect(
store.fetch("agent", { direction: "after", cursor: { epoch: "e", seq: 1 } }).rows,
).toMatchObject([
{
item: { text: "AB" },
seqStart: 1,
seqEnd: 2,
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
},
]);
});
it("serves a merged assistant message within the item budget", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("agent", { epoch: "e" });
const chunk = "a".repeat(200 * 1024);
for (let index = 0; index < 10; index++) {
store.append("agent", { type: "assistant_message", messageId: "m", text: chunk });
}
const [row] = store.fetch("agent", { limit: 1 }).rows;
expect(row).toMatchObject({ seqStart: 1, seqEnd: 10 });
expect(row.item).toMatchObject({ type: "assistant_message", messageId: "m" });
expect(Buffer.byteLength(JSON.stringify(row.item))).toBeLessThanOrEqual(256 * 1024);
expect(store.getLastAssistantMessage("agent")).toHaveLength(10 * chunk.length);
});
});
describe("projected sequence ownership", () => {
it("preserves fetched coverage when another source chunk arrives", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "assistant_message", text: "A" });
const before = store.fetch("a");
store.append("a", { type: "assistant_message", text: "B" });
expect(before.rows[0]).toMatchObject({
item: { text: "A" },
seqEnd: 1,
sourceSeqRanges: [{ startSeq: 1, endSeq: 1 }],
});
expect(store.fetch("a").rows[0]).toMatchObject({
item: { text: "AB" },
seqEnd: 2,
sourceSeqRanges: [{ startSeq: 1, endSeq: 2 }],
});
});
it("preserves source positions when seeding a projected history whose last update is an earlier tool", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
const tool = {
type: "tool_call" as const,
callId: "t",
name: "shell",
error: null,
detail: { type: "plain_text" as const, label: "work" },
};
store.append("a", { ...tool, status: "running" });
store.append("a", { type: "assistant_message", text: "Answer" });
store.append("a", { ...tool, status: "completed" });
store.initialize("b", { rows: store.getRows("a") });
expect(store.getLastItem("b")).toMatchObject({ type: "tool_call", status: "completed" });
expect(store.getLastAssistantMessage("b")).toBe("Answer");
expect(store.append("b", { type: "user_message", text: "next" }).seq).toBe(4);
expect(store.getLastItem("b")).toEqual({ type: "user_message", text: "next" });
expect(store.fetch("b").rows.map((row) => row.seqStart)).toEqual([1, 2, 4]);
});
it("returns the last projected assistant message without joining different messages", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "assistant_message", messageId: "first", text: "First" });
store.append("a", { type: "assistant_message", messageId: "second", text: "Sec" });
store.append("a", { type: "assistant_message", messageId: "second", text: "ond" });
expect(store.getLastAssistantMessage("a")).toBe("Second");
});
});
describe("turn metrics", () => {
const metrics = [
{ label: "Model", value: "gpt-5.5" },
{ label: "Cache", value: "82%", tone: "ok" as const },
];
const tool = {
type: "tool_call" as const,
callId: "t",
name: "shell",
error: null,
detail: { type: "plain_text" as const, label: "work" },
};
function turnMetricsByRow(store: InMemoryAgentTimelineStore, agentId: string) {
return store.fetch(agentId).rows.map((row) => row.turnMetrics ?? null);
}
it("puts a turn's metrics on its last assistant message, where its footer shows", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "go" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "First" }, { turnId: "turn-1" });
store.append("a", { ...tool, status: "completed" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "Done" }, { turnId: "turn-1" });
store.append("a", { type: "reasoning", text: "wrap up" }, { turnId: "turn-1" });
const stamped = store.stampTurnMetrics("a", metrics, { turnId: "turn-1" });
expect(stamped).toMatchObject({ seq: 4, item: { text: "Done" }, turnMetrics: metrics });
expect(turnMetricsByRow(store, "a")).toEqual([null, null, null, metrics, null]);
});
it("falls back to the turn's last row when it is a tool call and no message was written", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "go" });
store.append("a", { type: "reasoning", text: "thinking" });
store.append("a", { ...tool, status: "completed" });
store.stampTurnMetrics("a", metrics);
expect(turnMetricsByRow(store, "a")).toEqual([null, null, metrics]);
});
it("leaves the previous turn alone when the completed turn has no footer row", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "one" });
store.append("a", { type: "assistant_message", text: "Answer one" });
store.append("a", { type: "user_message", text: "two" });
store.append("a", { type: "reasoning", text: "thinking" });
expect(store.stampTurnMetrics("a", metrics)).toBeNull();
expect(turnMetricsByRow(store, "a")).toEqual([null, null, null, null]);
});
it("finds the completed turn by id when a newer turn already has rows", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "one" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "Answer one" }, { turnId: "turn-1" });
store.append("a", { type: "user_message", text: "two" }, { turnId: "turn-2" });
store.append("a", { type: "assistant_message", text: "Answer two" }, { turnId: "turn-2" });
store.stampTurnMetrics("a", metrics, { turnId: "turn-1" });
expect(turnMetricsByRow(store, "a")).toEqual([null, metrics, null, null]);
});
it("stamps nothing for a turn that wrote no rows instead of the turn before it", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "one" }, { turnId: "turn-1" });
store.append("a", { type: "assistant_message", text: "Answer one" }, { turnId: "turn-1" });
expect(store.stampTurnMetrics("a", metrics, { turnId: "turn-2" })).toBeNull();
expect(turnMetricsByRow(store, "a")).toEqual([null, null]);
});
it("keeps the metrics when a late update lands on the stamped row", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
store.append("a", { type: "user_message", text: "go" }, { turnId: "turn-1" });
store.append("a", { ...tool, status: "running" }, { turnId: "turn-1" });
store.stampTurnMetrics("a", metrics, { turnId: "turn-1" });
store.append("a", { ...tool, status: "completed" }, { turnId: "turn-1" });
expect(store.fetch("a").rows[1]).toMatchObject({
item: { status: "completed" },
turnMetrics: metrics,
});
});
it("keeps the stats on a message whose chunks the projection merges", () => {
const store = new InMemoryAgentTimelineStore();
const at = "2026-11-22T00:00:00.000Z";
store.initialize("a", {
rows: [
{ seq: 1, timestamp: at, item: { type: "user_message", text: "go" } },
{ seq: 2, timestamp: at, item: { type: "assistant_message", text: "Do" } },
{
seq: 3,
timestamp: at,
item: { type: "assistant_message", text: "ne" },
turnMetrics: metrics,
},
],
});
const rows = store.fetch("a").rows;
expect(rows).toHaveLength(2);
expect(rows[1]).toMatchObject({ item: { text: "Done" }, turnMetrics: metrics });
});
it("keeps the stats on a tool card whose updates the projection merges", () => {
const store = new InMemoryAgentTimelineStore();
const at = "2026-11-22T00:00:00.000Z";
store.initialize("a", {
rows: [
{ seq: 1, timestamp: at, item: { type: "user_message", text: "go" } },
{ seq: 2, timestamp: at, item: { ...tool, status: "running" } },
{ seq: 3, timestamp: at, item: { ...tool, status: "completed" }, turnMetrics: metrics },
],
});
const rows = store.fetch("a").rows;
expect(rows).toHaveLength(2);
expect(rows[1]).toMatchObject({ item: { status: "completed" }, turnMetrics: metrics });
});
it("restores stamped rows when a timeline is seeded from stored rows", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("live");
store.append("live", { type: "user_message", text: "go" });
store.append("live", { type: "assistant_message", text: "Done" });
store.stampTurnMetrics("live", metrics);
store.initialize("projected", { rows: store.getRows("live") });
store.initialize("canonical", {
rows: [
{
seq: 1,
timestamp: "2026-11-22T00:00:00.000Z",
item: { type: "user_message", text: "go" },
},
{
seq: 2,
timestamp: "2026-11-22T00:00:01.000Z",
item: { type: "assistant_message", text: "Done" },
turnMetrics: metrics,
},
],
});
expect(turnMetricsByRow(store, "projected")).toEqual([null, metrics]);
expect(turnMetricsByRow(store, "canonical")).toEqual([null, metrics]);
});
});
it("includes transitive tool updates in a contiguous projected tail", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a");
const tool = (callId: string, status: "running" | "completed") => ({
type: "tool_call" as const,
callId,
name: "shell",
status,
error: null,
detail: { type: "plain_text" as const, label: "work" },
});
store.append("a", tool("first", "running"));
store.append("a", tool("second", "running"));
store.append("a", { type: "user_message", text: "Continue" });
store.append("a", tool("first", "completed"));
store.append("a", { type: "assistant_message", text: "Answer" });
store.append("a", tool("second", "completed"));
const tail = store.fetch("a", { limit: 1 });
expect(tail.rows.map((row) => row.seqStart)).toEqual([1, 2, 3, 5]);
expect(tail).toMatchObject({ startSeq: 1, endSeq: 6, hasOlder: false });
});
async function measureTimelineTail(wholeTurns: boolean) {
const fixture = fileURLToPath(
new URL("./test-utils/timeline-responsiveness.ts", import.meta.url),
);
const { stdout, stderr } = await promisify(execFile)(
process.execPath,
["--expose-gc", "--import", "tsx", fixture, String(wholeTurns)],
{ timeout: 15_000 },
);
process.stderr.write(stderr);
return JSON.parse(stdout) as {
result: ReturnType<InMemoryAgentTimelineStore["fetch"]>;
blockingMs: number;
};
}
it("excludes unrelated test-runner CPU from the timeline fetch budget", async () => {
let unrelatedWork: ReturnType<typeof setImmediate>;
const burnCpu = () => {
const threadCpuUsage: (previous?: NodeJS.CpuUsage) => NodeJS.CpuUsage = Reflect.get(
process,
"threadCpuUsage",
);
const start = threadCpuUsage();
let elapsed: NodeJS.CpuUsage;
do {
elapsed = threadCpuUsage(start);
} while (elapsed.user + elapsed.system < 80_000);
unrelatedWork = setImmediate(burnCpu);
};
unrelatedWork = setImmediate(burnCpu);
try {
const { result: tail, blockingMs } = await measureTimelineTail(false);
expect(tail.rows).toHaveLength(200);
expect(tail.startSeq).toBe(99_801);
expect(tail.endSeq).toBe(100_000);
expect(blockingMs).toBeLessThan(50);
} finally {
clearImmediate(unrelatedWork);
}
});
it.each([false, true])(
"serves tail 200 from 100,000 retained rows without stalling the loop (wholeTurns=%s)",
async (wholeTurns) => {
const { result: tail, blockingMs } = await measureTimelineTail(wholeTurns);
expect(tail.rows).toHaveLength(200);
expect(tail.startSeq).toBe(99_801);
expect(tail.endSeq).toBe(100_000);
expect(blockingMs).toBeLessThan(50);
},
);
it("matches the previous reprojecting selector on seeded randomized timelines", () => {
let seed = 0x76aabbcc;
const random = (bound: number) => {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return Math.floor((seed / 0x1_0000_0000) * bound);
};
for (let scenario = 0; scenario < 100; scenario++) {
const store = new InMemoryAgentTimelineStore();
store.initialize("a", { epoch: "e" });
for (let seq = 1; seq <= 100; seq++) {
const identity = String(random(8));
const text = String(seq);
const items: AgentTimelineItem[] = [
{ type: "user_message", text },
{ type: "assistant_message", text },
{ type: "assistant_message", text, messageId: identity },
{ type: "reasoning", text },
{
type: "tool_call",
callId: identity,
name: "shell",
status: "running",
error: null,
detail: { type: "plain_text", label: text },
},
{
type: "plugin",
id: identity,
pluginId: "test",
kind: "state",
version: 1,
data: { text },
},
];
store.append("a", items[random(items.length)], { turnId: String(random(3)) });
}
// Include rehydration of already-projected rows, with non-monotonic seqEnd.
store.initialize("b", { rows: store.getRows("a"), epoch: "e" });
for (const agentId of ["a", "b"]) {
assertSelectionMatchesReference(store, agentId);
store.append(agentId, { type: "assistant_message", text: "later" });
assertSelectionMatchesReference(store, agentId);
}
}
});
function assertSelectionMatchesReference(store: InMemoryAgentTimelineStore, agentId: string): void {
for (const direction of ["tail", "before", "after"] as const) {
for (const limit of [0, 1, 7, 200]) {
for (const cursorSeq of [0, 1, 25, 50, 99, 100, 150]) {
const actual = store.fetch(agentId, {
direction,
limit,
cursor: { epoch: "e", seq: cursorSeq },
});
const expected = selectReferenceProjectedTimelinePage({
rows: store.getRows(agentId),
bounds: actual.window,
direction,
limit,
cursorSeq,
});
expect({
...expected,
entries: undefined,
rows: expected.entries.map((entry) => Object.assign({ seq: entry.seqEnd }, entry)),
}).toEqual({
entries: undefined,
rows: actual.rows,
startSeq: actual.startSeq,
endSeq: actual.endSeq,
hasOlder: actual.hasOlder,
hasNewer: actual.hasNewer,
});
}
}
}
}
it("continues a scroll across appends and lifecycle collapse without losing source coverage", () => {
const store = new InMemoryAgentTimelineStore();
store.initialize("a", { epoch: "e" });
const tool: AgentTimelineItem = {
type: "tool_call",
callId: "t",
name: "shell",
status: "running",
error: null,
detail: { type: "plain_text", label: "work" },
};
store.append("a", tool);
for (let seq = 2; seq <= 5; seq++) store.append("a", { type: "user_message", text: String(seq) });
const first = store.fetch("a", { direction: "after", cursor: { epoch: "e", seq: 0 }, limit: 2 });
expect(first.endSeq).toBe(2);
store.append("a", { ...tool, status: "completed" });
store.append("a", { type: "assistant_message", text: "Done" });
expect(first.rows[0].item).toMatchObject({ status: "running" });
const second = store.fetch("a", {
direction: "after",
cursor: { epoch: "e", seq: first.endSeq! },
limit: 2,
});
expect(second.rows.map((row) => row.seqStart)).toEqual([3, 4]);
expect(second.endSeq).toBe(4);
const third = store.fetch("a", {
direction: "after",
cursor: { epoch: "e", seq: second.endSeq! },
limit: 2,
});
expect(third.rows.map((row) => row.seqStart)).toEqual([1, 5]);
expect(third.rows[0].item).toMatchObject({ status: "completed" });
expect(third.endSeq).toBe(6);
const last = store.fetch("a", {
direction: "after",
cursor: { epoch: "e", seq: third.endSeq! },
limit: 2,
});
expect(last.rows.map((row) => row.item)).toEqual([{ type: "assistant_message", text: "Done" }]);
expect(last.endSeq).toBe(7);
expect(last.hasNewer).toBe(false);
});
@@ -0,0 +1,199 @@
import { randomUUID } from "node:crypto";
import { TimelineProjection, type ProjectedTimelineRow } from "./timeline-projection.js";
import { limitAgentTimelineItemContent } from "./agent-timeline-content.js";
import type { AgentMetric, AgentTimelineItem } from "./agent-sdk-types.js";
import type {
AgentTimelineFetchOptions,
AgentTimelineFetchResult,
AgentTimelineRow,
} from "./agent-timeline-store-types.js";
export interface SeedAgentTimelineOptions {
items?: readonly AgentTimelineItem[];
rows?: readonly AgentTimelineRow[];
epoch?: string;
nextSeq?: number;
timestamp?: string;
}
interface AgentTimelineState {
epoch: string;
projection: TimelineProjection;
minSeq: number;
nextSeq: number;
}
const DEFAULT_TIMELINE_FETCH_LIMIT = 200;
function cloneRow<T extends AgentTimelineRow>(row: T): T {
return { ...row };
}
export class InMemoryAgentTimelineStore {
private readonly states = new Map<string, AgentTimelineState>();
has(agentId: string): boolean {
return this.states.has(agentId);
}
initialize(agentId: string, options?: SeedAgentTimelineOptions): void {
const timestamp = options?.timestamp ?? new Date().toISOString();
const rows = options?.rows?.length
? options.rows.map(cloneRow)
: this.buildRowsFromItems(options?.items ?? [], options?.nextSeq ?? 1, timestamp);
const nextSeq = rows.reduce((next, row) => Math.max(next, row.seq + 1), options?.nextSeq ?? 1);
const projection = new TimelineProjection(rows);
this.states.set(agentId, {
epoch: options?.epoch ?? randomUUID(),
projection,
minSeq: projection.getRows()[0]?.seqStart ?? 0,
nextSeq,
});
}
delete(agentId: string): void {
this.states.delete(agentId);
}
getItems(agentId: string): AgentTimelineItem[] {
return this.requireState(agentId)
.projection.getRows()
.map((row) => row.item);
}
getRows(agentId: string): ProjectedTimelineRow[] {
return this.requireState(agentId).projection.getRows().map(cloneRow);
}
getSubmittedUserMessage(agentId: string, clientMessageId: string): AgentTimelineRow | null {
const row = this.requireState(agentId)
.projection.getRows()
.find(
(candidate) =>
candidate.item.type === "user_message" &&
candidate.item.clientMessageId === clientMessageId,
);
return row ? cloneRow(row) : null;
}
enrichSubmittedUserMessage(
agentId: string,
clientMessageId: string,
providerMessageId: string,
): AgentTimelineRow | null {
return this.requireState(agentId).projection.enrichSubmittedUserMessage(
clientMessageId,
providerMessageId,
);
}
/** Records a completed turn's metrics on its footer row. Null when the turn has none. */
stampTurnMetrics(
agentId: string,
metrics: AgentMetric[],
options?: { turnId?: string },
): AgentTimelineRow | null {
return this.requireState(agentId).projection.stampTurnMetrics(metrics, options?.turnId);
}
getEpoch(agentId: string): string {
return this.requireState(agentId).epoch;
}
getHead(agentId: string): { epoch: string; seq: number } {
const state = this.requireState(agentId);
return { epoch: state.epoch, seq: state.nextSeq - 1 };
}
fetch(agentId: string, options?: AgentTimelineFetchOptions): AgentTimelineFetchResult {
const state = this.requireState(agentId);
const direction = options?.direction ?? "tail";
const cursor = options?.cursor;
const hasRows = state.minSeq !== 0;
const window = { minSeq: state.minSeq, maxSeq: state.nextSeq - 1, nextSeq: state.nextSeq };
const staleCursor = cursor !== undefined && cursor.epoch !== state.epoch;
const gap =
!staleCursor &&
direction === "after" &&
cursor !== undefined &&
hasRows &&
cursor.seq < state.minSeq - 1;
const reset = staleCursor || gap;
const page = state.projection.selectPage({
bounds: window,
direction: reset ? "tail" : direction,
cursorSeq: cursor?.seq,
limit: options?.limit ?? DEFAULT_TIMELINE_FETCH_LIMIT,
wholeTurns: options?.wholeTurns,
});
return {
epoch: state.epoch,
direction,
reset,
staleCursor,
gap,
window,
hasOlder: page.hasOlder,
hasNewer: page.hasNewer,
startSeq: page.startSeq,
endSeq: page.endSeq,
// Stored rows are already within budget; this bounds assistant and reasoning merges.
rows: page.entries.map((entry) =>
Object.assign({ seq: entry.seqEnd }, entry, {
item: limitAgentTimelineItemContent(entry.item),
}),
),
};
}
append(
agentId: string,
item: AgentTimelineItem,
options?: { timestamp?: string; providerMessageId?: string; turnId?: string },
): AgentTimelineRow {
const state = this.requireState(agentId);
const row: AgentTimelineRow = {
seq: state.nextSeq,
timestamp: options?.timestamp ?? new Date().toISOString(),
item,
...(options?.turnId ? { turnId: options.turnId } : {}),
...(options?.providerMessageId ? { providerMessageId: options.providerMessageId } : {}),
};
state.nextSeq += 1;
if (state.minSeq === 0) state.minSeq = row.seq;
state.projection.append(row);
return cloneRow(row);
}
getLastItem(agentId: string): AgentTimelineItem | null {
const state = this.requireState(agentId);
return state.projection.getLastItem(state.nextSeq - 1);
}
getLastAssistantMessage(agentId: string): string | null {
return this.requireState(agentId).projection.getLastAssistantMessage();
}
private requireState(agentId: string): AgentTimelineState {
const state = this.states.get(agentId);
if (!state) {
throw new Error(`Unknown agent '${agentId}'`);
}
return state;
}
private buildRowsFromItems(
items: readonly AgentTimelineItem[],
startSeq: number,
timestamp: string,
): AgentTimelineRow[] {
let nextSeq = startSeq;
return items.map((item) => {
const row: AgentTimelineRow = {
seq: nextSeq,
timestamp,
item,
};
nextSeq += 1;
return row;
});
}
}
@@ -1,7 +1,29 @@
import { expect, test } from "vitest";
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pino from "pino";
import { afterEach, expect, test, vi } from "vitest";
import type { AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import { registerAgentAutoArchive } from "./create-agent-lifecycle-dispatch.js";
import type { ForgeService } from "../../services/forge-service.js";
import { createWorktree } from "../../utils/worktree.js";
import { WorkspaceAutomationBlockedError } from "../workspace-automation-gate.js";
import type { WorkspaceGitService } from "../workspace-git-service.js";
import type { PersistedWorkspaceRecord } from "../workspace-registry.js";
import type { AgentManager, AgentManagerEvent, AgentSubscriber } from "./agent-manager.js";
import type { AgentStorage } from "./agent-storage.js";
import {
CreateAgentLifecycleDispatch,
registerAgentAutoArchive,
} from "./create-agent-lifecycle-dispatch.js";
const cleanupPaths: string[] = [];
afterEach(() => {
for (const target of cleanupPaths.splice(0)) {
rmSync(target, { recursive: true, force: true });
}
});
class AgentLifecycleEvents {
private readonly listeners = new Set<AgentSubscriber>();
@@ -25,6 +47,109 @@ class AgentLifecycleEvents {
}
}
async function createUntrustedWorktreeFixture(slug: string, markerName: string) {
const tempDir = mkdtempSync(path.join(tmpdir(), "lifecycle-dispatch-"));
cleanupPaths.push(tempDir);
const repoDir = path.join(tempDir, "repo");
const paseoHome = path.join(tempDir, ".paseo");
mkdirSync(repoDir, { recursive: true });
execFileSync("git", ["init", "-b", "main"], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["config", "user.email", "test@getpaseo.local"], {
cwd: repoDir,
stdio: "pipe",
});
execFileSync("git", ["config", "user.name", "Paseo Test"], { cwd: repoDir, stdio: "pipe" });
writeFileSync(
path.join(repoDir, "paseo.json"),
JSON.stringify({
worktree: {
teardown: [
`node -e "require('fs').writeFileSync(process.env.PASEO_SOURCE_CHECKOUT_PATH + '/${markerName}', 'ran')"`,
],
},
}),
);
execFileSync("git", ["add", "."], { cwd: repoDir, stdio: "pipe" });
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "init"], {
cwd: repoDir,
stdio: "pipe",
});
const worktree = await createWorktree({
cwd: repoDir,
worktreeSlug: slug,
source: { kind: "branch-off", baseBranch: "main", branchName: slug },
paseoHome,
});
const workspace: PersistedWorkspaceRecord = {
workspaceId: `ws-${slug}`,
projectId: "proj-1",
cwd: worktree.worktreePath,
kind: "worktree",
worktreeRoot: worktree.worktreePath,
isPaseoOwnedWorktree: true,
mainRepoRoot: repoDir,
createdAt: "2026-11-24T00:00:00.000Z",
updatedAt: "2026-11-24T00:00:00.000Z",
};
const blockedSource = {
kind: "change_request" as const,
forge: "github",
number: 99,
headRepository: "contributor/paseo",
};
const assertWorkspaceAutomationAllowed = vi.fn(async (id: string) => {
if (id === workspace.workspaceId) {
throw new WorkspaceAutomationBlockedError(blockedSource);
}
});
const activeWorkspaces = [workspace];
const archived = new Set<string>();
const events = new AgentLifecycleEvents();
const agentManager = {
subscribe: (cb: AgentSubscriber) => events.subscribe(cb),
listAgents: () => [],
getAgent: () => null,
archiveAgent: vi.fn(async () => ({ archivedAt: new Date().toISOString() })),
archiveSnapshot: vi.fn(async () => ({})),
} as unknown as AgentManager;
const dispatch = new CreateAgentLifecycleDispatch({
paseoHome,
getWorkspace: async (id) => (id === workspace.workspaceId ? workspace : null),
assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: async () => false,
agentManager,
agentStorage: { listByWorkspace: async () => [] } as unknown as AgentStorage,
github: { invalidate: () => {} } as unknown as ForgeService,
workspaceGitService: {
getSnapshot: vi.fn(async () => null),
invalidateWorktrees: () => {},
} as unknown as WorkspaceGitService,
createPaseoWorktreeWorkflow: vi.fn(),
archiveAgentForClose: vi.fn(async () => undefined),
findWorkspaceIdForCwd: async () => workspace.workspaceId,
listActiveWorkspaces: async () => activeWorkspaces.filter((w) => !archived.has(w.workspaceId)),
archiveWorkspaceRecord: async (id) => {
archived.add(id);
},
emit: vi.fn(),
emitAgentRemove: vi.fn(async () => undefined),
emitWorkspaceUpdatesForWorkspaceIds: vi.fn(async () => undefined),
markWorkspaceArchiving: vi.fn(),
clearWorkspaceArchiving: vi.fn(),
killTerminalsForWorkspace: vi.fn(async () => undefined),
logger: pino({ level: "silent" }),
});
return {
dispatch,
events,
marker: path.join(repoDir, markerName),
createdWorktree: { worktree, workspace },
archived,
assertWorkspaceAutomationAllowed,
};
}
test("auto-archive self-releases once and later cancellation waits harmlessly", async () => {
const agentId = "4a7e2521-286d-4ad5-af35-e091c55302e3";
const agents = new AgentLifecycleEvents();
@@ -45,3 +170,41 @@ test("auto-archive self-releases once and later cancellation waits harmlessly",
expect(archiveCount).toBe(1);
expect(agents.listenerCount()).toBe(0);
});
test("failed create cleanup skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("failed-create-untrusted", "failed-create-teardown.log");
await dispatch.cleanupCreatedWorktreeAfterFailedAgentCreate({
createdWorktree,
createdAgentId: null,
});
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
test("first-turn auto-archive skips teardown commands for an unapproved cross-repository checkout", async () => {
const { dispatch, events, marker, createdWorktree, archived, assertWorkspaceAutomationAllowed } =
await createUntrustedWorktreeFixture("auto-archive-untrusted", "auto-archive-teardown.log");
const agentId = "agent-auto-archive-untrusted";
const registration = dispatch.registerAutoArchiveIfRequested({
autoArchive: true,
agentId,
createdWorktree,
});
events.completeTurn(agentId);
await registration.cancel();
expect(assertWorkspaceAutomationAllowed).toHaveBeenCalledWith(
createdWorktree.workspace.workspaceId,
);
expect(archived.has(createdWorktree.workspace.workspaceId)).toBe(true);
expect(existsSync(createdWorktree.worktree.worktreePath)).toBe(false);
expect(existsSync(marker)).toBe(false);
});
@@ -29,7 +29,8 @@ interface CreateAgentLifecycleDispatchDependencies {
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
getWorkspace?: ArchiveDependencies["getWorkspace"];
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
assertWorkspaceAutomationAllowed: ArchiveDependencies["assertWorkspaceAutomationAllowed"];
isCheckoutUntrusted: ArchiveDependencies["isCheckoutUntrusted"];
agentManager: AgentManager;
agentStorage: AgentStorage;
github: ForgeService;
@@ -201,6 +202,7 @@ export class CreateAgentLifecycleDispatch {
agentStorage: this.dependencies.agentStorage,
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
getWorkspace: this.dependencies.getWorkspace,
assertWorkspaceAutomationAllowed: this.dependencies.assertWorkspaceAutomationAllowed,
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,

Some files were not shown because too many files have changed in this diff Show More