mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-04 07:02:04 +00:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa93ed06c1 | ||
|
|
f2897d6687 | ||
|
|
d5be0e5827 |
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.111.0"
|
||||
".": "0.112.0"
|
||||
}
|
||||
|
||||
12
CHANGELOG.md
12
CHANGELOG.md
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## [0.112.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.111.0...v0.112.0) (2026-11-24)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* rewind the same provider session on an edited message ([#1704](https://github.com/agentclientprotocol/claude-agent-acp/issues/1704)) ([f2897d6](https://github.com/agentclientprotocol/claude-agent-acp/commit/f2897d6687f594220c07836c3e3528de552e30ef))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* stop holding an MCP request that Claude Code gave up ([#1711](https://github.com/agentclientprotocol/claude-agent-acp/issues/1711)) ([d5be0e5](https://github.com/agentclientprotocol/claude-agent-acp/commit/d5be0e5827fb111e5e95020d76920fe8a59e671b))
|
||||
|
||||
## [0.111.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.110.1...v0.111.0) (2026-11-24)
|
||||
|
||||
|
||||
|
||||
@@ -87,7 +87,14 @@ local command, keeps its key until `session/close` or the end of the connection.
|
||||
The adapter announces a session cursor (`cursor_update`) before each user message that follows
|
||||
another entry of the conversation, live and in a replay. `session/fork` with its `cursorId` copies
|
||||
the history before that message, and fails with `-32602` for any other `cursorId`. A v1 client gets
|
||||
no cursors yet.
|
||||
cursors only when it declares `clientCapabilities.session.cursors`. A v1 replay (`session/load`)
|
||||
anchors each cursor `before` its replayed user message. A live v1 prompt is not reported to the
|
||||
client that sent it, so its cursor is anchored `after` the last agent message, thought, tool call or
|
||||
compaction before it, with the same `cursorId` that a later replay issues. A session that was
|
||||
resumed without a replay has no such entity, so its live prompts get no cursor until it replays.
|
||||
When a v1 turn reports no entity (it was cancelled or failed before any output, or it was a slash
|
||||
command), the next prompt's cursor has the same `after <entity>` anchor as the previous prompt's
|
||||
cursor, with a different `cursorId`: the client uses the latest.
|
||||
|
||||
v2 is served by the v2 agent in `src/v2/`, which runs straight on Claude
|
||||
Code instead of translating to v1. A v2 client that declares JetBrains AIR
|
||||
|
||||
@@ -33,6 +33,7 @@ It describes only this adapter.
|
||||
- [Question custom answers](#question-custom-answers)
|
||||
- [Load replay end](#load-replay-end)
|
||||
- [Session fork point](#session-fork-point)
|
||||
- [Session rewind](#session-rewind)
|
||||
- [Presentation hints](#presentation-hints)
|
||||
- [Removed keys](#removed-keys)
|
||||
|
||||
@@ -179,6 +180,7 @@ It does not serve the [tool call contract](#tool-call-contract) yet.
|
||||
| `sessionRename` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that it supports `_session/rename`. | [Rename](#rename) |
|
||||
| `sessionListSubscribe` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that it supports `_session/list/subscribe`. | [List subscription](#list-subscription) |
|
||||
| `sessionWorktrees` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that rows carry `agentWorktree` for a worktree Claude Code made. | [List response](#list-response) |
|
||||
| `sessionRewind` | on request | Accepts `_session/rewind`, and announces its session cursors with the `rewind` capability. | [Session rewind](#session-rewind) |
|
||||
| `loadReplayEnd` | no | Sends one `session_info_update` after the whole history replay of a loaded session. | [Load replay end](#load-replay-end) |
|
||||
| `rawInputRendering` | no | Sends no display copy of readable input in `content`. The client renders `rawInput`. | [Tool call contract](#tool-call-contract) |
|
||||
|
||||
@@ -1890,6 +1892,48 @@ It adds this object to the `session/fork` request:
|
||||
- With or without this object, the forked session runs once the response arrives, so the client can prompt it without `session/load` or `session/resume`.
|
||||
A later load replays its history into it, and a later resume returns it. A load or resume with other settings (`cwd`, MCP servers, additional directories, or the session options in `_meta`) restarts it, as for any loaded session.
|
||||
|
||||
## Session rewind
|
||||
|
||||
AIR edits a user message by removing that message and everything after it from the provider's context, in the same session: same session id, no fork.
|
||||
`_session/rewind` asks the agent for that, at a session cursor:
|
||||
|
||||
```json
|
||||
{ "sessionId": "0f7c…", "cursorId": "before:<uuid of the user message>" }
|
||||
```
|
||||
|
||||
The response is `{ "rewound": true }`, which means that the cut is live and persisted, or `{ "rewound": false, "reason": "<reason>" }` when the conversation was left as it was.
|
||||
The client keeps its own history then.
|
||||
|
||||
- ACP v1 only. The agent advertises `sessionRewind` to a client that declares it, and then announces each `cursor_update` with the capabilities `{ "fork": {}, "rewind": {} }`, except a cursor whose resume point is before the newest compaction (`beforeCompaction`) and every cursor of a session whose context was cleared (`clearedContext`): those get `{ "fork": {} }`. Every other client gets `{ "fork": {} }` on all cursors, and the method is not found (`-32601`) for it. ACP v2 does not list `sessionRewind` and has no `_session/rewind`; it only honours a cut that v1 made.
|
||||
- `cursorId` is one that the session announced with `rewind`: the cursor before a user message of its history. The first user message has no cursor, since Claude Code has no entry before it to resume at, so a client offers no edit for it.
|
||||
- The adapter resumes the stored conversation of the session at the entry before the cursor's message (`resumeSessionAt`). The agent replaces its query with that resume and restores the model, mode, effort, agent and Fast mode as the user left them. Claude Code deletes nothing: the dropped entries stay in the transcript as an orphan branch, and the agent records the cut in `rewind.json` beside the session's `subagents/` directory before it replaces the query, and puts the file back as it was when the cut does not happen (`busy`, `backgroundWork` or `providerRefused` after the file was written). When putting it back fails, the request fails with an internal error instead of `rewound: false`: the rewind did not happen and its point could not be removed, so the next load of the session applies the cut. A failed cut then still resumes the conversation first, so the session can be prompted. A crash between the two leaves the point on disk: the next resume of the session applies the cut, and the client's next load replays the cut history.
|
||||
- A live prompt is not reported to the client that sent it, so its cursor is anchored `after` the last entity the client holds. After a rewind it is the entity the client held before the removed message; if the agent holds no such record, the next prompt gets no cursor. When a turn reports no entity (it was cancelled or failed before any output, or it was a slash command), the next prompt's cursor has the same `after <entity>` anchor as the previous prompt's cursor, with a different `cursorId`: the client uses the latest.
|
||||
- The cut also removes the cursors at and after it: the session no longer announces them, and a request that names one fails as an unknown cursor.
|
||||
- The cut holds until the next prompt stores a branch from it. Until then, the agent applies `rewind.json` wherever it reads or resumes the session: a `session/load` (v1) or `session/resume` with a replay (v2) replays the history before the cut, with its cursors only; a restart of the query, a later load or resume, and a v2 resume continue at the cut; `session/fork` copies the history before it, also without a `cursorId`, and rejects a `cursorId` or `jetbrains.air.fork` message from the removed part with `-32602`. The first resume after that prompt removes the file. `session/options` neither reads nor writes it. When the cut cannot be prepared (the stored history or `rewind.json` cannot be read, or `rewind.json` is not a valid record), the load, resume, replay or fork fails with an internal error instead of using the whole conversation, and the client can retry; the point stays on disk.
|
||||
- A rewind keeps the task list and the published session failures of the session. Its token totals start again, as they do after any restart of the query.
|
||||
- No file change is reverted. The files stay as the removed turns left them.
|
||||
- A prompt sent while the rewind runs waits for it, and runs on the rewound conversation.
|
||||
|
||||
| `reason` | When |
|
||||
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `busy` | Claude is working, a prompt is queued, Claude Code runs a cycle on its own, or a `/remote-control` command is in flight. AIR stops the turn before it sends the request. |
|
||||
| `backgroundWork` | A background task or subagent runs. Closing the query would end it. |
|
||||
| `beforeCompaction` | The message is before the newest compaction of the conversation: Claude Code resumes from that compaction on and finds no entry before it. |
|
||||
| `clearedContext` | The session's context was cleared when a plan was accepted: the conversation went on in another Claude Code session. |
|
||||
| `providerRefused` | Claude Code refused the cut, or the query could not restart with it. The agent resumed the conversation as it was, once, and the session can be prompted. |
|
||||
| `persistFailed` | `rewind.json` could not be written. The conversation and the rewind point are unchanged: the query was not replaced. The transcript can gain the `last-prompt` line that any resume writes. |
|
||||
|
||||
When the removed message is the last user message, Claude Code also checks the removed range and refuses a cut that would remove what the client never saw, such as a message the session absorbed mid-turn.
|
||||
The refusal is deterministic, so the agent never retries it.
|
||||
If the recovery resume fails too, the request fails with an internal error, the session ends, and the client loads it again. When it fails because the account needs a sign-in, the request fails with `authRequired` and the session stays: the next prompt after the sign-in resumes it.
|
||||
|
||||
The request fails with `-32602` for:
|
||||
|
||||
- a `cursorId` that the session's history does not hold: an unknown id, an id that is no cursor, the first message, a message before the newest compaction when the history before it cannot be read (the fallback in `src/resumed-session.ts`), or one that an earlier rewind removed;
|
||||
- a session id that names a subagent's child session.
|
||||
|
||||
A `sessionId` that is not held by the agent fails with `-32002`.
|
||||
|
||||
## Presentation hints
|
||||
|
||||
Each session mode and each value of the mode config option carries `_meta.jetbrains.air.kind`:
|
||||
|
||||
12
package-lock.json
generated
12
package-lock.json
generated
@@ -1,15 +1,15 @@
|
||||
{
|
||||
"name": "@agentclientprotocol/claude-agent-acp",
|
||||
"version": "0.111.0",
|
||||
"version": "0.112.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@agentclientprotocol/claude-agent-acp",
|
||||
"version": "0.111.0",
|
||||
"version": "0.112.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.11.0",
|
||||
"@agentclientprotocol/sdk": "2.12.0",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.331",
|
||||
"diff": "9.0.0",
|
||||
"zod": "4.6.7"
|
||||
@@ -38,9 +38,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@agentclientprotocol/sdk": {
|
||||
"version": "2.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-2.11.0.tgz",
|
||||
"integrity": "sha512-B4MQTHjaP11lsc82XTm4rHcHl7CP3jfjAappFIXTs3gYwTTHdq4HtxSFOCKZSWD46FtW2Q9uF7wveKC62wEIvg==",
|
||||
"version": "2.12.0",
|
||||
"resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-2.12.0.tgz",
|
||||
"integrity": "sha512-nSkamfY4Lw9/AVBU5G5V9p82ScXhANDMBybQwcPH/9+euUtZm04/VFUMaLj4gLFEXxQEy+QP1VQiKgSRbYVIPg==",
|
||||
"license": "Apache-2.0",
|
||||
"peerDependencies": {
|
||||
"@modelcontextprotocol/server": "^2.4.0",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"version": "0.111.0",
|
||||
"version": "0.112.0",
|
||||
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
|
||||
"main": "dist/lib.js",
|
||||
"types": "dist/lib.d.ts",
|
||||
@@ -68,7 +68,7 @@
|
||||
"node": ">=22"
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.11.0",
|
||||
"@agentclientprotocol/sdk": "2.12.0",
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.331",
|
||||
"diff": "9.0.0",
|
||||
"zod": "4.6.7"
|
||||
|
||||
@@ -48,6 +48,13 @@ export const AIR_SESSION_LIST_SUBSCRIBE_CAPABILITY = "sessionListSubscribe";
|
||||
* {@link AIR_SESSION_INDEX_CAPABILITY} is; the client does not declare it.
|
||||
*/
|
||||
export const AIR_SESSION_WORKTREES_CAPABILITY = "sessionWorktrees";
|
||||
/**
|
||||
* `_session/rewind`: removes a user message and everything after it from the
|
||||
* context of the same session (see `docs/air-extensions.md#session-rewind`).
|
||||
* The client declares it; the agent advertises it only to such a client, and
|
||||
* then announces its session cursors with the `rewind` capability.
|
||||
*/
|
||||
export const AIR_SESSION_REWIND_CAPABILITY = "sessionRewind";
|
||||
/**
|
||||
* The client wants to know when the history replay of a loaded session is
|
||||
* whole. After the last replayed update, the agent sends one
|
||||
|
||||
@@ -9,8 +9,14 @@ import {
|
||||
type SessionStoreEntry,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { createHash } from "node:crypto";
|
||||
import { loadFullSessionHistory, readHistoryAcrossCompactions } from "./resumed-session.js";
|
||||
import { loadFullSessionHistory } from "./resumed-session.js";
|
||||
import { forkPointOf } from "./session-cursors.js";
|
||||
import {
|
||||
cutAtRewindPoint,
|
||||
loadRewindableHistory,
|
||||
pendingRewindEnd,
|
||||
withoutRewoundBranch,
|
||||
} from "./session-rewind.js";
|
||||
import { assistantMessageText } from "./session-failure-extension.js";
|
||||
import { SessionTiming } from "./session-timing.js";
|
||||
|
||||
@@ -206,11 +212,9 @@ async function forkTranscript(
|
||||
): Promise<ForkSessionResponse> {
|
||||
const timing = new SessionTiming(dependencies.logger, "fork", params.sessionId);
|
||||
if (params.cursorId != null) {
|
||||
// The history as a replay reads it, which announces the cursors.
|
||||
const history = await readHistoryAcrossCompactions(
|
||||
params.sessionId,
|
||||
await getSessionMessages(params.sessionId),
|
||||
);
|
||||
// The history as a replay reads it, which announces the cursors: cut at a
|
||||
// pending rewind, so a cursor of a dropped turn is no cursor.
|
||||
const { visible: history } = await loadRewindableHistory(params.sessionId);
|
||||
const upToMessageId = forkPointOf(params.cursorId, history);
|
||||
timing.phase("cursor", ` resolution=${upToMessageId ? "found" : "missing"}`);
|
||||
if (upToMessageId === undefined) {
|
||||
@@ -227,7 +231,12 @@ async function forkTranscript(
|
||||
// SDK `dir` scopes source lookup, not the fork's working directory. Search
|
||||
// all projects: params.cwd can name a different workspace for the new session.
|
||||
if (!point) {
|
||||
const forked = await forkClaudeSession(params.sessionId);
|
||||
// A pending rewind ends the conversation at its point, not at the newest leaf.
|
||||
const rewoundEnd = await pendingRewindEnd(params.sessionId);
|
||||
const forked = await forkClaudeSession(
|
||||
params.sessionId,
|
||||
...(rewoundEnd ? [{ upToMessageId: rewoundEnd }] : []),
|
||||
);
|
||||
timing.phase("sdk-fork", " resolution=latest");
|
||||
return { sessionId: forked.sessionId };
|
||||
}
|
||||
@@ -236,7 +245,9 @@ async function forkTranscript(
|
||||
const liveUuid = candidateIds
|
||||
.map((candidateId) => dependencies.liveMessageIdToUuid?.get(candidateId))
|
||||
.find(Boolean);
|
||||
const history = liveUuid ? undefined : await getSessionMessages(params.sessionId);
|
||||
const history = liveUuid
|
||||
? undefined
|
||||
: await cutAtRewindPoint(params.sessionId, await getSessionMessages(params.sessionId));
|
||||
timing.phase("active-history", ` resolution=${liveUuid ? "live" : "pending"}`);
|
||||
const messageUuid =
|
||||
liveUuid ??
|
||||
@@ -253,7 +264,10 @@ async function forkTranscript(
|
||||
const fullHistoryUuid = messageUuid
|
||||
? undefined
|
||||
: resolveFromFullHistory(
|
||||
await loadFullSessionHistory(params.sessionId),
|
||||
await withoutRewoundBranch(
|
||||
params.sessionId,
|
||||
await loadFullSessionHistory(params.sessionId),
|
||||
),
|
||||
candidateIds,
|
||||
point,
|
||||
dependencies.messageIdForGrouping,
|
||||
|
||||
@@ -495,7 +495,12 @@ export class McpOverAcp {
|
||||
/**
|
||||
* Resolves when a request of the tool use `toolUseId` need wait no longer
|
||||
* for the announcement of its agent's child session: {@link release} ended
|
||||
* the wait, or {@link announcementWaitMs} passed. It never rejects.
|
||||
* the wait, {@link announcementWaitMs} passed, or `abandoned` aborted. It
|
||||
* never rejects.
|
||||
*
|
||||
* `abandoned` is the bridge's signal for the request. It aborts when Claude
|
||||
* Code closes the request's HTTP connection or the ACP connection closes.
|
||||
* The bridge then sends nothing, whatever the request names.
|
||||
*
|
||||
* Nothing that an announcement needs waits for the request. The hook that
|
||||
* recorded the tool use has answered. The session reads Claude Code's
|
||||
@@ -503,12 +508,14 @@ export class McpOverAcp {
|
||||
* to that stream before it ran the subagent's tool. A replay ends without
|
||||
* the request too.
|
||||
*/
|
||||
private held(toolUseId: string): Promise<void> {
|
||||
private held(toolUseId: string, abandoned: AbortSignal): Promise<void> {
|
||||
if (abandoned.aborted) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
const waiters = this.waiting.get(toolUseId) ?? new Set<() => void>();
|
||||
this.waiting.set(toolUseId, waiters);
|
||||
const end = () => {
|
||||
clearTimeout(timer);
|
||||
abandoned.removeEventListener("abort", end);
|
||||
waiters.delete(end);
|
||||
if (waiters.size === 0 && this.waiting.get(toolUseId) === waiters) {
|
||||
this.waiting.delete(toolUseId);
|
||||
@@ -518,6 +525,7 @@ export class McpOverAcp {
|
||||
const timer = setTimeout(end, this.announcementWaitMs);
|
||||
// The request's HTTP connection keeps the process alive, not this timer.
|
||||
timer.unref();
|
||||
abandoned.addEventListener("abort", end, { once: true });
|
||||
waiters.add(end);
|
||||
});
|
||||
}
|
||||
@@ -547,6 +555,7 @@ export class McpOverAcp {
|
||||
private attribution({
|
||||
serverId,
|
||||
params,
|
||||
signal,
|
||||
}: McpHttpRequestInfo):
|
||||
McpHttpRequestAttribution | undefined | Promise<McpHttpRequestAttribution | undefined> {
|
||||
const meta = params?._meta;
|
||||
@@ -557,7 +566,7 @@ export class McpOverAcp {
|
||||
if (typeof toolUseId !== "string") return undefined;
|
||||
const now = this.named(toolUseId, serverId);
|
||||
if (now !== "unannounced") return now;
|
||||
return this.held(toolUseId).then(() => {
|
||||
return this.held(toolUseId, signal).then(() => {
|
||||
const then = this.named(toolUseId, serverId);
|
||||
return then === "unannounced" ? undefined : then;
|
||||
});
|
||||
|
||||
@@ -21,16 +21,152 @@ import { isReplayHiddenMetaMessage, stripLocalCommandMetadata } from "./message-
|
||||
/** What the cursor ids start with. The rest is the uuid of the user message. */
|
||||
const BEFORE_MESSAGE = "before:";
|
||||
|
||||
/** The entity that a cursor is anchored to. */
|
||||
export type CursorEntity =
|
||||
| { type: "user_message" | "agent_message" | "agent_thought"; messageId: string }
|
||||
| { type: "tool_call"; toolCallId: string }
|
||||
| { type: "compaction"; compactionId: string };
|
||||
|
||||
/** The side of its {@link CursorEntity} that a cursor lies on. */
|
||||
export type CursorAnchor = CursorEntity & { position: "before" | "after" };
|
||||
|
||||
/** The `cursor_update` of the cursor before the user message `messageId`. */
|
||||
export function forkCursorUpdate(messageId: string) {
|
||||
return {
|
||||
...forkCursorBase(messageId),
|
||||
anchor: { type: "user_message" as const, messageId, position: "before" as const },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The cursor before the user message `messageId` for a client that holds no
|
||||
* such user message: `anchor` places it (see {@link LastReportedEntity}), and the
|
||||
* `cursorId` stays that of the message.
|
||||
*/
|
||||
export function anchoredForkCursorUpdate(messageId: string, anchor: CursorAnchor) {
|
||||
return { ...forkCursorBase(messageId), anchor };
|
||||
}
|
||||
|
||||
/**
|
||||
* `update` with the `rewind` capability added: the cursor is also a position
|
||||
* that `_session/rewind` accepts. For a client that declared `sessionRewind`.
|
||||
*/
|
||||
export function withRewindCapability<U extends { capabilities: { fork: object } }>(
|
||||
update: U,
|
||||
): U & { capabilities: { fork: object; rewind: object } } {
|
||||
return { ...update, capabilities: { ...update.capabilities, rewind: {} } };
|
||||
}
|
||||
|
||||
/** The uuid of the user message that `cursorId` lies before, or undefined for an id that is no cursor. */
|
||||
export function cursorMessageId(cursorId: string): string | undefined {
|
||||
return cursorId.startsWith(BEFORE_MESSAGE) ? cursorId.slice(BEFORE_MESSAGE.length) : undefined;
|
||||
}
|
||||
|
||||
function forkCursorBase(messageId: string) {
|
||||
return {
|
||||
sessionUpdate: "cursor_update" as const,
|
||||
cursorId: `${BEFORE_MESSAGE}${messageId}`,
|
||||
capabilities: { fork: {} },
|
||||
anchor: { type: "user_message" as const, messageId, position: "before" as const },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The last entity per session that a client can anchor a cursor to: an agent
|
||||
* message or thought with a `messageId`, a tool call, a compaction or a user
|
||||
* message with a `messageId`. v1 does not report a prompt that the client
|
||||
* sent, so its cursor lies `after` the entity before it. Each session update
|
||||
* that goes to the client passes through {@link sending}, a replay too.
|
||||
* Output of a subagent (a `parentToolUseId` in its `_meta`) is not on the
|
||||
* session's own timeline and is left out.
|
||||
*
|
||||
* It also records, for each cursor that the agent announces, the entity that
|
||||
* the client held right before that position ({@link recordCursor}). A rewind
|
||||
* to the cursor leaves the client with exactly that entity.
|
||||
*/
|
||||
export class LastReportedEntity {
|
||||
private readonly bySession = new Map<string, CursorEntity>();
|
||||
/** Per session, in announcement order: the entity before each announced cursor. */
|
||||
private readonly beforeCursor = new Map<string, Map<string, CursorEntity | undefined>>();
|
||||
|
||||
sending(notification: {
|
||||
sessionId: string;
|
||||
update: { sessionUpdate: string; _meta?: unknown } & Record<string, unknown>;
|
||||
}): void {
|
||||
const { sessionId, update } = notification;
|
||||
const meta = update._meta as { claudeCode?: { parentToolUseId?: unknown } } | null | undefined;
|
||||
if (meta?.claudeCode?.parentToolUseId) return;
|
||||
const messageId = typeof update.messageId === "string" ? update.messageId : undefined;
|
||||
switch (update.sessionUpdate) {
|
||||
case "user_message_chunk":
|
||||
if (messageId) this.bySession.set(sessionId, { type: "user_message", messageId });
|
||||
break;
|
||||
case "agent_message_chunk":
|
||||
if (messageId) this.bySession.set(sessionId, { type: "agent_message", messageId });
|
||||
break;
|
||||
case "agent_thought_chunk":
|
||||
if (messageId) this.bySession.set(sessionId, { type: "agent_thought", messageId });
|
||||
break;
|
||||
case "tool_call":
|
||||
if (typeof update.toolCallId === "string") {
|
||||
this.bySession.set(sessionId, { type: "tool_call", toolCallId: update.toolCallId });
|
||||
}
|
||||
break;
|
||||
case "compaction_update":
|
||||
if (typeof update.compactionId === "string") {
|
||||
this.bySession.set(sessionId, { type: "compaction", compactionId: update.compactionId });
|
||||
}
|
||||
break;
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
/** The position after the last entity of the session, if the client holds one. */
|
||||
after(sessionId: string): CursorAnchor | undefined {
|
||||
const entity = this.bySession.get(sessionId);
|
||||
return entity && { ...entity, position: "after" };
|
||||
}
|
||||
|
||||
/** The last entity of the session that the client holds, if any. */
|
||||
last(sessionId: string): CursorEntity | undefined {
|
||||
return this.bySession.get(sessionId);
|
||||
}
|
||||
|
||||
/** The agent announces `cursorId`; `before` is the entity the client holds right before it. */
|
||||
recordCursor(sessionId: string, cursorId: string, before: CursorEntity | undefined): void {
|
||||
let records = this.beforeCursor.get(sessionId);
|
||||
if (!records) this.beforeCursor.set(sessionId, (records = new Map()));
|
||||
records.set(cursorId, before);
|
||||
}
|
||||
|
||||
/**
|
||||
* The session is rewound to `cursorId`: the client drops the entities from
|
||||
* there on, so the entity recorded for the cursor is its last one (none for
|
||||
* a cursor that has no record: the next prompt then gets no cursor). The
|
||||
* records of the cursors at and after the cut go too.
|
||||
*/
|
||||
rewind(sessionId: string, cursorId: string): void {
|
||||
const records = this.beforeCursor.get(sessionId);
|
||||
const before = records?.get(cursorId);
|
||||
if (before) this.bySession.set(sessionId, before);
|
||||
else this.bySession.delete(sessionId);
|
||||
if (!records?.has(cursorId)) return;
|
||||
let cut = false;
|
||||
for (const id of [...records.keys()]) {
|
||||
cut ||= id === cursorId;
|
||||
if (cut) records.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
/** The client no longer holds the session's entities: it closed, or a replay rebuilds them. */
|
||||
forget(sessionId: string): void {
|
||||
for (const map of [this.bySession, this.beforeCursor]) {
|
||||
for (const id of map.keys()) {
|
||||
if (id === sessionId || id.startsWith(`${sessionId}:`)) map.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a prompt with this content gets a cursor when it is inserted live.
|
||||
* A slash command does not: Claude Code stores a command as command metadata
|
||||
@@ -52,8 +188,13 @@ export function promptGetsCursor(prompt: ReadonlyArray<{ type: string; text?: un
|
||||
*/
|
||||
export function hasForkCursor(messages: readonly SessionMessage[], index: number): boolean {
|
||||
const message = messages[index];
|
||||
if (!message || message.type !== "user" || !message.uuid) return false;
|
||||
if (!messages[index - 1]?.uuid) return false;
|
||||
if (!message || !messages[index - 1]?.uuid) return false;
|
||||
return isShownUserMessage(message);
|
||||
}
|
||||
|
||||
/** Whether a replay shows `message` as a user message of the session's own conversation. */
|
||||
function isShownUserMessage(message: SessionMessage): boolean {
|
||||
if (message.type !== "user" || !message.uuid) return false;
|
||||
if (message.parent_tool_use_id !== null) return false;
|
||||
if (isReplayHiddenMetaMessage(message) || isCompactSummaryMessage(message)) return false;
|
||||
// `null`: the message was command metadata alone, which a replay does not show.
|
||||
|
||||
595
src/session-rewind.ts
Normal file
595
src/session-rewind.ts
Normal file
@@ -0,0 +1,595 @@
|
||||
/**
|
||||
* `_session/rewind` (AIR -> agent): removes a user message and everything after
|
||||
* it from the context of the same Claude session, the one the client holds. A
|
||||
* fork would answer the same intent with a second session, so the edited
|
||||
* message would no longer run in the conversation that the user is looking at.
|
||||
*
|
||||
* The position is a session cursor (see `session-cursors.ts`): the one before
|
||||
* the user message to drop. The adapter resumes the stored conversation of the
|
||||
* session at the entry before that message (`resumeSessionAt`). Claude Code
|
||||
* deletes nothing: the dropped entries stay in the transcript as an orphan
|
||||
* branch, and `rewind.json` records the cut until the next prompt writes a
|
||||
* branch that descends from it.
|
||||
*
|
||||
* Every read of the stored history of a session cuts it at the point
|
||||
* (`cutAtRewindPoint`: replays, forks, v2's prompt keys), and every resume of
|
||||
* it stops there (`prepareRewoundResume`). The point is removed by the first
|
||||
* resume after the CLI stored a prompt on the rewound branch; until then the
|
||||
* file stays and cuts nothing, since the stored history no longer holds the
|
||||
* dropped prompt. v1 and v2 share this: both resume through
|
||||
* `prepareRewoundResume` and read through `cutAtRewindPoint`.
|
||||
*/
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import {
|
||||
getSessionMessages,
|
||||
type SessionMessage,
|
||||
type SessionStoreEntry,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { isCompactSummaryMessage } from "./context-compaction.js";
|
||||
import { isReplayHiddenMetaMessage } from "./message-filters.js";
|
||||
import {
|
||||
findTranscript,
|
||||
loadFullSessionHistory,
|
||||
readHistoryAcrossCompactions,
|
||||
} from "./resumed-session.js";
|
||||
import { cursorMessageId, forkPointOf } from "./session-cursors.js";
|
||||
|
||||
export const SESSION_REWIND_METHOD = "_session/rewind";
|
||||
|
||||
export type SessionRewindRequest = {
|
||||
sessionId: string;
|
||||
/** A cursor that the session announced, before the user message to drop. */
|
||||
cursorId: string;
|
||||
};
|
||||
|
||||
/** Why the conversation was left as it was. */
|
||||
export type SessionRewindRefusal =
|
||||
/** Claude is working, or a prompt is queued. */
|
||||
| "busy"
|
||||
/** A background task or subagent is running. */
|
||||
| "backgroundWork"
|
||||
/** The message is before the newest compaction of the conversation. */
|
||||
| "beforeCompaction"
|
||||
/** The session's context was cleared into another Claude session. */
|
||||
| "clearedContext"
|
||||
/** Claude Code refused the cut. The session goes on as it was. */
|
||||
| "providerRefused"
|
||||
/** The rewind point could not be written. Nothing changed. */
|
||||
| "persistFailed";
|
||||
|
||||
export type SessionRewindResponse = {
|
||||
rewound: boolean;
|
||||
reason?: SessionRewindRefusal;
|
||||
};
|
||||
|
||||
export function parseSessionRewindRequest(params: unknown): SessionRewindRequest {
|
||||
if (!params || typeof params !== "object") {
|
||||
throw RequestError.invalidParams(undefined, "rewind params must be an object");
|
||||
}
|
||||
const { sessionId, cursorId } = params as Record<string, unknown>;
|
||||
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
||||
throw RequestError.invalidParams(undefined, "rewind params require a non-empty sessionId");
|
||||
}
|
||||
if (typeof cursorId !== "string" || cursorId.length === 0) {
|
||||
throw RequestError.invalidParams(undefined, "rewind params require a non-empty cursorId");
|
||||
}
|
||||
return { sessionId, cursorId };
|
||||
}
|
||||
|
||||
type Logger = { log: (...args: unknown[]) => void; error: (...args: unknown[]) => void };
|
||||
|
||||
/** The stored history of a session, as a replay shows it. */
|
||||
export type RewindableHistory = {
|
||||
/** Every message of the conversation the session continues, from its first
|
||||
* prompt on, across compactions. A rewind cursor is one of this list. */
|
||||
visible: readonly SessionMessage[];
|
||||
/** The part of `visible` that the newest compaction left: where Claude Code
|
||||
* can resume. */
|
||||
current: readonly SessionMessage[];
|
||||
};
|
||||
|
||||
/** What the rewind needs from the agent that holds the session. */
|
||||
export type SessionRewindHost = {
|
||||
logger: Logger;
|
||||
/** The context of the session was cleared into another Claude session. */
|
||||
clearedContext: boolean;
|
||||
/** Whether Claude works, or a prompt is queued: `startTurn`'s check. */
|
||||
claudeIsWorking(): boolean;
|
||||
/** Whether a background task or subagent runs. Closing the query ends it. */
|
||||
hasBackgroundWork(): boolean;
|
||||
loadHistory(): Promise<RewindableHistory>;
|
||||
/**
|
||||
* Closes the query and recreates the same session by resuming its
|
||||
* conversation, stopped at `resumeAt.resumeSessionAt` when it is set. Restores
|
||||
* the user's model, mode, agent, effort and Fast mode, and starts the reader.
|
||||
*/
|
||||
replaceQuery(resumeAt?: { resumeSessionAt: string; resumeDropsTurn?: string }): Promise<void>;
|
||||
/**
|
||||
* The session is rewound to `cursorId`. The next prompt's cursor anchors to
|
||||
* the entity that the client held before that cursor.
|
||||
*/
|
||||
rewound(cursorId: string): void;
|
||||
/** Deals with a session whose query is closed and could not be resumed,
|
||||
* and returns the error the rewind fails with. */
|
||||
abandon(error: unknown): Promise<unknown>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Drops the user message of `request.cursorId` and everything after it.
|
||||
*
|
||||
* `{ rewound: true }` means that the cut is live and recorded in `rewind.json`;
|
||||
* `{ rewound: false, reason }` means that the conversation and the rewind point
|
||||
* are unchanged. The transcript can still gain the `last-prompt` line that any
|
||||
* resume writes: `prepareRewoundResume` runs before the refusals that follow
|
||||
* it, and with a stale point that is not pending it also deletes `rewind.json`,
|
||||
* as any resume does. A cursor that the session's history does not hold is a
|
||||
* bad request (-32602): the rewind never acts at another position.
|
||||
*
|
||||
* The point is written before the query is replaced, and restored to what it
|
||||
* was when the cut does not happen. A crash between the write and the cut
|
||||
* leaves a point that the next resume applies. When the restore fails too, the
|
||||
* request fails with an internal error instead of `rewound: false`, since the
|
||||
* next resume applies a cut that was reported as not made.
|
||||
*/
|
||||
export async function rewindSession(
|
||||
request: SessionRewindRequest,
|
||||
host: SessionRewindHost,
|
||||
): Promise<SessionRewindResponse> {
|
||||
const { sessionId, cursorId } = request;
|
||||
const refuse = (reason: SessionRewindRefusal): SessionRewindResponse => {
|
||||
host.logger.log(`Rewind of session ${sessionId} refused: ${reason}`);
|
||||
return { rewound: false, reason };
|
||||
};
|
||||
// AIR stops the turn before it rewinds. Work still running here would be
|
||||
// killed with the query.
|
||||
const busy = (): SessionRewindResponse | undefined =>
|
||||
host.claudeIsWorking()
|
||||
? refuse("busy")
|
||||
: host.hasBackgroundWork()
|
||||
? refuse("backgroundWork")
|
||||
: undefined;
|
||||
const refusal = busy();
|
||||
if (refusal) return refusal;
|
||||
// The transcript of the session holds the conversation from before the
|
||||
// clear, which the cursor would be resolved against.
|
||||
if (host.clearedContext) return refuse("clearedContext");
|
||||
|
||||
const history = await host.loadHistory();
|
||||
const resumeSessionAt = forkPointOf(cursorId, history.visible);
|
||||
const droppedPromptUuid = cursorMessageId(cursorId);
|
||||
if (!resumeSessionAt || !droppedPromptUuid) {
|
||||
throw RequestError.invalidParams(
|
||||
{ cursorId },
|
||||
`Cursor ${cursorId} is not a rewind position of session ${sessionId}`,
|
||||
);
|
||||
}
|
||||
// Claude Code resumes a compacted conversation from its newest compaction on
|
||||
// and finds no entry before it ("No message found with message.uuid of ...").
|
||||
if (!history.current.some((message) => message.uuid === resumeSessionAt)) {
|
||||
return refuse("beforeCompaction");
|
||||
}
|
||||
// Before the query closes: marks the branch a second rewind resumes on.
|
||||
const earlierCut = await prepareRewoundResume(sessionId, host.logger);
|
||||
// Read after the preparation, which removes a point that is no longer pending.
|
||||
const previousPoint = await readRewindPoint(sessionId, host.logger);
|
||||
const dropped = history.visible.findIndex((message) => message.uuid === droppedPromptUuid);
|
||||
// `resumeDropsTurn` makes Claude Code refuse a cut that discards anything
|
||||
// the named turn does not account for, so it can guard only the last turn:
|
||||
// the turns after an earlier one are always in the discarded range.
|
||||
const dropsOneTurn = !history.visible.slice(dropped + 1).some(startsTurn);
|
||||
|
||||
try {
|
||||
await writeRewindPoint(sessionId, { resumeSessionAt, droppedPromptUuid });
|
||||
} catch (error) {
|
||||
host.logger.error(`Failed to record the rewind point of session ${sessionId}:`, error);
|
||||
return refuse("persistFailed");
|
||||
}
|
||||
// Puts `rewind.json` back, for a cut that does not happen. A failure leaves
|
||||
// the new point in place, which the next resume of the session applies.
|
||||
const restorePoint = async () => {
|
||||
try {
|
||||
if (previousPoint) await writeRewindPoint(sessionId, previousPoint);
|
||||
else await clearRewindPoint(sessionId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
host.logger.error(
|
||||
`Failed to restore the rewind point of session ${sessionId}; the next resume applies the cut:`,
|
||||
error,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const pointNotRemoved = () =>
|
||||
RequestError.internalError(
|
||||
undefined,
|
||||
`The rewind of session ${sessionId} did not happen, but its rewind point could not be removed. The next load of the session applies the cut.`,
|
||||
);
|
||||
// Claude Code can start a cycle on its own while the transcript is read,
|
||||
// prepared or the point is written. Nothing is awaited between this check
|
||||
// and `replaceQuery`, whose first statement closes the query synchronously.
|
||||
const lateRefusal = busy();
|
||||
if (lateRefusal) {
|
||||
if (!(await restorePoint())) throw pointNotRemoved();
|
||||
return lateRefusal;
|
||||
}
|
||||
|
||||
try {
|
||||
await host.replaceQuery({
|
||||
resumeSessionAt,
|
||||
...(dropsOneTurn ? { resumeDropsTurn: droppedPromptUuid } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
// Claude Code refuses a cut deterministically, so retrying fails again.
|
||||
// Recover once into the conversation as it was: the query of the session is
|
||||
// already closed, and a session the client cannot prompt is worse than one
|
||||
// that was not rewound.
|
||||
host.logger.log(
|
||||
`Rewind of session ${sessionId} ${isRewindRefusal(error) ? "was refused by Claude Code" : `failed: ${error}`}; resuming the conversation as it was`,
|
||||
);
|
||||
// Before the recovery resume, which reads `rewind.json` and would stop at
|
||||
// the new point. If the file cannot be restored, only the earlier cut is used.
|
||||
const restored = await restorePoint();
|
||||
try {
|
||||
const recoveredCut = restored
|
||||
? ((await prepareRewoundResume(sessionId, host.logger)) ?? earlierCut)
|
||||
: earlierCut;
|
||||
await host.replaceQuery(recoveredCut ? { resumeSessionAt: recoveredCut } : undefined);
|
||||
} catch (recoveryError) {
|
||||
throw await host.abandon(recoveryError);
|
||||
}
|
||||
// After the recovery, so the session can be prompted.
|
||||
if (!restored) throw pointNotRemoved();
|
||||
return { rewound: false, reason: "providerRefused" };
|
||||
}
|
||||
host.rewound(cursorId);
|
||||
return { rewound: true };
|
||||
}
|
||||
|
||||
/** Whether Claude Code refused the cut (see `resumeDropsTurn` of the SDK options). */
|
||||
export function isRewindRefusal(error: unknown): boolean {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return message.includes("Resume rejected by --resume-drops-turn:");
|
||||
}
|
||||
|
||||
/** Whether a message opens a turn: a prompt of the user, not a tool result or injected context. */
|
||||
function startsTurn(message: SessionMessage): boolean {
|
||||
if (
|
||||
message.type !== "user" ||
|
||||
message.parent_tool_use_id !== null ||
|
||||
isReplayHiddenMetaMessage(message) ||
|
||||
isCompactSummaryMessage(message)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const content = (message.message as { content?: unknown } | undefined)?.content;
|
||||
return !(
|
||||
Array.isArray(content) &&
|
||||
content.length > 0 &&
|
||||
content.every((block) => (block as { type?: unknown } | null)?.type === "tool_result")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The history of `sessionId` that a cursor of it is resolved against: the
|
||||
* conversation the session continues, cut at its rewind point.
|
||||
*/
|
||||
export async function loadRewindableHistory(
|
||||
sessionId: string,
|
||||
logger?: Logger,
|
||||
): Promise<RewindableHistory> {
|
||||
const current = await cutAtRewindPoint(sessionId, await getSessionMessages(sessionId), logger);
|
||||
return { current, visible: await readHistoryAcrossCompactions(sessionId, current, logger) };
|
||||
}
|
||||
|
||||
/**
|
||||
* `stored`, the `getSessionMessages` chain of `sessionId`, without the branch
|
||||
* that a pending rewind dropped. Cut before reading across compactions: the
|
||||
* newest leaf is the last retained message.
|
||||
*/
|
||||
export async function cutAtRewindPoint<M extends { uuid?: string | null }>(
|
||||
sessionId: string,
|
||||
stored: readonly M[],
|
||||
logger?: Logger,
|
||||
): Promise<M[]> {
|
||||
return activeSessionMessages(stored, await readRewindPoint(sessionId, logger));
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry that a fork of the whole of `sessionId` ends at while a rewind is
|
||||
* pending, or undefined when there is none: the newest leaf then still lies in
|
||||
* the dropped branch.
|
||||
*/
|
||||
export async function pendingRewindEnd(
|
||||
sessionId: string,
|
||||
logger?: Logger,
|
||||
): Promise<string | undefined> {
|
||||
const point = await readRewindPoint(sessionId, logger);
|
||||
if (!point) return undefined;
|
||||
const stored = await getSessionMessages(sessionId);
|
||||
return stored.some((message) => message.uuid === point.droppedPromptUuid)
|
||||
? point.resumeSessionAt
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `entries`, the records of the whole transcript of `sessionId` with its
|
||||
* inactive branches, without the dropped prompt of a rewind and the records
|
||||
* that descend from it. A record comes after its parent in the transcript.
|
||||
*/
|
||||
export async function withoutRewoundBranch(
|
||||
sessionId: string,
|
||||
entries: SessionStoreEntry[],
|
||||
logger?: Logger,
|
||||
): Promise<SessionStoreEntry[]> {
|
||||
const point = await readRewindPoint(sessionId, logger);
|
||||
if (!point) return entries;
|
||||
const dropped = new Set<string>([point.droppedPromptUuid]);
|
||||
return entries.filter((entry) => {
|
||||
if (typeof entry.uuid !== "string") return true;
|
||||
const parent = entry.parentUuid || entry.logicalParentUuid;
|
||||
const inDropped =
|
||||
entry.uuid === point.droppedPromptUuid || (typeof parent === "string" && dropped.has(parent));
|
||||
if (inDropped) dropped.add(entry.uuid);
|
||||
return !inDropped;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The messages of the conversation that a session continues, given its stored
|
||||
* `history` and its `rewindPoint`. A rewind leaves the dropped branch in the
|
||||
* transcript, and until the next prompt writes a branch from the point,
|
||||
* `history` still ends in the dropped branch: it is cut before the dropped
|
||||
* prompt. Once a branch descends from the point, `history` no longer holds the
|
||||
* dropped prompt and is returned as it is.
|
||||
*/
|
||||
export function activeSessionMessages<M extends { uuid?: string | null }>(
|
||||
history: readonly M[],
|
||||
rewindPoint: RewindPoint | undefined,
|
||||
): M[] {
|
||||
const at = rewindPoint
|
||||
? history.findIndex((message) => message.uuid === rewindPoint.droppedPromptUuid)
|
||||
: -1;
|
||||
return at === -1 ? [...history] : history.slice(0, at);
|
||||
}
|
||||
|
||||
/** A rewind: the entry the session resumes at, and the prompt it dropped. */
|
||||
export type RewindPoint = {
|
||||
/** The last retained entry, for `resumeSessionAt`. */
|
||||
resumeSessionAt: string;
|
||||
/** The first entry of the dropped branch: the user prompt the rewind removed. */
|
||||
droppedPromptUuid: string;
|
||||
};
|
||||
|
||||
/** `<projectDir>/<sessionId>/rewind.json`, beside the session's `subagents/`. */
|
||||
async function rewindPointFile(sessionId: string): Promise<string | undefined> {
|
||||
const transcript = await findTranscript(sessionId);
|
||||
return transcript && path.join(path.dirname(transcript), sessionId, "rewind.json");
|
||||
}
|
||||
|
||||
/** Records the last rewind of a session. */
|
||||
export async function writeRewindPoint(sessionId: string, point: RewindPoint): Promise<void> {
|
||||
const target = await rewindPointFile(sessionId);
|
||||
if (!target) throw new Error(`Session ${sessionId} has no transcript`);
|
||||
await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
||||
const temporary = `${target}.tmp.${randomBytes(8).toString("hex")}`;
|
||||
try {
|
||||
await writeFile(temporary, JSON.stringify(point), { mode: 0o600, flag: "wx" });
|
||||
await rename(temporary, target);
|
||||
} catch (error) {
|
||||
await rm(temporary, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The last rewind of a session, or undefined for one that has none (no
|
||||
* `rewind.json`, ENOENT). A record that cannot be read (EACCES, EISDIR) or
|
||||
* parsed fails with an internal error: reading it as "no rewind" would show or
|
||||
* resume the dropped turns. The file stays, so the client can retry.
|
||||
*/
|
||||
export async function readRewindPoint(
|
||||
sessionId: string,
|
||||
logger?: Logger,
|
||||
): Promise<RewindPoint | undefined> {
|
||||
try {
|
||||
const file = await rewindPointFile(sessionId);
|
||||
if (!file) return undefined;
|
||||
let point: Partial<RewindPoint>;
|
||||
try {
|
||||
point = JSON.parse(await readFile(file, "utf8"));
|
||||
} catch (error) {
|
||||
if ((error as { code?: unknown }).code === "ENOENT") return undefined;
|
||||
throw error;
|
||||
}
|
||||
const { resumeSessionAt, droppedPromptUuid } = point ?? {};
|
||||
if (typeof resumeSessionAt !== "string" || typeof droppedPromptUuid !== "string") {
|
||||
throw new Error("rewind.json holds no resumeSessionAt and droppedPromptUuid");
|
||||
}
|
||||
return { resumeSessionAt, droppedPromptUuid };
|
||||
} catch (error) {
|
||||
logger?.error(`Failed to read the rewind point of session ${sessionId}:`, error);
|
||||
throw RequestError.internalError(
|
||||
undefined,
|
||||
`Session ${sessionId} was rewound, but its rewind point cannot be read (${error instanceof Error ? error.message : String(error)}). Try again.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes the record of the last rewind. */
|
||||
export async function clearRewindPoint(sessionId: string): Promise<void> {
|
||||
const file = await rewindPointFile(sessionId);
|
||||
if (file) await rm(file, { force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the transcript of `sessionId` for a resume, and returns the entry
|
||||
* that a pending rewind point makes the resume stop at, if any.
|
||||
*
|
||||
* Claude Code resumes the branch of the leaf that the last `last-prompt` line
|
||||
* of the transcript names, and looks up `resumeSessionAt` on that branch only.
|
||||
* A process that resumed at a rewind point keeps writing that line with the
|
||||
* leaf it loaded until it exits, and a query restart starts the next process
|
||||
* before the closed one has exited, so the line can name the branch that the
|
||||
* rewind dropped. A second rewind then fails with "No message found with
|
||||
* message.uuid of ...", and a plain resume brings the dropped turns back. So
|
||||
* the line is written for the leaf of the session's conversation: explicit at
|
||||
* a pending rewind point, whose dropped branch descends from it, and plain at
|
||||
* the newest entry otherwise. Once the point is no longer pending, the plain
|
||||
* line is all the next process needs, and `rewind.json` is removed.
|
||||
*/
|
||||
export async function prepareRewoundResume(
|
||||
sessionId: string,
|
||||
logger?: Logger,
|
||||
): Promise<string | undefined> {
|
||||
const point = await readRewindPoint(sessionId, logger);
|
||||
if (!point) return undefined;
|
||||
try {
|
||||
const history = await loadFullSessionHistory(sessionId);
|
||||
const byUuid = entriesByUuid(history);
|
||||
const newest = newestMainChainUuid(history);
|
||||
if (!newest) return undefined;
|
||||
const active = chainUuids(newest, byUuid);
|
||||
const pending = isPending(point, history, active);
|
||||
const leaf = pending ? point.resumeSessionAt : newest;
|
||||
await markResumedLeaf(sessionId, history, byUuid, leaf, pending);
|
||||
if (!pending) await clearRewindPoint(sessionId);
|
||||
return pending ? point.resumeSessionAt : undefined;
|
||||
} catch (error) {
|
||||
// A plain resume would bring the dropped turns back, so the resume fails
|
||||
// instead and the client can retry.
|
||||
logger?.error(`Failed to prepare the resume of rewound session ${sessionId}:`, error);
|
||||
throw RequestError.internalError(
|
||||
undefined,
|
||||
`Session ${sessionId} was rewound, but the cut could not be prepared (${error instanceof Error ? error.message : String(error)}). Try again.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the rewind is still to be applied: the dropped prompt is on the newest
|
||||
* conversation chain, or that chain does not pass through the point's resume
|
||||
* entry and holds nothing written after it (a branch from before the cut).
|
||||
* A chain through the resume entry without the dropped prompt is the edited
|
||||
* conversation, which a later entry of any other kind must not undo.
|
||||
*/
|
||||
function isPending(
|
||||
point: RewindPoint,
|
||||
history: SessionStoreEntry[],
|
||||
active: ReadonlySet<string>,
|
||||
): boolean {
|
||||
const pointIndex = history.findIndex((entry) => entry.uuid === point.resumeSessionAt);
|
||||
if (pointIndex < 0) return false;
|
||||
if (active.has(point.droppedPromptUuid)) return true;
|
||||
if (active.has(point.resumeSessionAt)) return false;
|
||||
return !history.some((entry, index) => index > pointIndex && active.has(entry.uuid as string));
|
||||
}
|
||||
|
||||
async function markResumedLeaf(
|
||||
sessionId: string,
|
||||
history: SessionStoreEntry[],
|
||||
byUuid: Map<string, SessionStoreEntry>,
|
||||
leaf: string,
|
||||
explicit: boolean,
|
||||
): Promise<void> {
|
||||
const transcript = await findTranscript(sessionId);
|
||||
if (!transcript) return;
|
||||
const lines = (await readFile(transcript, "utf8")).split("\n");
|
||||
for (let index = lines.length - 1; index >= 0; index--) {
|
||||
const line = lines[index]!;
|
||||
if (!line.includes('"last-prompt"')) continue;
|
||||
try {
|
||||
const record = JSON.parse(line);
|
||||
if (record.type !== "last-prompt") continue;
|
||||
if (record.leafUuid === leaf && (record.explicit === true) === explicit) return;
|
||||
break;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const branch = chainUuids(leaf, byUuid);
|
||||
const lastPrompt = history
|
||||
.filter((entry) => branch.has(entry.uuid as string) && entry.type === "user")
|
||||
.map(promptText)
|
||||
.findLast((text) => text !== undefined);
|
||||
const record = {
|
||||
type: "last-prompt",
|
||||
...(lastPrompt !== undefined ? { lastPrompt } : {}),
|
||||
leafUuid: leaf,
|
||||
...(explicit ? { explicit: true } : {}),
|
||||
sessionId,
|
||||
};
|
||||
const separator = lines.at(-1) === "" ? "" : "\n";
|
||||
await appendFile(transcript, `${separator}${JSON.stringify(record)}\n`);
|
||||
}
|
||||
|
||||
/** The text of a user entry that carries a prompt, undefined for any other. */
|
||||
function promptText(entry: SessionStoreEntry): string | undefined {
|
||||
if (entry.isMeta === true || isCompactSummaryMessage(entry)) return undefined;
|
||||
const content = (entry.message as { content?: unknown } | undefined)?.content;
|
||||
if (typeof content === "string") return content;
|
||||
if (!Array.isArray(content)) return undefined;
|
||||
if (content.some((block) => (block as { type?: unknown } | null)?.type === "tool_result")) {
|
||||
return undefined;
|
||||
}
|
||||
const text = content
|
||||
.map((block) => block as { type?: unknown; text?: unknown } | null)
|
||||
.flatMap((block) =>
|
||||
block?.type === "text" && typeof block.text === "string" ? [block.text] : [],
|
||||
)
|
||||
.join("");
|
||||
return text.length > 0 ? text : undefined;
|
||||
}
|
||||
|
||||
/** An entry of the main conversation: not a subagent's, and not the transcript of a tool. */
|
||||
function isMainChainEntry(entry: SessionStoreEntry): boolean {
|
||||
return (
|
||||
entry.isSidechain !== true && entry.parent_tool_use_id == null && entry.parent_agent_id == null
|
||||
);
|
||||
}
|
||||
|
||||
/** The entry types that the SDK reads as the conversation's chain; other records
|
||||
* (titles, tags, summaries) are metadata even when they carry a `uuid`. */
|
||||
const CHAIN_ENTRY_TYPES: ReadonlySet<unknown> = new Set([
|
||||
"user",
|
||||
"assistant",
|
||||
"system",
|
||||
"attachment",
|
||||
]);
|
||||
|
||||
/** The uuid of the newest entry of the main conversation: the leaf that
|
||||
* `getSessionMessages` reads. Like it, skips `progress` entries. */
|
||||
function newestMainChainUuid(entries: SessionStoreEntry[]): string | undefined {
|
||||
return entries.findLast(
|
||||
(entry) =>
|
||||
typeof entry.uuid === "string" &&
|
||||
CHAIN_ENTRY_TYPES.has(entry.type) &&
|
||||
isMainChainEntry(entry),
|
||||
)?.uuid;
|
||||
}
|
||||
|
||||
/** The uuids of `leaf` and of every entry it descends from. A compaction
|
||||
* boundary has no `parentUuid`; its `logicalParentUuid` carries the chain on. */
|
||||
function chainUuids(
|
||||
leaf: string | undefined,
|
||||
byUuid: ReadonlyMap<string, SessionStoreEntry>,
|
||||
): Set<string> {
|
||||
const chain = new Set<string>();
|
||||
let cursor = leaf;
|
||||
while (cursor && !chain.has(cursor)) {
|
||||
const entry = byUuid.get(cursor);
|
||||
if (!entry) break;
|
||||
chain.add(cursor);
|
||||
const parent = entry.parentUuid || entry.logicalParentUuid;
|
||||
cursor = typeof parent === "string" ? parent : undefined;
|
||||
}
|
||||
return chain;
|
||||
}
|
||||
|
||||
function entriesByUuid(entries: SessionStoreEntry[]): Map<string, SessionStoreEntry> {
|
||||
return new Map(
|
||||
entries.flatMap((entry) => (typeof entry.uuid === "string" ? [[entry.uuid, entry]] : [])),
|
||||
);
|
||||
}
|
||||
@@ -207,6 +207,8 @@ const CLAUDE_CODE_MCP_META = {
|
||||
* headers that mirror its version, method and tool name. A `tools/call` has
|
||||
* the id of its tool use (`toolUseId`) and a progress token in `_meta`.
|
||||
* `headers` replace the config's own, which carry the server's bearer token.
|
||||
* `abandoned` closes the request's connection, as Claude Code does when it
|
||||
* gives a request up. The promise then rejects.
|
||||
*
|
||||
* Resolves with the HTTP status and the JSON-RPC messages of the response:
|
||||
* the one message of a JSON body, or every message of an event stream. It
|
||||
@@ -218,6 +220,7 @@ export function claudeCodeMcpRequest(
|
||||
params: Record<string, unknown> = {},
|
||||
headers: Record<string, string> | undefined = config.headers,
|
||||
toolUseId = "toolu_01",
|
||||
abandoned?: AbortSignal,
|
||||
): Promise<{ status: number; messages: Array<Record<string, any>> }> {
|
||||
const meta =
|
||||
method === "tools/call"
|
||||
@@ -234,6 +237,7 @@ export function claudeCodeMcpRequest(
|
||||
config.url,
|
||||
{
|
||||
method: "POST",
|
||||
signal: abandoned,
|
||||
headers: {
|
||||
...headers,
|
||||
accept: "application/json, text/event-stream",
|
||||
@@ -267,7 +271,7 @@ export function claudeCodeMcpRequest(
|
||||
|
||||
/**
|
||||
* The message of the JSON-RPC error (`-33002`) that the HTTP bridge of
|
||||
* `@agentclientprotocol/sdk` 2.11.0 answers Claude Code with, when the client
|
||||
* `@agentclientprotocol/sdk` 2.12.0 answers Claude Code with, when the client
|
||||
* rejected the `mcp/message` request with `-32602` and the message
|
||||
* `Invalid params: <reason>`. Claude Code 2.1.330 passes it on as it is: as
|
||||
* the `error` of a PostToolUseFailure hook, and as the tool's result, which
|
||||
|
||||
@@ -337,12 +337,15 @@ describe("McpOverAcp", () => {
|
||||
agentId: agent?.id,
|
||||
agentType: agent?.type,
|
||||
});
|
||||
/** Claude Code sends `method` for the tool use `id`: what its `mcp/message` request named. */
|
||||
const request = async (id: string, method = "tools/call") => {
|
||||
await claudeCodeMcpRequest(config, method, { name: "echo" }, undefined, id);
|
||||
/**
|
||||
* Claude Code sends `method` for the tool use `id`: what its `mcp/message`
|
||||
* request named. It rejects when `abandoned` closes the request first.
|
||||
*/
|
||||
const request = async (id: string, method = "tools/call", abandoned?: AbortSignal) => {
|
||||
await claudeCodeMcpRequest(config, method, { name: "echo" }, undefined, id, abandoned);
|
||||
return named.at(-1);
|
||||
};
|
||||
return { mcp, tools, hook, request };
|
||||
return { mcp, tools, hook, request, named };
|
||||
}
|
||||
type RootSession = Awaited<ReturnType<typeof rootSession>>;
|
||||
|
||||
@@ -548,6 +551,21 @@ describe("McpOverAcp", () => {
|
||||
const held = mcp as unknown as Record<"toolUses" | "waiting", Map<string, unknown>>;
|
||||
expect([held.toolUses.size, held.waiting.size]).toEqual([0, 0]);
|
||||
});
|
||||
|
||||
it("stops waiting, and sends nothing, when Claude Code gives the request up", async () => {
|
||||
const { mcp, hook, request, named } = await rootSession(UNKNOWN_AGENT);
|
||||
await hook("PreToolUse", "toolu_01", { id: "agent-1" });
|
||||
const abandoned = new AbortController();
|
||||
|
||||
const requested = request("toolu_01", "tools/call", abandoned.signal);
|
||||
await vi.waitFor(() => expect(waiting(mcp).size).toBe(1));
|
||||
abandoned.abort();
|
||||
|
||||
await expect(requested).rejects.toThrow();
|
||||
// Not after the minute that the request would wait for an announcement.
|
||||
await vi.waitFor(() => expect(waiting(mcp).size).toBe(0));
|
||||
expect(named).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it.each<{ ended: string; end: (session: RootSession) => Promise<void> }>([
|
||||
|
||||
746
src/tests/session-rewind.test.ts
Normal file
746
src/tests/session-rewind.test.ts
Normal file
@@ -0,0 +1,746 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { appendFile, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { mkdirSync, rmSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { getSessionMessages, type SessionMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
activeSessionMessages,
|
||||
cutAtRewindPoint,
|
||||
isRewindRefusal,
|
||||
loadRewindableHistory,
|
||||
parseSessionRewindRequest,
|
||||
pendingRewindEnd,
|
||||
prepareRewoundResume,
|
||||
readRewindPoint,
|
||||
rewindSession,
|
||||
withoutRewoundBranch,
|
||||
writeRewindPoint,
|
||||
type RewindableHistory,
|
||||
type SessionRewindHost,
|
||||
} from "../session-rewind.js";
|
||||
import { loadFullSessionHistory } from "../resumed-session.js";
|
||||
import {
|
||||
transcriptAssistant,
|
||||
transcriptCompactBoundary,
|
||||
transcriptCompactSummary,
|
||||
transcriptUser,
|
||||
writeTranscript,
|
||||
} from "./helpers.js";
|
||||
|
||||
vi.mock("../resumed-session.js", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("../resumed-session.js")>();
|
||||
return { ...original, loadFullSessionHistory: vi.fn(original.loadFullSessionHistory) };
|
||||
});
|
||||
|
||||
vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("@anthropic-ai/claude-agent-sdk")>();
|
||||
return { ...original, getSessionMessages: vi.fn(original.getSessionMessages) };
|
||||
});
|
||||
|
||||
const SESSION_ID = "11111111-2222-3333-4444-555555555555";
|
||||
|
||||
function user(uuid: string, content: unknown, extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
type: "user",
|
||||
uuid,
|
||||
session_id: SESSION_ID,
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: { role: "user", content },
|
||||
...extra,
|
||||
} as unknown as SessionMessage;
|
||||
}
|
||||
|
||||
function assistant(uuid: string, extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
type: "assistant",
|
||||
uuid,
|
||||
session_id: SESSION_ID,
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: { role: "assistant", content: [{ type: "text", text: uuid }] },
|
||||
...extra,
|
||||
} as unknown as SessionMessage;
|
||||
}
|
||||
|
||||
/** Three turns. A cursor exists before `u2` and `u3`, and `s1` is a subagent's prompt. */
|
||||
const visible: SessionMessage[] = [
|
||||
user("u1", "first"),
|
||||
assistant("a1"),
|
||||
user("u2", "second"),
|
||||
assistant("a2"),
|
||||
user("r1", [{ type: "tool_result", tool_use_id: "t1", content: "ok" }]),
|
||||
assistant("a3"),
|
||||
user("s1", "subagent task", { parent_tool_use_id: "t2" }),
|
||||
user("u3", "third"),
|
||||
assistant("a4"),
|
||||
];
|
||||
|
||||
function fakeHost(
|
||||
overrides: Partial<SessionRewindHost> = {},
|
||||
history: RewindableHistory = { visible, current: visible },
|
||||
) {
|
||||
const replaceQuery = vi.fn<SessionRewindHost["replaceQuery"]>(async () => {});
|
||||
const rewound = vi.fn<SessionRewindHost["rewound"]>();
|
||||
const abandon = vi.fn<SessionRewindHost["abandon"]>(async (error) => error);
|
||||
const host: SessionRewindHost = {
|
||||
logger: { log: vi.fn(), error: vi.fn() },
|
||||
clearedContext: false,
|
||||
claudeIsWorking: () => false,
|
||||
hasBackgroundWork: () => false,
|
||||
loadHistory: async () => history,
|
||||
replaceQuery,
|
||||
rewound,
|
||||
abandon,
|
||||
...overrides,
|
||||
};
|
||||
return Object.assign(host, {
|
||||
replaceQuery: overrides.replaceQuery ?? replaceQuery,
|
||||
rewound: overrides.rewound ?? rewound,
|
||||
abandon: overrides.abandon ?? abandon,
|
||||
}) as SessionRewindHost & {
|
||||
replaceQuery: typeof replaceQuery;
|
||||
rewound: typeof rewound;
|
||||
abandon: typeof abandon;
|
||||
};
|
||||
}
|
||||
|
||||
let configDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
configDir = await mkdtemp(path.join(os.tmpdir(), "session-rewind-"));
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", configDir);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await rm(configDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const projectDir = () => path.join(configDir, "projects", "project");
|
||||
const rewindFile = () => path.join(projectDir(), SESSION_ID, "rewind.json");
|
||||
const exists = (file: string) =>
|
||||
stat(file).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
|
||||
describe("parseSessionRewindRequest", () => {
|
||||
it("takes a session id and a cursor id", () => {
|
||||
expect(parseSessionRewindRequest({ sessionId: "s", cursorId: "before:u2" })).toEqual({
|
||||
sessionId: "s",
|
||||
cursorId: "before:u2",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([null, "s", {}, { sessionId: "s" }, { cursorId: "c" }, { sessionId: "", cursorId: "c" }])(
|
||||
"rejects %j with -32602",
|
||||
(params) => {
|
||||
expect(() => parseSessionRewindRequest(params)).toThrow(
|
||||
expect.objectContaining({ code: -32602 }),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("rewindSession", () => {
|
||||
beforeEach(async () => {
|
||||
await writeTranscript(projectDir(), SESSION_ID, [
|
||||
transcriptUser("u1", "first"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptUser("u2", "second"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
]);
|
||||
});
|
||||
|
||||
const rewind = (host: SessionRewindHost, cursorId: string) =>
|
||||
rewindSession({ sessionId: SESSION_ID, cursorId }, host);
|
||||
|
||||
describe("the position", () => {
|
||||
it.each([
|
||||
["a cursor of no session", "before:nope"],
|
||||
["an id that is no cursor", "u2"],
|
||||
["the first message, which has no cursor", "before:u1"],
|
||||
["a tool result", "before:r1"],
|
||||
["a subagent's message", "before:s1"],
|
||||
["an agent message", "before:a2"],
|
||||
])("fails with -32602 for %s and changes nothing", async (_, cursorId) => {
|
||||
const host = fakeHost();
|
||||
await expect(rewind(host, cursorId)).rejects.toMatchObject({ code: -32602 });
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("fails with -32602 for a message before the newest compaction when the history before it cannot be read", async () => {
|
||||
await writeTranscript(projectDir(), SESSION_ID, [
|
||||
transcriptUser("u1", "first"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptUser("u2", "second"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
transcriptCompactBoundary("b1", "a2"),
|
||||
transcriptCompactSummary("s1"),
|
||||
transcriptUser("u3", "third"),
|
||||
transcriptAssistant("a3", "three"),
|
||||
]);
|
||||
const read = vi.mocked(getSessionMessages);
|
||||
const original = read.getMockImplementation()!;
|
||||
// The read across compactions is the one that gets a session store.
|
||||
read.mockImplementation(async (sessionId, options) => {
|
||||
if (options?.sessionStore) throw new Error("unreadable");
|
||||
return original(sessionId, options);
|
||||
});
|
||||
try {
|
||||
const host = fakeHost({ loadHistory: () => loadRewindableHistory(SESSION_ID) });
|
||||
await expect(rewind(host, "before:u2")).rejects.toMatchObject({ code: -32602 });
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeUndefined();
|
||||
} finally {
|
||||
read.mockImplementation(original);
|
||||
}
|
||||
});
|
||||
|
||||
it("resumes at the entry before the message, and drops that message", async () => {
|
||||
const host = fakeHost();
|
||||
expect(await rewind(host, "before:u3")).toEqual({ rewound: true });
|
||||
// The entry before `u3` is the subagent's prompt `s1`: the stored order.
|
||||
expect(host.replaceQuery).toHaveBeenCalledWith({
|
||||
resumeSessionAt: "s1",
|
||||
resumeDropsTurn: "u3",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("reports the cursor that it rewound to", async () => {
|
||||
const host = fakeHost();
|
||||
await rewind(host, "before:u2");
|
||||
expect(host.rewound).toHaveBeenCalledWith("before:u2");
|
||||
});
|
||||
|
||||
describe("resumeDropsTurn", () => {
|
||||
it("guards the last turn", async () => {
|
||||
const host = fakeHost();
|
||||
await rewind(host, "before:u3");
|
||||
expect(host.replaceQuery).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ resumeDropsTurn: "u3" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("is not passed for an earlier turn: the turns after it are in the dropped range", async () => {
|
||||
const host = fakeHost();
|
||||
await rewind(host, "before:u2");
|
||||
expect(host.replaceQuery).toHaveBeenCalledWith({ resumeSessionAt: "a1" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("refusals", () => {
|
||||
it.each([
|
||||
["busy", { claudeIsWorking: () => true }],
|
||||
["backgroundWork", { hasBackgroundWork: () => true }],
|
||||
["clearedContext", { clearedContext: true }],
|
||||
] as const)("answers %s without touching anything", async (reason, overrides) => {
|
||||
const host = fakeHost(overrides);
|
||||
expect(await rewind(host, "before:u2")).toEqual({ rewound: false, reason });
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("answers beforeCompaction for a message whose predecessor the compaction dropped", async () => {
|
||||
const host = fakeHost(
|
||||
{},
|
||||
{ visible, current: visible.filter((message) => message.uuid !== "a1") },
|
||||
);
|
||||
expect(await rewind(host, "before:u2")).toEqual({
|
||||
rewound: false,
|
||||
reason: "beforeCompaction",
|
||||
});
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers busy when Claude starts a cycle while the history is read", async () => {
|
||||
let working = false;
|
||||
const host = fakeHost({
|
||||
claudeIsWorking: () => working,
|
||||
loadHistory: async () => {
|
||||
working = true;
|
||||
return { visible, current: visible };
|
||||
},
|
||||
});
|
||||
expect(await rewind(host, "before:u2")).toEqual({ rewound: false, reason: "busy" });
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers busy when Claude starts a cycle while the transcript is prepared", async () => {
|
||||
let working = false;
|
||||
const host = fakeHost({
|
||||
claudeIsWorking: () => working,
|
||||
loadHistory: async () => {
|
||||
// After the history is read and before the transcript preparation ends.
|
||||
setImmediate(() => (working = true));
|
||||
return { visible, current: visible };
|
||||
},
|
||||
});
|
||||
expect(await rewind(host, "before:u2")).toEqual({ rewound: false, reason: "busy" });
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
expect(host.rewound).not.toHaveBeenCalled();
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("the rewind point", () => {
|
||||
it("is written before the query is replaced", async () => {
|
||||
const host = fakeHost();
|
||||
let writtenDuringCut: unknown;
|
||||
host.replaceQuery.mockImplementation(async () => {
|
||||
writtenDuringCut = await readRewindPoint(SESSION_ID);
|
||||
});
|
||||
await rewind(host, "before:u2");
|
||||
expect(writtenDuringCut).toEqual({ resumeSessionAt: "a1", droppedPromptUuid: "u2" });
|
||||
expect(await readRewindPoint(SESSION_ID)).toEqual(writtenDuringCut);
|
||||
expect(host.rewound).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("answers persistFailed and leaves the query alone when it cannot be written", async () => {
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", path.join(configDir, "elsewhere"));
|
||||
const host = fakeHost();
|
||||
expect(await rewind(host, "before:u2")).toEqual({
|
||||
rewound: false,
|
||||
reason: "persistFailed",
|
||||
});
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
expect(host.rewound).not.toHaveBeenCalled();
|
||||
expect(host.logger.error).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("when the cut does not happen", () => {
|
||||
const earlier = { resumeSessionAt: "a1", droppedPromptUuid: "u2" };
|
||||
const refusal = new Error("Resume rejected by --resume-drops-turn: queued message");
|
||||
|
||||
it.each([
|
||||
["no point", undefined],
|
||||
["an earlier pending point", earlier],
|
||||
])("restores %s after a failed cut", async (_, previous) => {
|
||||
if (previous) await writeRewindPoint(SESSION_ID, previous);
|
||||
const before = previous && (await readFile(rewindFile(), "utf8"));
|
||||
const host = fakeHost();
|
||||
host.replaceQuery.mockRejectedValueOnce(refusal);
|
||||
expect(await rewind(host, "before:u3")).toEqual({
|
||||
rewound: false,
|
||||
reason: "providerRefused",
|
||||
});
|
||||
expect(await readRewindPoint(SESSION_ID)).toEqual(previous);
|
||||
if (before !== undefined) expect(await readFile(rewindFile(), "utf8")).toBe(before);
|
||||
expect(host.rewound).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("restores the point before the recovery resumes, which reads it", async () => {
|
||||
const host = fakeHost();
|
||||
host.replaceQuery.mockRejectedValueOnce(refusal);
|
||||
let seenByRecovery: unknown = "unset";
|
||||
host.replaceQuery.mockImplementationOnce(async () => {
|
||||
seenByRecovery = await readRewindPoint(SESSION_ID);
|
||||
});
|
||||
await rewind(host, "before:u3");
|
||||
expect(seenByRecovery).toBeUndefined();
|
||||
});
|
||||
|
||||
it("restores the point when the rewind is abandoned", async () => {
|
||||
const host = fakeHost();
|
||||
host.replaceQuery.mockRejectedValue(refusal);
|
||||
await expect(rewind(host, "before:u3")).rejects.toBe(refusal);
|
||||
expect(await exists(rewindFile())).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no point", undefined],
|
||||
["an earlier pending point", earlier],
|
||||
])("restores %s when Claude starts a cycle before the cut", async (_, previous) => {
|
||||
if (previous) await writeRewindPoint(SESSION_ID, previous);
|
||||
let working = false;
|
||||
const host = fakeHost({
|
||||
claudeIsWorking: () => working,
|
||||
loadHistory: async () => {
|
||||
// After the history is read and before the point is written.
|
||||
setImmediate(() => setImmediate(() => (working = true)));
|
||||
return { visible, current: visible };
|
||||
},
|
||||
});
|
||||
const before = previous && (await readFile(rewindFile(), "utf8"));
|
||||
expect(await rewind(host, "before:u3")).toEqual({ rewound: false, reason: "busy" });
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
expect(await readRewindPoint(SESSION_ID)).toEqual(previous);
|
||||
if (before !== undefined) expect(await readFile(rewindFile(), "utf8")).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when the point cannot be put back", () => {
|
||||
const refusal = new Error("Resume rejected by --resume-drops-turn: queued message");
|
||||
/** Replaces `rewind.json` with a directory, which `rm` without `recursive` cannot remove. */
|
||||
const blockRemoval = async () => {
|
||||
await rm(rewindFile(), { force: true });
|
||||
await mkdir(rewindFile());
|
||||
};
|
||||
|
||||
it("fails instead of answering busy, when Claude starts a cycle before the cut", async () => {
|
||||
let calls = 0;
|
||||
const host = fakeHost({
|
||||
claudeIsWorking: () => {
|
||||
// The second check is the one after the point is written.
|
||||
if (++calls < 2) return false;
|
||||
rmSync(rewindFile(), { force: true });
|
||||
mkdirSync(rewindFile());
|
||||
return true;
|
||||
},
|
||||
});
|
||||
await expect(rewind(host, "before:u3")).rejects.toMatchObject({ code: -32603 });
|
||||
expect(host.replaceQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails after the recovery resume, when the cut fails", async () => {
|
||||
const host = fakeHost();
|
||||
host.replaceQuery.mockImplementationOnce(async () => {
|
||||
await blockRemoval();
|
||||
throw refusal;
|
||||
});
|
||||
await expect(rewind(host, "before:u3")).rejects.toMatchObject({ code: -32603 });
|
||||
expect(host.replaceQuery).toHaveBeenCalledTimes(2);
|
||||
expect(host.replaceQuery.mock.calls.at(-1)).toEqual([undefined]);
|
||||
expect(host.abandon).not.toHaveBeenCalled();
|
||||
expect(host.rewound).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("no longer accepts a cursor at or after the cut, and a second rewind works", async () => {
|
||||
expect(await rewind(fakeHost(), "before:u2")).toEqual({ rewound: true });
|
||||
|
||||
// The transcript still holds the dropped branch, and the SDK reads it to its end.
|
||||
const afterRewind = await loadRewindableHistory(SESSION_ID);
|
||||
expect(afterRewind.visible.map((message) => message.uuid)).toEqual(["u1", "a1"]);
|
||||
await expect(
|
||||
rewindSession({ sessionId: SESSION_ID, cursorId: "before:u2" }, fakeHost({}, afterRewind)),
|
||||
).rejects.toMatchObject({ code: -32602 });
|
||||
|
||||
// The next prompts continue from the cut, as Claude Code writes them.
|
||||
const line = (record: Record<string, unknown>) =>
|
||||
appendFile(
|
||||
path.join(projectDir(), `${SESSION_ID}.jsonl`),
|
||||
JSON.stringify({ sessionId: SESSION_ID, isSidechain: false, ...record }) + "\n",
|
||||
);
|
||||
await line({ ...transcriptUser("n1", "edited"), parentUuid: "a1" });
|
||||
await line({ ...transcriptAssistant("n2", "answer"), parentUuid: "n1" });
|
||||
await line({ ...transcriptUser("n3", "more"), parentUuid: "n2" });
|
||||
await line({ ...transcriptAssistant("n4", "more answer"), parentUuid: "n3" });
|
||||
|
||||
const second = fakeHost();
|
||||
const secondHistory = await loadRewindableHistory(SESSION_ID);
|
||||
expect(secondHistory.visible.map((message) => message.uuid)).toEqual([
|
||||
"u1",
|
||||
"a1",
|
||||
"n1",
|
||||
"n2",
|
||||
"n3",
|
||||
"n4",
|
||||
]);
|
||||
expect(
|
||||
await rewind({ ...second, loadHistory: async () => secondHistory }, "before:n3"),
|
||||
).toEqual({ rewound: true });
|
||||
expect(second.replaceQuery).toHaveBeenCalledWith({
|
||||
resumeSessionAt: "n2",
|
||||
resumeDropsTurn: "n3",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("recovery", () => {
|
||||
const refusal = new Error(
|
||||
"Resume rejected by --resume-drops-turn: the range holds a queued message",
|
||||
);
|
||||
|
||||
it.each([
|
||||
["a refusal of the cut", refusal],
|
||||
["a failed restart", new Error("spawn failed")],
|
||||
])("recovers once into the untruncated conversation after %s", async (_, error) => {
|
||||
const host = fakeHost();
|
||||
host.replaceQuery.mockRejectedValueOnce(error);
|
||||
expect(await rewind(host, "before:u3")).toEqual({
|
||||
rewound: false,
|
||||
reason: "providerRefused",
|
||||
});
|
||||
expect(host.replaceQuery.mock.calls).toEqual([
|
||||
[{ resumeSessionAt: "s1", resumeDropsTurn: "u3" }],
|
||||
[undefined],
|
||||
]);
|
||||
expect(host.abandon).not.toHaveBeenCalled();
|
||||
expect(await exists(rewindFile())).toBe(false);
|
||||
});
|
||||
|
||||
it("recovers into the cut that an earlier rewind made", async () => {
|
||||
await writeRewindPoint(SESSION_ID, { resumeSessionAt: "a1", droppedPromptUuid: "u2" });
|
||||
const host = fakeHost();
|
||||
host.replaceQuery.mockRejectedValueOnce(refusal);
|
||||
await rewind(host, "before:u3");
|
||||
expect(host.replaceQuery.mock.calls.at(-1)).toEqual([{ resumeSessionAt: "a1" }]);
|
||||
});
|
||||
|
||||
it("fails with what abandon returns when the recovery fails too", async () => {
|
||||
const failure = new Error("could not resume");
|
||||
const host = fakeHost({ abandon: vi.fn(async () => failure) });
|
||||
host.replaceQuery.mockRejectedValue(refusal);
|
||||
await expect(rewind(host, "before:u3")).rejects.toBe(failure);
|
||||
expect(host.replaceQuery).toHaveBeenCalledTimes(2);
|
||||
expect(host.abandon).toHaveBeenCalledWith(refusal);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("isRewindRefusal", () => {
|
||||
it("matches the message prefix of the CLI's refusal only", () => {
|
||||
expect(isRewindRefusal(new Error("Resume rejected by --resume-drops-turn: x"))).toBe(true);
|
||||
expect(isRewindRefusal(new Error("No message found with message.uuid of x"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("activeSessionMessages", () => {
|
||||
const history = visible.slice(0, 4);
|
||||
|
||||
it("cuts a history that still ends in the dropped branch", () => {
|
||||
expect(
|
||||
activeSessionMessages(history, { resumeSessionAt: "a1", droppedPromptUuid: "u2" }).map(
|
||||
(message) => message.uuid,
|
||||
),
|
||||
).toEqual(["u1", "a1"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no rewind point", undefined],
|
||||
[
|
||||
"a point whose dropped prompt a later branch left out",
|
||||
{ resumeSessionAt: "a1", droppedPromptUuid: "gone" },
|
||||
],
|
||||
])("returns the history as it is for %s", (_, point) => {
|
||||
expect(activeSessionMessages(history, point)).toEqual(history);
|
||||
});
|
||||
});
|
||||
|
||||
describe("prepareRewoundResume", () => {
|
||||
const lastPrompts = async () =>
|
||||
(await readFile(path.join(projectDir(), `${SESSION_ID}.jsonl`), "utf8"))
|
||||
.split("\n")
|
||||
.filter((line) => line.includes('"last-prompt"'))
|
||||
.map((line) => JSON.parse(line));
|
||||
|
||||
beforeEach(async () => {
|
||||
await writeTranscript(projectDir(), SESSION_ID, [
|
||||
transcriptUser("u1", "first"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptUser("u2", "second"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does nothing for a session that was never rewound", async () => {
|
||||
expect(await prepareRewoundResume(SESSION_ID)).toBeUndefined();
|
||||
expect(await lastPrompts()).toEqual([]);
|
||||
});
|
||||
|
||||
it("names the rewind point explicitly while the dropped branch is the newest", async () => {
|
||||
await writeRewindPoint(SESSION_ID, { resumeSessionAt: "a1", droppedPromptUuid: "u2" });
|
||||
expect(await prepareRewoundResume(SESSION_ID)).toBe("a1");
|
||||
expect(await lastPrompts()).toEqual([
|
||||
{
|
||||
type: "last-prompt",
|
||||
lastPrompt: "first",
|
||||
leafUuid: "a1",
|
||||
explicit: true,
|
||||
sessionId: SESSION_ID,
|
||||
},
|
||||
]);
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeDefined();
|
||||
});
|
||||
|
||||
it("names the newest entry and removes the point once a branch descends from it", async () => {
|
||||
await writeRewindPoint(SESSION_ID, { resumeSessionAt: "a1", droppedPromptUuid: "u2" });
|
||||
await appendFile(
|
||||
path.join(projectDir(), `${SESSION_ID}.jsonl`),
|
||||
JSON.stringify({
|
||||
...transcriptUser("n1", "edited"),
|
||||
parentUuid: "a1",
|
||||
sessionId: SESSION_ID,
|
||||
}) + "\n",
|
||||
);
|
||||
expect(await prepareRewoundResume(SESSION_ID)).toBeUndefined();
|
||||
expect(await lastPrompts()).toEqual([
|
||||
{ type: "last-prompt", lastPrompt: "edited", leafUuid: "n1", sessionId: SESSION_ID },
|
||||
]);
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("prepareRewoundResume with trailing metadata and failures", () => {
|
||||
const transcript = () => path.join(projectDir(), `${SESSION_ID}.jsonl`);
|
||||
|
||||
beforeEach(async () => {
|
||||
await writeTranscript(projectDir(), SESSION_ID, [
|
||||
transcriptUser("u1", "first"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptUser("u2", "second"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
]);
|
||||
await writeRewindPoint(SESSION_ID, { resumeSessionAt: "a1", droppedPromptUuid: "u2" });
|
||||
await appendFile(
|
||||
transcript(),
|
||||
[
|
||||
{ ...transcriptUser("n1", "edited"), parentUuid: "a1", sessionId: SESSION_ID },
|
||||
{ ...transcriptAssistant("n2", "answer"), parentUuid: "n1", sessionId: SESSION_ID },
|
||||
{ type: "ai-title", uuid: "t1", aiTitle: "A title", sessionId: SESSION_ID },
|
||||
{ type: "tag", uuid: "t2", tag: "x", sessionId: SESSION_ID },
|
||||
]
|
||||
.map((record) => JSON.stringify(record))
|
||||
.join("\n") + "\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the edited conversation when uuid-bearing metadata follows it", async () => {
|
||||
expect(await prepareRewoundResume(SESSION_ID)).toBeUndefined();
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeUndefined();
|
||||
const lastPrompt = (await readFile(transcript(), "utf8"))
|
||||
.split("\n")
|
||||
.filter((line) => line.includes('"last-prompt"'))
|
||||
.map((line) => JSON.parse(line))
|
||||
.at(-1);
|
||||
expect(lastPrompt).toMatchObject({ leafUuid: "n2" });
|
||||
expect(lastPrompt.explicit).toBeUndefined();
|
||||
});
|
||||
|
||||
it("fails the resume instead of resuming plainly when the history cannot be read", async () => {
|
||||
vi.mocked(loadFullSessionHistory).mockRejectedValueOnce(new Error("EIO"));
|
||||
await expect(prepareRewoundResume(SESSION_ID)).rejects.toMatchObject({
|
||||
message: expect.stringContaining("could not be prepared"),
|
||||
});
|
||||
expect(await readRewindPoint(SESSION_ID)).toBeDefined();
|
||||
});
|
||||
|
||||
describe.each([
|
||||
[
|
||||
"cannot be read",
|
||||
async () => {
|
||||
await rm(rewindFile(), { force: true });
|
||||
await mkdir(rewindFile());
|
||||
},
|
||||
],
|
||||
["is not JSON", () => writeFile(rewindFile(), "{ not json")],
|
||||
["lacks the cut", () => writeFile(rewindFile(), JSON.stringify({ resumeSessionAt: "a1" }))],
|
||||
])("a rewind point that %s", (_, corrupt) => {
|
||||
beforeEach(corrupt);
|
||||
|
||||
it("fails the resume, and leaves the transcript and the point alone", async () => {
|
||||
const before = await readFile(transcript(), "utf8");
|
||||
await expect(prepareRewoundResume(SESSION_ID)).rejects.toMatchObject({
|
||||
message: expect.stringContaining("rewind point cannot be read"),
|
||||
});
|
||||
expect(await readFile(transcript(), "utf8")).toBe(before);
|
||||
expect(await exists(rewindFile())).toBe(true);
|
||||
});
|
||||
|
||||
it("fails the replay, the fork reads and the rewind instead of showing the dropped turns", async () => {
|
||||
const stored = await getSessionMessages(SESSION_ID);
|
||||
await expect(cutAtRewindPoint(SESSION_ID, stored)).rejects.toThrow("cannot be read");
|
||||
await expect(pendingRewindEnd(SESSION_ID)).rejects.toThrow("cannot be read");
|
||||
await expect(withoutRewoundBranch(SESSION_ID, [])).rejects.toThrow("cannot be read");
|
||||
await expect(readRewindPoint(SESSION_ID)).rejects.toThrow("cannot be read");
|
||||
});
|
||||
});
|
||||
|
||||
it("is unaffected by a failing history read when there is no rewind point", async () => {
|
||||
await rm(rewindFile(), { force: true });
|
||||
vi.mocked(loadFullSessionHistory).mockRejectedValueOnce(new Error("EIO"));
|
||||
expect(await prepareRewoundResume(SESSION_ID)).toBeUndefined();
|
||||
vi.mocked(loadFullSessionHistory).mockReset();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a pending rewind point", () => {
|
||||
const point = { resumeSessionAt: "a2", droppedPromptUuid: "u3" };
|
||||
|
||||
beforeEach(async () => {
|
||||
await writeTranscript(projectDir(), SESSION_ID, [
|
||||
transcriptUser("u1", "first"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptUser("u2", "second"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
transcriptUser("u3", "third"),
|
||||
transcriptAssistant("a3", "three"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("is cut from the stored history, and from nothing else once it is not pending", async () => {
|
||||
const stored = await getSessionMessages(SESSION_ID);
|
||||
expect(stored.map((message) => message.uuid)).toEqual(["u1", "a1", "u2", "a2", "u3", "a3"]);
|
||||
expect(await cutAtRewindPoint(SESSION_ID, stored)).toHaveLength(6);
|
||||
|
||||
await writeRewindPoint(SESSION_ID, point);
|
||||
expect((await cutAtRewindPoint(SESSION_ID, stored)).map((message) => message.uuid)).toEqual([
|
||||
"u1",
|
||||
"a1",
|
||||
"u2",
|
||||
"a2",
|
||||
]);
|
||||
});
|
||||
|
||||
it("is cut before the history of a compaction is read", async () => {
|
||||
await writeTranscript(projectDir(), SESSION_ID, [
|
||||
transcriptUser("u1", "first"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptCompactBoundary("b1", "a1"),
|
||||
transcriptCompactSummary("s1"),
|
||||
transcriptUser("u2", "second"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
transcriptUser("u3", "third"),
|
||||
transcriptAssistant("a3", "three"),
|
||||
]);
|
||||
const uuids = async () =>
|
||||
(await loadRewindableHistory(SESSION_ID)).visible.map((message) => message.uuid);
|
||||
expect(await uuids()).toEqual(["u1", "a1", "s1", "u2", "a2", "u3", "a3"]);
|
||||
|
||||
await writeRewindPoint(SESSION_ID, point);
|
||||
const history = await loadRewindableHistory(SESSION_ID);
|
||||
expect(history.visible.map((message) => message.uuid)).toEqual(["u1", "a1", "s1", "u2", "a2"]);
|
||||
expect(history.current.map((message) => message.uuid)).toEqual(["s1", "u2", "a2"]);
|
||||
});
|
||||
|
||||
it("ends a fork of the whole session at its resume entry, until a branch descends from it", async () => {
|
||||
expect(await pendingRewindEnd(SESSION_ID)).toBeUndefined();
|
||||
await writeRewindPoint(SESSION_ID, point);
|
||||
expect(await pendingRewindEnd(SESSION_ID)).toBe("a2");
|
||||
|
||||
await appendFile(
|
||||
path.join(projectDir(), `${SESSION_ID}.jsonl`),
|
||||
JSON.stringify({
|
||||
...transcriptUser("n1", "edited"),
|
||||
parentUuid: "a2",
|
||||
sessionId: SESSION_ID,
|
||||
}) + "\n",
|
||||
);
|
||||
expect(await pendingRewindEnd(SESSION_ID)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("leaves out the dropped branch of the full history, and keeps the other inactive ones", async () => {
|
||||
await appendFile(
|
||||
path.join(projectDir(), `${SESSION_ID}.jsonl`),
|
||||
JSON.stringify({
|
||||
...transcriptAssistant("alt", "older branch"),
|
||||
parentUuid: "u2",
|
||||
sessionId: SESSION_ID,
|
||||
}) + "\n",
|
||||
);
|
||||
const full = await loadFullSessionHistory(SESSION_ID);
|
||||
const uuids = async () =>
|
||||
(await withoutRewoundBranch(SESSION_ID, full)).flatMap((entry) =>
|
||||
typeof entry.uuid === "string" ? [entry.uuid] : [],
|
||||
);
|
||||
expect(await uuids()).toEqual(["u1", "a1", "u2", "a2", "u3", "a3", "alt"]);
|
||||
|
||||
await writeRewindPoint(SESSION_ID, point);
|
||||
expect(await uuids()).toEqual(["u1", "a1", "u2", "a2", "alt"]);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { messageIdForGrouping } from "../../sdk-to-acp.js";
|
||||
import { forkSession } from "../../fork-session.js";
|
||||
import { writeRewindPoint } from "../../session-rewind.js";
|
||||
import { encodeProjectPath } from "../../session-index/project-dirs.js";
|
||||
|
||||
// Use the real SDK against temporary transcripts, without starting Claude Code.
|
||||
@@ -227,3 +228,50 @@ describe("fork at a session cursor", () => {
|
||||
expect(await fs.readdir(path.dirname(sourceFile))).toEqual([path.basename(sourceFile)]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fork after a rewind", () => {
|
||||
const fork = (extra: Partial<Parameters<typeof forkSession>[0]>, deps = {}) =>
|
||||
forkSession(
|
||||
{ sessionId, cwd: sourceCwd, mcpServers: [], ...extra },
|
||||
{ messageIdForGrouping, ...deps },
|
||||
);
|
||||
const messagePoint = (messageId: string) => ({
|
||||
_meta: { jetbrains: { air: { fork: { version: 1, messageId } } } },
|
||||
});
|
||||
let droppedPrompt: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
// The user rewound the follow-up: it and its answers stay in the transcript.
|
||||
const [, firstAnswer, followup] = await getSessionMessages(sessionId, { dir: sourceCwd });
|
||||
droppedPrompt = followup!.uuid;
|
||||
await writeRewindPoint(sessionId, {
|
||||
resumeSessionAt: firstAnswer!.uuid,
|
||||
droppedPromptUuid: droppedPrompt,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the whole session", {}],
|
||||
["a message of the retained part", messagePoint("msg_first")],
|
||||
])("copies the retained history for %s", async (_, extra) => {
|
||||
const forked = await getSessionMessages((await fork(extra)).sessionId);
|
||||
expect(forked.map((message) => message.message)).toEqual([
|
||||
{ role: "user", content: "First prompt" },
|
||||
expect.objectContaining({ id: "msg_first" }),
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the dropped prompt's cursor", () => ({ cursorId: `before:${droppedPrompt}` }), "cursorId"],
|
||||
["an active message of the dropped part", () => messagePoint("msg_active"), "messageId"],
|
||||
["an inactive message of the dropped part", () => messagePoint("msg_inactive"), "messageId"],
|
||||
])("rejects %s with -32602 and forks nothing", async (_, request, field) => {
|
||||
await expect(fork(request())).rejects.toMatchObject({
|
||||
code: -32602,
|
||||
data: expect.objectContaining({ [field]: expect.any(String) }),
|
||||
});
|
||||
expect(
|
||||
(await fs.readdir(path.dirname(sourceFile))).filter((name) => name.endsWith(".jsonl")),
|
||||
).toEqual([path.basename(sourceFile)]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,8 @@ import { describe, it, expect, vi } from "vitest";
|
||||
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import { Pushable } from "../../utils.js";
|
||||
import { initializeClient } from "../helpers.js";
|
||||
import { AIR_SESSION_REWIND_CAPABILITY } from "../../air-extension.js";
|
||||
import { mockSessionState, successfulResultMessage, wrapQuery } from "./session-doubles.js";
|
||||
|
||||
const HUMAN = { kind: "human" };
|
||||
@@ -41,7 +43,7 @@ function createAgent() {
|
||||
const userChunks = () =>
|
||||
updates.filter((update) => update.sessionUpdate === "user_message_chunk");
|
||||
const userTexts = () => userChunks().map((update) => update.content.text);
|
||||
return { agent, userTexts, userChunks };
|
||||
return { agent, updates, userTexts, userChunks };
|
||||
}
|
||||
|
||||
async function promptWith(messages: (promptUuid: string) => unknown[]) {
|
||||
@@ -204,3 +206,70 @@ describe("user messages typed in another client of the session", () => {
|
||||
expect(chunks.map((chunk) => chunk.content)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the cursor of a user message typed in another client", () => {
|
||||
const REWIND_CLIENT = {
|
||||
session: { cursors: {} },
|
||||
_meta: { jetbrains: { air: { version: 1, capabilities: [AIR_SESSION_REWIND_CAPABILITY] } } },
|
||||
};
|
||||
const answer = {
|
||||
type: "assistant",
|
||||
uuid: "answer-1",
|
||||
session_id: "test-session",
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: {
|
||||
id: "msg_answer-1",
|
||||
role: "assistant",
|
||||
model: "claude-sonnet-4",
|
||||
content: [{ type: "text", text: "Answer" }],
|
||||
usage: {},
|
||||
},
|
||||
};
|
||||
|
||||
async function cursorsAfter(messages: unknown[], capabilities: object = REWIND_CLIENT) {
|
||||
const { agent, updates } = createAgent();
|
||||
await initializeClient(agent, capabilities);
|
||||
const input = new Pushable<any>();
|
||||
async function* generator() {
|
||||
const { value: sent } = await input[Symbol.asyncIterator]().next();
|
||||
yield echoOfAdapterMessage(sent.uuid, "typed in Zed");
|
||||
yield* messages;
|
||||
yield successfulResultMessage();
|
||||
yield idle;
|
||||
}
|
||||
agent.sessions["test-session"] = mockSessionState({ query: wrapQuery(generator()), input });
|
||||
await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "typed" }] });
|
||||
return updates.filter((update) => update.sessionUpdate === "cursor_update");
|
||||
}
|
||||
|
||||
it("is announced before the message, with the capabilities of the client", async () => {
|
||||
const cursors = await cursorsAfter([
|
||||
answer,
|
||||
userReplay("phone-1", "typed on the phone", { origin: HUMAN }),
|
||||
]);
|
||||
expect(cursors).toEqual([
|
||||
{
|
||||
sessionUpdate: "cursor_update",
|
||||
cursorId: "before:phone-1",
|
||||
capabilities: { fork: {}, rewind: {} },
|
||||
anchor: { type: "user_message", messageId: "phone-1", position: "before" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a message of a subagent", { origin: HUMAN, parent_tool_use_id: "toolu_1" }],
|
||||
["a slash command", { origin: HUMAN }, "/review"],
|
||||
])("is not announced for %s", async (_description, extra, text = "typed on the phone") => {
|
||||
const cursors = await cursorsAfter([answer, userReplay("phone-1", text, extra)]);
|
||||
expect(cursors).toEqual([]);
|
||||
});
|
||||
|
||||
it("is not announced for the first message of the session", async () => {
|
||||
const cursors = await cursorsAfter([
|
||||
userReplay("phone-1", "typed on the phone", { origin: HUMAN }),
|
||||
]);
|
||||
expect(cursors).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
319
src/tests/v1/session-cursors.test.ts
Normal file
319
src/tests/v1/session-cursors.test.ts
Normal file
@@ -0,0 +1,319 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
forkSession as forkClaudeSession,
|
||||
getSessionMessages,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { ClientCapabilities } from "@agentclientprotocol/sdk/unstable";
|
||||
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import { LastReportedEntity } from "../../session-cursors.js";
|
||||
import { Pushable } from "../../utils.js";
|
||||
import { initializeClient } from "../helpers.js";
|
||||
import {
|
||||
mockSessionState,
|
||||
successfulResultMessage,
|
||||
userEcho,
|
||||
wrapQuery,
|
||||
} from "./session-doubles.js";
|
||||
|
||||
vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@anthropic-ai/claude-agent-sdk")>();
|
||||
return { ...actual, forkSession: vi.fn(), getSessionMessages: vi.fn() };
|
||||
});
|
||||
|
||||
type History = Awaited<ReturnType<typeof getSessionMessages>>;
|
||||
|
||||
const WITH_CURSORS: ClientCapabilities = { session: { cursors: {} } };
|
||||
|
||||
function user(uuid: string, content: unknown, extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
type: "user",
|
||||
uuid,
|
||||
session_id: "s1",
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: { role: "user", content },
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function assistant(uuid: string, content: unknown[], extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
type: "assistant",
|
||||
uuid,
|
||||
session_id: "s1",
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: { id: `msg_${uuid}`, role: "assistant", model: "claude-sonnet-4", content, usage: {} },
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
/** The history of a session: the user messages that get a cursor are `u2` and `u6`. */
|
||||
const history = [
|
||||
user("u1", "First prompt"),
|
||||
assistant("a1", [{ type: "tool_use", id: "toolu_1", name: "Bash", input: { command: "ls" } }]),
|
||||
// A tool result is no user message.
|
||||
user("r1", [{ type: "tool_result", tool_use_id: "toolu_1", content: "ok" }]),
|
||||
assistant("a2", [{ type: "text", text: "Done" }]),
|
||||
user("u2", "Second prompt"),
|
||||
assistant("a3", [{ type: "text", text: "Sub" }], { parent_tool_use_id: "toolu_2" }),
|
||||
// A subagent's prompt.
|
||||
user("s1", "Subagent task", { parent_tool_use_id: "toolu_2" }),
|
||||
// A local command that a replay does not show.
|
||||
user("c1", "<command-name>/compact</command-name><command-message>compact</command-message>"),
|
||||
assistant("a4", [{ type: "text", text: "Answer" }]),
|
||||
user("u6", "Third prompt"),
|
||||
] as unknown as History;
|
||||
|
||||
function setup(capabilities: ClientCapabilities) {
|
||||
const updates: any[] = [];
|
||||
const agent = new ClaudeAcpAgent(
|
||||
{
|
||||
sessionUpdate: async (notification: any) => {
|
||||
updates.push(notification.update);
|
||||
},
|
||||
} as unknown as AcpClient,
|
||||
{ log: () => {}, error: () => {} },
|
||||
);
|
||||
const cursors = () => updates.filter((update) => update.sessionUpdate === "cursor_update");
|
||||
const replay = async (messages: History = history) => {
|
||||
vi.mocked(getSessionMessages).mockResolvedValueOnce(messages);
|
||||
await (
|
||||
agent as unknown as { replaySessionHistory(sessionId: string): Promise<void> }
|
||||
).replaySessionHistory("s1");
|
||||
};
|
||||
return { agent, updates, cursors, replay, ready: () => initializeClient(agent, capabilities) };
|
||||
}
|
||||
|
||||
const cursorOf = (uuid: string, anchor: unknown) => ({
|
||||
sessionUpdate: "cursor_update",
|
||||
cursorId: `before:${uuid}`,
|
||||
capabilities: { fork: {} },
|
||||
anchor,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(getSessionMessages).mockReset();
|
||||
vi.mocked(forkClaudeSession).mockReset();
|
||||
});
|
||||
|
||||
describe("session cursors on v1", () => {
|
||||
describe("replay", () => {
|
||||
it("announces a cursor right after each user message that a fork can start before", async () => {
|
||||
const { updates, cursors, replay, ready } = setup(WITH_CURSORS);
|
||||
await ready();
|
||||
await replay();
|
||||
|
||||
// The first message, a tool result, a subagent's message and a hidden command get none.
|
||||
expect(cursors()).toEqual([
|
||||
cursorOf("u2", { type: "user_message", messageId: "u2", position: "before" }),
|
||||
cursorOf("u6", { type: "user_message", messageId: "u6", position: "before" }),
|
||||
]);
|
||||
// The anchor names the messageId that the replayed message carries.
|
||||
for (const cursor of cursors()) {
|
||||
const index = updates.indexOf(cursor);
|
||||
expect(updates[index - 1]).toMatchObject({
|
||||
sessionUpdate: "user_message_chunk",
|
||||
messageId: cursor.anchor.messageId,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["declares no cursors", {}],
|
||||
["declares them as null", { session: { cursors: null } }],
|
||||
])("sends no cursor to a client that %s", async (_, capabilities) => {
|
||||
const { cursors, replay, ready } = setup(capabilities as ClientCapabilities);
|
||||
await ready();
|
||||
await replay();
|
||||
expect(cursors()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("live prompt", () => {
|
||||
/** A session that answers each prompt with one agent message, and the prompts' uuids. */
|
||||
function liveSession(capabilities: ClientCapabilities) {
|
||||
const harness = setup(capabilities);
|
||||
const input = new Pushable<any>();
|
||||
const prompts: string[] = [];
|
||||
async function* answers() {
|
||||
for await (const prompt of input) {
|
||||
prompts.push(prompt.uuid);
|
||||
yield userEcho(prompt);
|
||||
yield assistant(`live-${prompts.length}`, [{ type: "text", text: "Answer" }], {
|
||||
session_id: "test-session",
|
||||
});
|
||||
yield successfulResultMessage();
|
||||
yield { type: "system", subtype: "session_state_changed", state: "idle" };
|
||||
}
|
||||
}
|
||||
harness.agent.sessions["test-session"] = mockSessionState({
|
||||
query: wrapQuery(answers()),
|
||||
input,
|
||||
});
|
||||
const prompt = (text: string) =>
|
||||
harness.agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text }] });
|
||||
return { ...harness, prompt, prompts };
|
||||
}
|
||||
|
||||
it("announces the cursor after the entity before it, which a later replay issues too", async () => {
|
||||
const { cursors, prompt, prompts, replay, ready } = liveSession(WITH_CURSORS);
|
||||
await ready();
|
||||
await prompt("First");
|
||||
// The first prompt of a session has nothing before it, and a slash command gets none.
|
||||
await prompt("/context");
|
||||
expect(cursors()).toEqual([]);
|
||||
await prompt("Second");
|
||||
|
||||
expect(cursors()).toEqual([
|
||||
cursorOf(prompts[2]!, {
|
||||
type: "agent_message",
|
||||
messageId: "msg_live-2",
|
||||
position: "after",
|
||||
}),
|
||||
]);
|
||||
|
||||
// The stored history of those prompts, as Claude Code writes it.
|
||||
await replay([
|
||||
user(prompts[0]!, "First"),
|
||||
assistant("a1", [{ type: "text", text: "Answer" }]),
|
||||
user(prompts[2]!, "Second"),
|
||||
] as unknown as History);
|
||||
expect(cursors().at(-1)).toEqual(
|
||||
cursorOf(prompts[2]!, { type: "user_message", messageId: prompts[2]!, position: "before" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("sends no cursor to a client that declares none", async () => {
|
||||
const { cursors, prompt, ready } = liveSession({});
|
||||
await ready();
|
||||
await prompt("First");
|
||||
await prompt("Second");
|
||||
expect(cursors()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("session/fork at a cursor", () => {
|
||||
async function fork(cursorId: string) {
|
||||
const { agent, replay, cursors, ready } = setup(WITH_CURSORS);
|
||||
await ready();
|
||||
vi.spyOn(agent as any, "validateCwd").mockResolvedValue(undefined);
|
||||
vi.spyOn(agent as any, "getOrCreateSession").mockResolvedValue({
|
||||
sessionId: "forked",
|
||||
modes: null,
|
||||
configOptions: [],
|
||||
});
|
||||
await replay();
|
||||
const announced = cursors().map((cursor) => cursor.cursorId);
|
||||
vi.mocked(getSessionMessages).mockResolvedValueOnce(history);
|
||||
vi.mocked(forkClaudeSession).mockResolvedValueOnce({ sessionId: "forked" });
|
||||
const response = agent.unstable_forkSession({
|
||||
sessionId: "s1",
|
||||
cwd: "/workspace",
|
||||
mcpServers: [],
|
||||
cursorId,
|
||||
});
|
||||
return { announced, response };
|
||||
}
|
||||
|
||||
it("forks the history before the announced cursor's message", async () => {
|
||||
const { announced, response } = await fork("before:u6");
|
||||
expect(announced).toContain("before:u6");
|
||||
await expect(response).resolves.toMatchObject({ sessionId: "forked" });
|
||||
expect(forkClaudeSession).toHaveBeenCalledWith("s1", { upToMessageId: "a4" });
|
||||
});
|
||||
|
||||
it.each(["before:u1", "before:s1", "cur_unknown"])(
|
||||
"rejects %s with -32602",
|
||||
async (cursorId) => {
|
||||
const { announced, response } = await fork(cursorId);
|
||||
expect(announced).not.toContain(cursorId);
|
||||
await expect(response).rejects.toMatchObject({ code: -32602, data: { cursorId } });
|
||||
expect(forkClaudeSession).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the entity that a live cursor anchors to", () => {
|
||||
const send = (tracker: LastReportedEntity, update: Record<string, unknown>, sessionId = "s") =>
|
||||
tracker.sending({ sessionId, update: update as any });
|
||||
|
||||
it("is the last tool call, compaction or message that the client holds, without subagent output", () => {
|
||||
const tracker = new LastReportedEntity();
|
||||
expect(tracker.after("s")).toBeUndefined();
|
||||
send(tracker, { sessionUpdate: "agent_message_chunk", messageId: "m1" });
|
||||
send(tracker, { sessionUpdate: "agent_message_chunk" }); // no messageId to anchor to
|
||||
expect(tracker.after("s")).toEqual({
|
||||
type: "agent_message",
|
||||
messageId: "m1",
|
||||
position: "after",
|
||||
});
|
||||
send(tracker, { sessionUpdate: "tool_call", toolCallId: "t1" });
|
||||
send(tracker, { sessionUpdate: "tool_call_update", toolCallId: "t2" });
|
||||
send(tracker, {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "t3",
|
||||
_meta: { claudeCode: { parentToolUseId: "toolu_agent" } },
|
||||
});
|
||||
expect(tracker.after("s")).toEqual({ type: "tool_call", toolCallId: "t1", position: "after" });
|
||||
send(tracker, { sessionUpdate: "compaction_update", compactionId: "c1" });
|
||||
expect(tracker.after("s")).toEqual({
|
||||
type: "compaction",
|
||||
compactionId: "c1",
|
||||
position: "after",
|
||||
});
|
||||
});
|
||||
|
||||
it("is forgotten with the session and its children", () => {
|
||||
const tracker = new LastReportedEntity();
|
||||
send(tracker, { sessionUpdate: "tool_call", toolCallId: "t1" });
|
||||
send(tracker, { sessionUpdate: "tool_call", toolCallId: "t2" }, "s:replay-subagent:x");
|
||||
tracker.forget("s");
|
||||
expect(tracker.after("s")).toBeUndefined();
|
||||
expect(tracker.after("s:replay-subagent:x")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("the entity before an announced cursor", () => {
|
||||
const entity = (messageId: string) => ({ type: "agent_message" as const, messageId });
|
||||
|
||||
it("is the last entity of a rewound session, and the records from the cut on are dropped", () => {
|
||||
const tracker = new LastReportedEntity();
|
||||
tracker.recordCursor("s", "before:u2", entity("m1"));
|
||||
tracker.recordCursor("s", "before:u3", entity("m2"));
|
||||
tracker.recordCursor("s", "before:u4", entity("m3"));
|
||||
tracker.sending({
|
||||
sessionId: "s",
|
||||
update: { sessionUpdate: "tool_call", toolCallId: "t" },
|
||||
});
|
||||
|
||||
tracker.rewind("s", "before:u3");
|
||||
expect(tracker.after("s")).toEqual({ ...entity("m2"), position: "after" });
|
||||
// `before:u3` and `before:u4` are gone: no entity to anchor to.
|
||||
tracker.rewind("s", "before:u4");
|
||||
expect(tracker.after("s")).toBeUndefined();
|
||||
tracker.rewind("s", "before:u2");
|
||||
expect(tracker.after("s")).toEqual({ ...entity("m1"), position: "after" });
|
||||
});
|
||||
|
||||
it("is none for a cursor recorded without one, and for an unknown cursor", () => {
|
||||
const tracker = new LastReportedEntity();
|
||||
tracker.recordCursor("s", "before:u2", undefined);
|
||||
tracker.sending({ sessionId: "s", update: { sessionUpdate: "tool_call", toolCallId: "t" } });
|
||||
tracker.rewind("s", "before:u2");
|
||||
expect(tracker.after("s")).toBeUndefined();
|
||||
tracker.sending({ sessionId: "s", update: { sessionUpdate: "tool_call", toolCallId: "t" } });
|
||||
tracker.rewind("s", "before:unknown");
|
||||
expect(tracker.after("s")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("is forgotten with the session", () => {
|
||||
const tracker = new LastReportedEntity();
|
||||
tracker.recordCursor("s", "before:u2", entity("m1"));
|
||||
tracker.forget("s");
|
||||
tracker.rewind("s", "before:u2");
|
||||
expect(tracker.after("s")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
309
src/tests/v1/session-rewind-integration.test.ts
Normal file
309
src/tests/v1/session-rewind-integration.test.ts
Normal file
@@ -0,0 +1,309 @@
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import { randomUUID } from "crypto";
|
||||
import {
|
||||
appendFile,
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
realpath,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "fs/promises";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import { AIR_SESSION_REWIND_CAPABILITY } from "../../air-extension.js";
|
||||
|
||||
type Update = { sessionId: string; update: Record<string, any> };
|
||||
|
||||
/** A client that records every notification, and the agent over it. */
|
||||
async function startAgent() {
|
||||
const updates: Update[] = [];
|
||||
const client = {
|
||||
sessionUpdate: async (notification: Update) => {
|
||||
updates.push(notification);
|
||||
},
|
||||
requestPermission: async () => ({ outcome: { outcome: "cancelled" } }),
|
||||
readTextFile: async () => ({ content: "" }),
|
||||
writeTextFile: async () => ({}),
|
||||
} as unknown as AcpClient;
|
||||
const agent = new ClaudeAcpAgent(client);
|
||||
await agent.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
session: { cursors: {} },
|
||||
_meta: {
|
||||
jetbrains: { air: { version: 1, capabilities: [AIR_SESSION_REWIND_CAPABILITY] } },
|
||||
},
|
||||
},
|
||||
} as any);
|
||||
return { agent, updates };
|
||||
}
|
||||
type Started = Awaited<ReturnType<typeof startAgent>>;
|
||||
|
||||
const textOf = (updates: Update[], kind: string) =>
|
||||
updates
|
||||
.filter((n) => n.update.sessionUpdate === kind && n.update.content?.type === "text")
|
||||
.map((n) => n.update.content.text as string)
|
||||
.join("");
|
||||
|
||||
const cursorsOf = (updates: Update[]) =>
|
||||
updates.filter((n) => n.update.sessionUpdate === "cursor_update").map((n) => n.update);
|
||||
|
||||
/** Finds `<sessionId>.jsonl` under the user's real Claude config (auth lives there). */
|
||||
async function findTranscript(sessionId: string): Promise<string> {
|
||||
const projects = path.join(
|
||||
process.env.CLAUDE_CONFIG_DIR ?? path.join(os.homedir(), ".claude"),
|
||||
"projects",
|
||||
);
|
||||
for (const dir of await readdir(projects)) {
|
||||
const candidate = path.join(projects, dir, `${sessionId}.jsonl`);
|
||||
try {
|
||||
await readFile(candidate, "utf8");
|
||||
return candidate;
|
||||
} catch {
|
||||
// not in this project directory
|
||||
}
|
||||
}
|
||||
throw new Error(`No transcript for ${sessionId}`);
|
||||
}
|
||||
|
||||
/** Findings of the hook scenario go to a file when REWIND_IT_NOTES names one: vitest swallows console output here. */
|
||||
const note = async (...parts: unknown[]) => {
|
||||
if (process.env.REWIND_IT_NOTES) {
|
||||
await appendFile(process.env.REWIND_IT_NOTES, parts.map(String).join(" ") + "\n");
|
||||
}
|
||||
};
|
||||
|
||||
const rewindJson = async (sessionId: string) => {
|
||||
const transcript = await findTranscript(sessionId);
|
||||
try {
|
||||
return JSON.parse(
|
||||
await readFile(path.join(path.dirname(transcript), sessionId, "rewind.json"), "utf8"),
|
||||
);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("session rewind against the real CLI", () => {
|
||||
const agents: Started["agent"][] = [];
|
||||
const dirs: string[] = [];
|
||||
const transcripts: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
for (const agent of agents.splice(0)) await agent.dispose();
|
||||
for (const file of transcripts.splice(0)) {
|
||||
await rm(file, { force: true });
|
||||
await rm(file.replace(/\.jsonl$/, ""), { recursive: true, force: true });
|
||||
}
|
||||
for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function workDir(settings?: object) {
|
||||
const cwd = await realpath(await mkdtemp(path.join(os.tmpdir(), "rewind-it-")));
|
||||
dirs.push(cwd);
|
||||
if (settings) {
|
||||
await mkdir(path.join(cwd, ".claude"));
|
||||
await writeFile(path.join(cwd, ".claude", "settings.local.json"), JSON.stringify(settings));
|
||||
}
|
||||
return cwd;
|
||||
}
|
||||
|
||||
async function begin(cwd: string) {
|
||||
const started = await startAgent();
|
||||
agents.push(started.agent);
|
||||
const { sessionId } = await started.agent.newSession({ cwd, mcpServers: [] });
|
||||
await started.agent.setSessionConfigOption({ sessionId, configId: "model", value: "haiku" });
|
||||
return { ...started, sessionId, cwd };
|
||||
}
|
||||
|
||||
/** Prompts, and returns the reply and the cursor that the prompt got (if any). */
|
||||
async function ask({ agent, updates, sessionId }: Started & { sessionId: string }, text: string) {
|
||||
const mark = updates.length;
|
||||
await agent.prompt({ sessionId, prompt: [{ type: "text", text }] });
|
||||
const mine = updates.slice(mark);
|
||||
const cursors = cursorsOf(mine);
|
||||
return {
|
||||
reply: textOf(mine, "agent_message_chunk"),
|
||||
cursor: cursors.at(-1) as Record<string, any> | undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const say = (word: string) => `Remember the word ${word}. Reply with exactly: ${word}`;
|
||||
const recall = "What were my previous messages? List them all, quoting the words.";
|
||||
|
||||
/** Three turns; the cursors of turns B and C. */
|
||||
async function threeTurns(cwd: string) {
|
||||
const s = await begin(cwd);
|
||||
transcripts.push("");
|
||||
const a = await ask(s, say("ZEBRA"));
|
||||
const b = await ask(s, say("MANGO"));
|
||||
const c = await ask(s, say("COBALT"));
|
||||
transcripts[transcripts.length - 1] = await findTranscript(s.sessionId);
|
||||
return { s, a, b, c };
|
||||
}
|
||||
|
||||
const rewind = (s: { agent: ClaudeAcpAgent; sessionId: string }, cursorId: string) =>
|
||||
s.agent.rewindSession({ sessionId: s.sessionId, cursorId });
|
||||
|
||||
/** The text of the user messages replayed by `session/load` in a fresh agent. */
|
||||
async function reload(sessionId: string, cwd: string) {
|
||||
const fresh = await startAgent();
|
||||
agents.push(fresh.agent);
|
||||
await fresh.agent.loadSession({ sessionId, cwd, mcpServers: [] });
|
||||
return { ...fresh, sessionId, replayed: textOf(fresh.updates, "user_message_chunk") };
|
||||
}
|
||||
|
||||
it("1: rewinds the last turn; the first prompt has no cursor", async () => {
|
||||
const { s, a, b, c } = await threeTurns(await workDir());
|
||||
expect(a.cursor).toBeUndefined();
|
||||
expect(b.cursor?.cursorId).toMatch(/^before:/);
|
||||
expect(c.cursor?.capabilities).toHaveProperty("rewind");
|
||||
|
||||
expect(await rewind(s, c.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
expect(await rewindJson(s.sessionId)).toBeDefined();
|
||||
|
||||
const { reply } = await ask(s, recall);
|
||||
expect(reply).toContain("ZEBRA");
|
||||
expect(reply).toContain("MANGO");
|
||||
expect(reply).not.toContain("COBALT");
|
||||
}, 300000);
|
||||
|
||||
it("2: rewinds an earlier turn", async () => {
|
||||
const { s, b } = await threeTurns(await workDir());
|
||||
expect(await rewind(s, b.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
|
||||
const { reply } = await ask(s, recall);
|
||||
expect(reply).toContain("ZEBRA");
|
||||
expect(reply).not.toContain("MANGO");
|
||||
expect(reply).not.toContain("COBALT");
|
||||
}, 300000);
|
||||
|
||||
it("3a: two rewinds in a row without a prompt", async () => {
|
||||
const { s, b, c } = await threeTurns(await workDir());
|
||||
expect(await rewind(s, c.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
expect(await rewind(s, b.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
|
||||
const { reply } = await ask(s, recall);
|
||||
expect(reply).toContain("ZEBRA");
|
||||
expect(reply).not.toContain("MANGO");
|
||||
expect(reply).not.toContain("COBALT");
|
||||
}, 300000);
|
||||
|
||||
it("3b: two rewinds with a prompt in between", async () => {
|
||||
const { s, b, c } = await threeTurns(await workDir());
|
||||
expect(await rewind(s, c.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
const d = await ask(s, say("PAPAYA"));
|
||||
expect(await rewind(s, b.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
|
||||
const { reply } = await ask(s, recall);
|
||||
expect(reply).toContain("ZEBRA");
|
||||
expect(reply).not.toContain("MANGO");
|
||||
expect(reply).not.toContain("COBALT");
|
||||
expect(reply).not.toContain("PAPAYA");
|
||||
expect(d.cursor).toBeDefined();
|
||||
}, 300000);
|
||||
|
||||
describe("4: persistence", () => {
|
||||
it.each([
|
||||
["with a new prompt after the rewind", true],
|
||||
["with no prompt after the rewind", false],
|
||||
])(
|
||||
"%s",
|
||||
async (_, prompted) => {
|
||||
const cwd = await workDir();
|
||||
const { s, c } = await threeTurns(cwd);
|
||||
expect(await rewind(s, c.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
if (prompted) await ask(s, say("PAPAYA"));
|
||||
await s.agent.closeSession({ sessionId: s.sessionId });
|
||||
|
||||
const loaded = await reload(s.sessionId, cwd);
|
||||
expect(loaded.replayed).toContain("ZEBRA");
|
||||
expect(loaded.replayed).toContain("MANGO");
|
||||
expect(loaded.replayed).not.toContain("COBALT");
|
||||
if (prompted) expect(loaded.replayed).toContain("PAPAYA");
|
||||
|
||||
const { reply } = await ask(loaded, recall);
|
||||
expect(reply).toContain("ZEBRA");
|
||||
expect(reply).toContain("MANGO");
|
||||
expect(reply).not.toContain("COBALT");
|
||||
},
|
||||
300000,
|
||||
);
|
||||
});
|
||||
|
||||
it("5: unknown cursor is -32602, a running prompt is busy", async () => {
|
||||
const { s, c } = await threeTurns(await workDir());
|
||||
await expect(rewind(s, `before:${randomUUID()}`)).rejects.toMatchObject({ code: -32602 });
|
||||
|
||||
const mark = s.updates.length;
|
||||
const running = s.agent.prompt({
|
||||
sessionId: s.sessionId,
|
||||
prompt: [
|
||||
{ type: "text", text: "Write the numbers from 1 to 600, one per line, nothing else." },
|
||||
],
|
||||
});
|
||||
while (!textOf(s.updates.slice(mark), "agent_message_chunk")) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
expect(await rewind(s, c.cursor!.cursorId)).toEqual({ rewound: false, reason: "busy" });
|
||||
await running;
|
||||
}, 300000);
|
||||
|
||||
it("6: SessionStart hook, rewind with no prompt, then reload", async () => {
|
||||
const hook = {
|
||||
hooks: {
|
||||
SessionStart: [
|
||||
{
|
||||
hooks: [
|
||||
{
|
||||
type: "command",
|
||||
command: `echo '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"The secret code word is KIWI."}}'`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const cwd = await workDir(hook);
|
||||
const { s, c } = await threeTurns(cwd);
|
||||
expect(await rewind(s, c.cursor!.cursorId)).toEqual({ rewound: true });
|
||||
await s.agent.closeSession({ sessionId: s.sessionId });
|
||||
|
||||
const lines = (await readFile(transcripts.at(-1)!, "utf8")).trimEnd().split("\n");
|
||||
await note(
|
||||
"TRANSCRIPT TAIL (hook, after rewind):\n" +
|
||||
lines
|
||||
.slice(-8)
|
||||
.map((line) => line.slice(0, 600))
|
||||
.join("\n"),
|
||||
);
|
||||
await note(
|
||||
"PARENTLESS NON-USER LINES:",
|
||||
lines
|
||||
.map((line) => JSON.parse(line))
|
||||
.filter((l) => l.parentUuid == null && l.type !== "user" && l.type !== "last-prompt")
|
||||
.map((l) => `${l.type}/${l.subtype ?? l.attachment?.type ?? ""}`),
|
||||
);
|
||||
await note(
|
||||
"LINE TYPES:",
|
||||
lines
|
||||
.map((line, index) => {
|
||||
const l = JSON.parse(line);
|
||||
return `${index}:${l.type}/${l.subtype ?? l.attachment?.type ?? l.operation ?? ""}${l.parentUuid == null ? "(root)" : ""}`;
|
||||
})
|
||||
.join(" "),
|
||||
);
|
||||
await note("rewind.json:", JSON.stringify(await rewindJson(s.sessionId)));
|
||||
|
||||
const loaded = await reload(s.sessionId, cwd);
|
||||
expect(loaded.replayed).toContain("MANGO");
|
||||
expect(loaded.replayed).not.toContain("COBALT");
|
||||
const { reply } = await ask(loaded, recall);
|
||||
expect(reply).toContain("MANGO");
|
||||
expect(reply).not.toContain("COBALT");
|
||||
}, 300000);
|
||||
});
|
||||
961
src/tests/v1/session-rewind.test.ts
Normal file
961
src/tests/v1/session-rewind.test.ts
Normal file
@@ -0,0 +1,961 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
client as acpClient,
|
||||
type ClientCapabilities,
|
||||
type InitializeResponse,
|
||||
} from "@agentclientprotocol/sdk/unstable";
|
||||
import type { Options } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import { ClaudeAcpAgent, v1AgentApp } from "../../v1/acp-agent.js";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import { AIR_SESSION_REWIND_CAPABILITY } from "../../air-extension.js";
|
||||
import {
|
||||
initializeClient,
|
||||
makeMockQuery,
|
||||
transcriptAssistant,
|
||||
transcriptCompactBoundary,
|
||||
transcriptCompactSummary,
|
||||
transcriptUser,
|
||||
writeTranscript,
|
||||
} from "../helpers.js";
|
||||
import { writeRewindPoint } from "../../session-rewind.js";
|
||||
import { successfulResultMessage, userEcho } from "./session-doubles.js";
|
||||
|
||||
const sdk = vi.hoisted(() => ({
|
||||
query: vi.fn(),
|
||||
getSessionMessages: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
vi.mock("@anthropic-ai/claude-agent-sdk", async () => ({
|
||||
...(await vi.importActual<typeof import("@anthropic-ai/claude-agent-sdk")>(
|
||||
"@anthropic-ai/claude-agent-sdk",
|
||||
)),
|
||||
...sdk,
|
||||
resolveSettings: async () => ({ effective: {}, sources: [], provenance: {} }),
|
||||
filterEscalatingDefaultMode: (result: any) => result.effective,
|
||||
}));
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((done) => (resolve = done));
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
const MODELS = ["sonnet", "opus"].map((value) => ({
|
||||
value,
|
||||
displayName: value,
|
||||
description: "",
|
||||
resolvedModel: `claude-${value}-4-6`,
|
||||
supportsAutoMode: true,
|
||||
supportsFastMode: true,
|
||||
supportsEffort: true,
|
||||
supportedEffortLevels: ["low", "medium", "high", "xhigh"] as const,
|
||||
}));
|
||||
|
||||
const air = (...capabilities: string[]): ClientCapabilities => ({
|
||||
session: { cursors: {} },
|
||||
_meta: { jetbrains: { air: { version: 1, capabilities } } },
|
||||
});
|
||||
const REWIND_CLIENT = air(AIR_SESSION_REWIND_CAPABILITY);
|
||||
|
||||
function user(uuid: string, content: unknown) {
|
||||
return {
|
||||
type: "user",
|
||||
uuid,
|
||||
session_id: "s",
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: { role: "user", content },
|
||||
};
|
||||
}
|
||||
function assistant(uuid: string) {
|
||||
return {
|
||||
type: "assistant",
|
||||
uuid,
|
||||
session_id: "s",
|
||||
parent_tool_use_id: null,
|
||||
parent_agent_id: null,
|
||||
message: {
|
||||
id: `msg_${uuid}`,
|
||||
role: "assistant",
|
||||
model: "claude-sonnet-4-6",
|
||||
content: [{ type: "text", text: uuid }],
|
||||
},
|
||||
};
|
||||
}
|
||||
/** Two turns: the cursors are before `u2` and `u3`. */
|
||||
const HISTORY = [
|
||||
user("u1", "one"),
|
||||
assistant("a1"),
|
||||
user("u2", "two"),
|
||||
assistant("a2"),
|
||||
user("u3", "three"),
|
||||
];
|
||||
|
||||
describe("_session/rewind on v1", { timeout: 10_000 }, () => {
|
||||
let agent: ClaudeAcpAgent;
|
||||
let dir: string;
|
||||
let updates: any[];
|
||||
let queries: ReturnType<typeof createQuery>[];
|
||||
/** Fails the initialization of the nth query that is created from now on. */
|
||||
let failInitialization: Error[];
|
||||
let initializationGate: Promise<void> | undefined;
|
||||
let turnGate: Promise<void> | undefined;
|
||||
/** Holds every `session/update` to the client while it is set. */
|
||||
let updateGate: Promise<void> | undefined;
|
||||
/** Resolved when a `session/update` starts to wait for `updateGate`. */
|
||||
let updateReached: ReturnType<typeof deferred>;
|
||||
|
||||
function createQuery(request: { options: Options; prompt: AsyncIterable<any> }) {
|
||||
const state = { model: request.options.model ?? "sonnet" };
|
||||
const prompts: string[] = [];
|
||||
const failure = failInitialization.shift();
|
||||
const query = {
|
||||
...makeMockQuery(),
|
||||
request,
|
||||
state,
|
||||
prompts,
|
||||
initializationResult: async () => {
|
||||
await initializationGate;
|
||||
if (failure) throw failure;
|
||||
return { models: MODELS };
|
||||
},
|
||||
setModel: vi.fn(async (value: string) => {
|
||||
state.model = value;
|
||||
}),
|
||||
close: vi.fn(),
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
for await (const message of request.prompt) {
|
||||
prompts.push(message.message.content);
|
||||
yield userEcho(message);
|
||||
await turnGate;
|
||||
yield successfulResultMessage();
|
||||
yield { type: "system", subtype: "status", status: "idle" };
|
||||
}
|
||||
},
|
||||
};
|
||||
const iterator = query[Symbol.asyncIterator]();
|
||||
return Object.assign(query, { next: iterator.next.bind(iterator) });
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "v1-session-rewind-"));
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
|
||||
updates = [];
|
||||
queries = [];
|
||||
failInitialization = [];
|
||||
initializationGate = turnGate = updateGate = undefined;
|
||||
updateReached = deferred();
|
||||
sdk.query.mockImplementation((request) => {
|
||||
const query = createQuery(request);
|
||||
queries.push(query);
|
||||
return query;
|
||||
});
|
||||
sdk.getSessionMessages.mockResolvedValue(HISTORY);
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () =>
|
||||
Response.json({ data: MODELS.map((model) => ({ id: model.resolvedModel })) }),
|
||||
),
|
||||
);
|
||||
agent = new ClaudeAcpAgent(
|
||||
{
|
||||
sessionUpdate: async (update: any) => {
|
||||
if (updateGate) updateReached.resolve();
|
||||
await updateGate;
|
||||
updates.push(update);
|
||||
},
|
||||
} as AcpClient,
|
||||
{ log() {}, error() {}, warn() {} },
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await agent.dispose();
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
vi.clearAllMocks();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function start(capabilities: ClientCapabilities = REWIND_CLIENT) {
|
||||
await initializeClient(agent, capabilities);
|
||||
await agent.unstable_setProvider({
|
||||
providerId: "main",
|
||||
apiType: "anthropic",
|
||||
baseUrl: "https://provider.example",
|
||||
});
|
||||
const { sessionId } = await agent.newSession({ cwd: dir, mcpServers: [] });
|
||||
// The transcript that the rewind point is recorded beside.
|
||||
await writeTranscript(path.join(dir, "projects", "project"), sessionId, [
|
||||
transcriptUser("u1", "one"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
]);
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
const rewind = (sessionId: string, cursorId = "before:u3") =>
|
||||
agent.rewindSession({ sessionId, cursorId });
|
||||
const prompt = (sessionId: string, text = "hi") =>
|
||||
agent.prompt({ sessionId, prompt: [{ type: "text", text }] });
|
||||
|
||||
describe("capability", () => {
|
||||
it.each([
|
||||
["a client that declares it", REWIND_CLIENT, true],
|
||||
["an AIR client that does not", air(), false],
|
||||
["a client that is not AIR", { session: { cursors: {} } }, false],
|
||||
])("is advertised to %s: %s", async (_, capabilities, advertised) => {
|
||||
const response = (await agent.initialize({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: capabilities,
|
||||
})) as InitializeResponse;
|
||||
const listed = (response._meta as any)?.jetbrains?.air?.capabilities ?? [];
|
||||
expect(listed.includes(AIR_SESSION_REWIND_CAPABILITY)).toBe(advertised);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a client that declares sessionRewind", REWIND_CLIENT, { fork: {}, rewind: {} }],
|
||||
["an AIR client that does not", air(), { fork: {} }],
|
||||
["a client that is not AIR", { session: { cursors: {} } }, { fork: {} }],
|
||||
])("puts rewind on the cursors of %s", async (_, capabilities, expected) => {
|
||||
await start(capabilities);
|
||||
await (agent as any).replaySessionHistory("s");
|
||||
const cursors = updates
|
||||
.map((notification) => notification.update)
|
||||
.filter((update) => update.sessionUpdate === "cursor_update");
|
||||
expect(cursors.map((cursor) => cursor.cursorId)).toEqual(["before:u2", "before:u3"]);
|
||||
for (const cursor of cursors) expect(cursor.capabilities).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("capability on a cursor that cannot be rewound to", () => {
|
||||
const cursorsOf = () =>
|
||||
updates
|
||||
.map((notification) => notification.update)
|
||||
.filter((update) => update.sessionUpdate === "cursor_update")
|
||||
.map((update) => [update.cursorId, Object.keys(update.capabilities).sort()]);
|
||||
|
||||
it("is fork alone for a cursor before the newest compaction, in a replay", async () => {
|
||||
const sessionId = await start();
|
||||
await writeTranscript(path.join(dir, "projects", "project"), sessionId, [
|
||||
transcriptUser("u1", "one"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptUser("ux", "earlier"),
|
||||
transcriptAssistant("ax", "earlier"),
|
||||
transcriptCompactBoundary("b1", "ax"),
|
||||
transcriptCompactSummary("s1"),
|
||||
transcriptUser("u2", "two"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
]);
|
||||
const current = [user("s1", "summary"), user("u2", "two"), assistant("a2")];
|
||||
const visible = [user("u1", "one"), assistant("a1"), user("ux", "earlier")].concat(
|
||||
[assistant("ax")],
|
||||
current,
|
||||
);
|
||||
(current[0] as any).isCompactSummary = true;
|
||||
(visible[4] as any).isCompactSummary = true;
|
||||
sdk.getSessionMessages.mockImplementation(async (_id: string, options?: any) =>
|
||||
options?.sessionStore ? visible : current,
|
||||
);
|
||||
updates.length = 0;
|
||||
|
||||
await (agent as any).replaySessionHistory(sessionId);
|
||||
|
||||
expect(cursorsOf()).toEqual([
|
||||
["before:ux", ["fork"]],
|
||||
["before:u2", ["fork", "rewind"]],
|
||||
]);
|
||||
});
|
||||
|
||||
it("is fork alone in a session whose context was cleared, in a replay and live", async () => {
|
||||
const sessionId = await start();
|
||||
agent.sessions[sessionId]!.claudeSessionId = "another-session";
|
||||
updates.length = 0;
|
||||
await (agent as any).replaySessionHistory(sessionId);
|
||||
await prompt(sessionId, "first");
|
||||
await prompt(sessionId, "second");
|
||||
|
||||
// Two from the replay, two live prompts.
|
||||
expect(cursorsOf().map(([, capabilities]) => capabilities)).toEqual(Array(4).fill(["fork"]));
|
||||
});
|
||||
});
|
||||
|
||||
describe("rewinding", () => {
|
||||
it("recreates the same session at the cut, with the user's choices", async () => {
|
||||
const sessionId = await start();
|
||||
await agent.setSessionConfigOption({ sessionId, configId: "model", value: "opus" });
|
||||
const before = queries[0]!;
|
||||
|
||||
expect(await rewind(sessionId)).toEqual({ rewound: true });
|
||||
|
||||
expect(before.close).toHaveBeenCalled();
|
||||
const resumed = queries.at(-1)!;
|
||||
expect(resumed.request.options).toMatchObject({
|
||||
resume: sessionId,
|
||||
resumeSessionAt: "a2",
|
||||
resumeDropsTurn: "u3",
|
||||
});
|
||||
expect(resumed.state.model).toBe("opus");
|
||||
expect(agent.sessions[sessionId]!.query).toBe(resumed);
|
||||
// The reader runs: a prompt reaches the resumed query and ends its turn.
|
||||
expect(await prompt(sessionId, "edited")).toMatchObject({ stopReason: "end_turn" });
|
||||
expect(resumed.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("gives the edited message a cursor after the entity that the client keeps, and rewinds again", async () => {
|
||||
const sessionId = await start();
|
||||
await (agent as any).replaySessionHistory(sessionId);
|
||||
await rewind(sessionId);
|
||||
updates.length = 0;
|
||||
|
||||
await prompt(sessionId, "edited");
|
||||
|
||||
const cursors = updates
|
||||
.map((notification) => notification.update)
|
||||
.filter((update) => update.sessionUpdate === "cursor_update");
|
||||
expect(cursors).toEqual([
|
||||
{
|
||||
sessionUpdate: "cursor_update",
|
||||
cursorId: expect.stringMatching(/^before:/),
|
||||
capabilities: { fork: {}, rewind: {} },
|
||||
anchor: { type: "agent_message", messageId: "msg_a2", position: "after" },
|
||||
},
|
||||
]);
|
||||
|
||||
// The stored history now holds the edited message after `a2`.
|
||||
const edited = cursors[0].cursorId.slice("before:".length);
|
||||
sdk.getSessionMessages.mockResolvedValue([
|
||||
...HISTORY.slice(0, 4),
|
||||
user(edited, "edited"),
|
||||
assistant("a5"),
|
||||
]);
|
||||
expect(await rewind(sessionId, cursors[0].cursorId)).toEqual({ rewound: true });
|
||||
expect(queries.at(-1)!.request.options).toMatchObject({
|
||||
resumeSessionAt: "a2",
|
||||
resumeDropsTurn: edited,
|
||||
});
|
||||
});
|
||||
|
||||
describe("the anchor of the edited message", () => {
|
||||
const cursorsAfter = (from: number) =>
|
||||
updates
|
||||
.slice(from)
|
||||
.map((notification) => notification.update)
|
||||
.filter((update) => update.sessionUpdate === "cursor_update");
|
||||
/** Prompts `texts`, and returns the cursor of each. */
|
||||
async function promptAll(sessionId: string, texts: string[]) {
|
||||
const from = updates.length;
|
||||
for (const text of texts) await prompt(sessionId, text);
|
||||
return cursorsAfter(from);
|
||||
}
|
||||
/** The stored history once `cursors` were prompted after `a2`. */
|
||||
const storedAfter = (cursors: any[]) => {
|
||||
const stored = [
|
||||
...HISTORY.slice(0, 4),
|
||||
...cursors.map((cursor) => user(cursor.cursorId.slice("before:".length), "prompt")),
|
||||
];
|
||||
sdk.getSessionMessages.mockResolvedValue(stored);
|
||||
};
|
||||
const A2 = { type: "agent_message", messageId: "msg_a2", position: "after" };
|
||||
|
||||
beforeEach(() => sdk.getSessionMessages.mockResolvedValue(HISTORY.slice(0, 4)));
|
||||
|
||||
it("is that of the dropped message when the retained tail is a prompt that had no output", async () => {
|
||||
const sessionId = await start();
|
||||
await (agent as any).replaySessionHistory(sessionId);
|
||||
const [first, second] = await promptAll(sessionId, ["first", "second"]);
|
||||
expect(second.anchor).toEqual(A2);
|
||||
storedAfter([first, second]);
|
||||
|
||||
await rewind(sessionId, second.cursorId);
|
||||
const from = updates.length;
|
||||
await prompt(sessionId, "edited");
|
||||
|
||||
expect(cursorsAfter(from)[0].anchor).toEqual(A2);
|
||||
});
|
||||
|
||||
it("is the live compaction_update right after a compaction", async () => {
|
||||
const sessionId = await start();
|
||||
await (agent as any).replaySessionHistory(sessionId);
|
||||
const [first] = await promptAll(sessionId, ["first"]);
|
||||
await (agent as any).client.sessionUpdate({
|
||||
sessionId,
|
||||
update: { sessionUpdate: "compaction_update", compactionId: "live-compaction" },
|
||||
});
|
||||
const [second] = await promptAll(sessionId, ["second"]);
|
||||
expect(second.anchor).toEqual({
|
||||
type: "compaction",
|
||||
compactionId: "live-compaction",
|
||||
position: "after",
|
||||
});
|
||||
storedAfter([first, second]);
|
||||
|
||||
await rewind(sessionId, second.cursorId);
|
||||
const from = updates.length;
|
||||
await prompt(sessionId, "edited");
|
||||
|
||||
expect(cursorsAfter(from)[0].anchor).toEqual({
|
||||
type: "compaction",
|
||||
compactionId: "live-compaction",
|
||||
position: "after",
|
||||
});
|
||||
});
|
||||
|
||||
it("is the entity replayed before the message for a cursor that a replay announced", async () => {
|
||||
sdk.getSessionMessages.mockResolvedValue(HISTORY);
|
||||
const sessionId = await start();
|
||||
await (agent as any).replaySessionHistory(sessionId);
|
||||
|
||||
await rewind(sessionId, "before:u2");
|
||||
const from = updates.length;
|
||||
await prompt(sessionId, "edited");
|
||||
|
||||
expect(cursorsAfter(from)[0].anchor).toEqual({
|
||||
type: "agent_message",
|
||||
messageId: "msg_a1",
|
||||
position: "after",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("does not guard an earlier turn with resumeDropsTurn", async () => {
|
||||
const sessionId = await start();
|
||||
await rewind(sessionId, "before:u2");
|
||||
const options = queries.at(-1)!.request.options;
|
||||
expect(options.resumeSessionAt).toBe("a1");
|
||||
expect(options.resumeDropsTurn).toBeUndefined();
|
||||
});
|
||||
|
||||
it("holds a prompt that arrives meanwhile until the session is resumed", async () => {
|
||||
const sessionId = await start();
|
||||
const gate = deferred();
|
||||
initializationGate = gate.promise;
|
||||
|
||||
const rewinding = rewind(sessionId);
|
||||
const prompting = prompt(sessionId, "edited");
|
||||
await vi.waitFor(() => expect(queries).toHaveLength(2));
|
||||
expect(queries.flatMap((query) => query.prompts)).toEqual([]);
|
||||
|
||||
gate.resolve();
|
||||
expect(await rewinding).toEqual({ rewound: true });
|
||||
await prompting;
|
||||
expect(queries).toHaveLength(2);
|
||||
expect(queries[0]!.prompts).toEqual([]);
|
||||
expect(queries[1]!.request.options.resumeSessionAt).toBe("a2");
|
||||
expect(queries[1]!.prompts).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a prompt that is past its first check when the rewind starts", () => {
|
||||
it("waits for the rewind and runs on the resumed session", async () => {
|
||||
const sessionId = await start();
|
||||
// A pending task plan makes the prompt send an update before it queues.
|
||||
agent.sessions[sessionId]!.taskState.set("task-1", {
|
||||
subject: "Run tests",
|
||||
status: "in_progress",
|
||||
} as any);
|
||||
const planGate = deferred();
|
||||
updateGate = planGate.promise;
|
||||
const prompting = prompt(sessionId, "edited");
|
||||
await updateReached.promise;
|
||||
|
||||
const resumeGate = deferred();
|
||||
initializationGate = resumeGate.promise;
|
||||
const rewinding = rewind(sessionId);
|
||||
await vi.waitFor(() => expect(queries).toHaveLength(2));
|
||||
updateGate = undefined;
|
||||
planGate.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(queries.flatMap((query) => query.prompts)).toEqual([]);
|
||||
|
||||
resumeGate.resolve();
|
||||
expect(await rewinding).toEqual({ rewound: true });
|
||||
await prompting;
|
||||
expect(queries[0]!.prompts).toEqual([]);
|
||||
expect(queries[1]!.prompts).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a rewind that starts and finishes during an await of the prompt", () => {
|
||||
const planned = (sessionId: string) =>
|
||||
agent.sessions[sessionId]!.taskState.set("task-1", {
|
||||
subject: "Run tests",
|
||||
status: "in_progress",
|
||||
} as any);
|
||||
|
||||
/** Holds the prompt at `hold` until a whole rewind is done, then lets it go on. */
|
||||
async function rewindDuring(
|
||||
sessionId: string,
|
||||
hold: Promise<void>,
|
||||
release: () => void,
|
||||
expected: { rewound: boolean; reason?: string } = { rewound: true },
|
||||
meta?: Record<string, unknown>,
|
||||
text = "edited",
|
||||
) {
|
||||
const prompting = agent.prompt({
|
||||
sessionId,
|
||||
prompt: [{ type: "text", text }],
|
||||
...(meta ? { _meta: meta } : {}),
|
||||
});
|
||||
prompting.catch(() => {});
|
||||
await hold;
|
||||
expect(await rewind(sessionId)).toEqual(expected);
|
||||
release();
|
||||
return prompting;
|
||||
}
|
||||
|
||||
/** Holds the prompt after its first rewind check, while it publishes the prompt suggestions it clears. */
|
||||
function holdAtPromptSuggestions(sessionId: string) {
|
||||
agent.sessions[sessionId]!.promptSuggestions = { clear: () => ["stale"] } as any;
|
||||
const gate = deferred();
|
||||
const reached = deferred();
|
||||
vi.spyOn(agent as any, "publishPromptSuggestions").mockImplementation(async () => {
|
||||
reached.resolve();
|
||||
await gate.promise;
|
||||
});
|
||||
return { gate, reached };
|
||||
}
|
||||
|
||||
it("runs the prompt on the rewound session when the rewind ends before the rewind check", async () => {
|
||||
const sessionId = await start();
|
||||
planned(sessionId);
|
||||
const gate = deferred();
|
||||
const reached = deferred();
|
||||
vi.spyOn(agent as any, "publishTaskPlan").mockImplementation(async () => {
|
||||
reached.resolve();
|
||||
await gate.promise;
|
||||
});
|
||||
|
||||
await rewindDuring(sessionId, reached.promise, gate.resolve);
|
||||
expect(queries).toHaveLength(2);
|
||||
expect(queries[0]!.prompts).toEqual([]);
|
||||
expect(queries[1]!.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("runs a /remote-control command on the rewound session's query", async () => {
|
||||
const sessionId = await start();
|
||||
const gate = deferred();
|
||||
const reached = deferred();
|
||||
const enableRemoteControl = () => vi.fn(async () => ({ session_url: "https://claude.ai/s" }));
|
||||
sdk.query.mockImplementation((request) => {
|
||||
const query = Object.assign(createQuery(request), {
|
||||
enableRemoteControl: enableRemoteControl(),
|
||||
});
|
||||
queries.push(query);
|
||||
return query;
|
||||
});
|
||||
Object.assign(queries[0]!, {
|
||||
enableRemoteControl: enableRemoteControl(),
|
||||
supportedCommands: async () => {
|
||||
reached.resolve();
|
||||
await gate.promise;
|
||||
return [];
|
||||
},
|
||||
});
|
||||
|
||||
const prompting = rewindDuring(
|
||||
sessionId,
|
||||
reached.promise,
|
||||
gate.resolve,
|
||||
undefined,
|
||||
undefined,
|
||||
"/remote-control",
|
||||
);
|
||||
await prompting;
|
||||
expect(queries).toHaveLength(2);
|
||||
expect((queries[0] as any).enableRemoteControl).not.toHaveBeenCalled();
|
||||
expect((queries[1] as any).enableRemoteControl).toHaveBeenCalledWith(true, undefined);
|
||||
});
|
||||
|
||||
describe("when the rewind ends after the first rewind check", () => {
|
||||
it("takes the file change report, the title context and the idle compaction's disarm again from the new session", async () => {
|
||||
const sessionId = await start();
|
||||
const { gate, reached } = holdAtPromptSuggestions(sessionId);
|
||||
const turn = deferred();
|
||||
turnGate = turn.promise;
|
||||
const meta = { jetbrains: { air: { agentFileChangeReportRequest: { requestId: "r-1" } } } };
|
||||
|
||||
const reporter = {
|
||||
request: vi.fn(() => "report-1"),
|
||||
report: vi.fn(async () => undefined),
|
||||
finish: vi.fn(),
|
||||
};
|
||||
let onPrompt!: ReturnType<typeof vi.spyOn>;
|
||||
let disarm!: ReturnType<typeof vi.spyOn>;
|
||||
// The rewind is done when the prompt is released: the successor is in place.
|
||||
const prompting = rewindDuring(
|
||||
sessionId,
|
||||
reached.promise,
|
||||
() => {
|
||||
const successor = agent.sessions[sessionId]!;
|
||||
successor.fileChangeReporter = reporter as any;
|
||||
onPrompt = vi.spyOn(successor.titles, "onPrompt");
|
||||
disarm = vi.spyOn(successor.idleCompaction!, "disarm");
|
||||
gate.resolve();
|
||||
},
|
||||
{ rewound: true },
|
||||
meta,
|
||||
);
|
||||
|
||||
await vi.waitFor(() => expect(queries[1]!.prompts).toHaveLength(1));
|
||||
expect(reporter.request).toHaveBeenCalledWith(meta);
|
||||
expect(agent.sessions[sessionId]!.turnQueue![0]!.fileChangeReport).toBe("report-1");
|
||||
expect(onPrompt).toHaveBeenCalledWith([{ type: "text", text: "edited" }]);
|
||||
expect(disarm).toHaveBeenCalledWith("prompt");
|
||||
turn.resolve();
|
||||
await prompting;
|
||||
});
|
||||
|
||||
it("waits for a /remote-control command that the successor holds, which the old session did not", async () => {
|
||||
const sessionId = await start();
|
||||
const { gate, reached } = holdAtPromptSuggestions(sessionId);
|
||||
// A command prompt that the same rewind held starts on the new session.
|
||||
const command = deferred();
|
||||
const held = vi.spyOn(command.promise, "catch");
|
||||
|
||||
const prompting = rewindDuring(sessionId, reached.promise, () => {
|
||||
agent.sessions[sessionId]!.remoteControlCommand = command.promise;
|
||||
gate.resolve();
|
||||
});
|
||||
|
||||
await vi.waitFor(() => expect(held).toHaveBeenCalled());
|
||||
expect(queries.flatMap((query) => query.prompts)).toEqual([]);
|
||||
agent.sessions[sessionId]!.remoteControlCommand = undefined;
|
||||
command.resolve();
|
||||
await prompting;
|
||||
expect(queries[1]!.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("follows into the session that a refused cut's recovery leaves", async () => {
|
||||
const sessionId = await start();
|
||||
const { gate, reached } = holdAtPromptSuggestions(sessionId);
|
||||
failInitialization = [new Error("Resume rejected by --resume-drops-turn: queued message")];
|
||||
|
||||
await rewindDuring(sessionId, reached.promise, gate.resolve, {
|
||||
rewound: false,
|
||||
reason: "providerRefused",
|
||||
});
|
||||
expect(queries).toHaveLength(3);
|
||||
expect(queries.slice(0, 2).flatMap((query) => query.prompts)).toEqual([]);
|
||||
expect(queries[2]!.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("follows two rewinds that finish during one await to the current session", async () => {
|
||||
const sessionId = await start();
|
||||
const { gate, reached } = holdAtPromptSuggestions(sessionId);
|
||||
const prompting = agent.prompt({ sessionId, prompt: [{ type: "text", text: "edited" }] });
|
||||
prompting.catch(() => {});
|
||||
await reached.promise;
|
||||
expect(await rewind(sessionId)).toEqual({ rewound: true });
|
||||
const intermediate = agent.sessions[sessionId]!;
|
||||
expect(await rewind(sessionId, "before:u2")).toEqual({ rewound: true });
|
||||
expect(intermediate.queryClosed).toBe(true);
|
||||
gate.resolve();
|
||||
await prompting;
|
||||
expect(queries).toHaveLength(3);
|
||||
expect(queries.slice(0, 2).flatMap((query) => query.prompts)).toEqual([]);
|
||||
expect(queries[2]!.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("ends the prompt with the session-ended error when the session it follows into is closed", async () => {
|
||||
const sessionId = await start();
|
||||
const { gate, reached } = holdAtPromptSuggestions(sessionId);
|
||||
const prompting = agent.prompt({ sessionId, prompt: [{ type: "text", text: "edited" }] });
|
||||
prompting.catch(() => {});
|
||||
await reached.promise;
|
||||
(agent as any).rewoundSessions.set(agent.sessions[sessionId], { queryClosed: true });
|
||||
gate.resolve();
|
||||
await expect(prompting).rejects.toMatchObject({
|
||||
message: expect.stringContaining("session has ended"),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["deleted", (session: any, id: string) => delete agent.sessions[id]],
|
||||
["closed", (session: any) => (session.queryClosed = true)],
|
||||
])(
|
||||
"still ends the prompt with the session-ended error when the session is %s",
|
||||
async (_, end) => {
|
||||
const sessionId = await start();
|
||||
const session = agent.sessions[sessionId]!;
|
||||
const command = deferred();
|
||||
session.remoteControlCommand = command.promise;
|
||||
const held = vi.spyOn(command.promise, "catch");
|
||||
|
||||
const prompting = prompt(sessionId, "edited");
|
||||
prompting.catch(() => {});
|
||||
await vi.waitFor(() => expect(held).toHaveBeenCalled());
|
||||
end(session, sessionId);
|
||||
command.resolve();
|
||||
await expect(prompting).rejects.toMatchObject({
|
||||
message: expect.stringContaining("session has ended"),
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("refusals", () => {
|
||||
it("answers busy while a turn runs", async () => {
|
||||
const sessionId = await start();
|
||||
const gate = deferred();
|
||||
turnGate = gate.promise;
|
||||
const turn = prompt(sessionId);
|
||||
await vi.waitFor(() => expect(queries[0]!.prompts).toHaveLength(1));
|
||||
|
||||
expect(await rewind(sessionId)).toEqual({ rewound: false, reason: "busy" });
|
||||
|
||||
gate.resolve();
|
||||
await turn;
|
||||
expect(queries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"backgroundWork",
|
||||
(session: any) => session.liveBackgroundTasks.set("task", { isSubagent: true }),
|
||||
],
|
||||
["clearedContext", (session: any) => (session.claudeSessionId = "another-session")],
|
||||
])("answers %s without replacing the query", async (reason, arrange) => {
|
||||
const sessionId = await start();
|
||||
arrange(agent.sessions[sessionId]);
|
||||
expect(await rewind(sessionId)).toEqual({ rewound: false, reason });
|
||||
expect(queries).toHaveLength(1);
|
||||
expect(queries[0]!.close).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers busy while a /remote-control command is in flight", async () => {
|
||||
const sessionId = await start();
|
||||
const command = deferred();
|
||||
agent.sessions[sessionId]!.remoteControlCommand = command.promise;
|
||||
|
||||
expect(await rewind(sessionId)).toEqual({ rewound: false, reason: "busy" });
|
||||
|
||||
expect(queries).toHaveLength(1);
|
||||
expect(queries[0]!.close).not.toHaveBeenCalled();
|
||||
agent.sessions[sessionId]!.remoteControlCommand = undefined;
|
||||
});
|
||||
|
||||
it("fails with -32002 for a session that the agent does not hold", async () => {
|
||||
await start();
|
||||
await expect(rewind("unknown-session")).rejects.toMatchObject({ code: -32002 });
|
||||
});
|
||||
|
||||
it("fails with -32602 for a cursor the history does not hold", async () => {
|
||||
const sessionId = await start();
|
||||
await expect(rewind(sessionId, "before:u1")).rejects.toMatchObject({ code: -32602 });
|
||||
expect(queries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an AIR client that did not declare sessionRewind", air()],
|
||||
["a client that is not AIR", { session: { cursors: {} } }],
|
||||
])("answers method not found to %s", async (_, clientCapabilities) => {
|
||||
let created!: ClaudeAcpAgent;
|
||||
const connection = acpClient({ name: "rewind-test" }).connect(
|
||||
v1AgentApp({ log() {}, error() {} }, (made) => (created = made)),
|
||||
);
|
||||
try {
|
||||
await connection.agent.request("initialize", { protocolVersion: 1, clientCapabilities });
|
||||
await expect(
|
||||
connection.agent.request("_session/rewind", { sessionId: "s", cursorId: "before:u2" }),
|
||||
).rejects.toMatchObject({ code: -32601 });
|
||||
expect((created as any).sessionRewinds.size).toBe(0);
|
||||
} finally {
|
||||
connection.close();
|
||||
await created.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails with -32602 for a subagent's session", async () => {
|
||||
let created!: ClaudeAcpAgent;
|
||||
const connection = acpClient({ name: "rewind-test" }).connect(
|
||||
v1AgentApp({ log() {}, error() {} }, (made) => (created = made)),
|
||||
);
|
||||
try {
|
||||
await connection.agent.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: REWIND_CLIENT,
|
||||
});
|
||||
(created as any).announcedChildren.sending({
|
||||
sessionId: "root",
|
||||
update: { sessionUpdate: "subagent_update", sessionId: "child" },
|
||||
});
|
||||
await expect(
|
||||
connection.agent.request("_session/rewind", {
|
||||
sessionId: "child",
|
||||
cursorId: "before:u2",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: -32602 });
|
||||
} finally {
|
||||
connection.close();
|
||||
await created.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("recovery", () => {
|
||||
it("resumes the conversation as it was, with the choices, when the cut is refused", async () => {
|
||||
const sessionId = await start();
|
||||
await agent.setSessionConfigOption({ sessionId, configId: "model", value: "opus" });
|
||||
failInitialization = [
|
||||
new Error("Resume rejected by --resume-drops-turn: the range holds a queued message"),
|
||||
];
|
||||
|
||||
expect(await rewind(sessionId)).toEqual({ rewound: false, reason: "providerRefused" });
|
||||
|
||||
// One attempt at the cut, one recovery, and no retry.
|
||||
const attempts = queries.slice(1);
|
||||
expect(attempts).toHaveLength(2);
|
||||
expect(attempts[0]!.request.options.resumeSessionAt).toBe("a2");
|
||||
expect(attempts[1]!.request.options.resume).toBe(sessionId);
|
||||
expect(attempts[1]!.request.options.resumeSessionAt).toBeUndefined();
|
||||
expect(attempts[1]!.state.model).toBe("opus");
|
||||
expect(agent.sessions[sessionId]!.query).toBe(attempts[1]);
|
||||
expect(await prompt(sessionId)).toMatchObject({ stopReason: "end_turn" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("a recovery that fails too", () => {
|
||||
const refused = new Error(
|
||||
"Resume rejected by --resume-drops-turn: the range holds a queued message",
|
||||
);
|
||||
|
||||
it("ends the session and fails with an internal error", async () => {
|
||||
const sessionId = await start();
|
||||
failInitialization = [refused, new Error("cannot start")];
|
||||
|
||||
await expect(rewind(sessionId)).rejects.toMatchObject({
|
||||
code: -32603,
|
||||
});
|
||||
|
||||
expect(agent.sessions[sessionId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("fails with authRequired and keeps the session when the account needs a sign-in", async () => {
|
||||
const sessionId = await start();
|
||||
failInitialization = [refused, RequestError.authRequired()];
|
||||
|
||||
await expect(rewind(sessionId)).rejects.toMatchObject({
|
||||
code: RequestError.authRequired().code,
|
||||
});
|
||||
|
||||
expect(agent.sessions[sessionId]).toBeDefined();
|
||||
expect(agent.sessions[sessionId]!.needsSignOutRespawn).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("state that outlives the cut", () => {
|
||||
it.each([
|
||||
["a rewind", []],
|
||||
[
|
||||
"a refused cut and its recovery",
|
||||
[new Error("Resume rejected by --resume-drops-turn: the range holds a queued message")],
|
||||
],
|
||||
])("keeps the task list and the failure state through %s", async (_, failures) => {
|
||||
const sessionId = await start();
|
||||
const before = agent.sessions[sessionId]!;
|
||||
before.taskState.set("task-1", { id: "task-1" } as any);
|
||||
before.subagentChecklists.add("checklist-1");
|
||||
failInitialization = [...failures];
|
||||
|
||||
await rewind(sessionId);
|
||||
|
||||
const after = agent.sessions[sessionId]!;
|
||||
expect(after).not.toBe(before);
|
||||
expect(after.taskState).toBe(before.taskState);
|
||||
expect(after.subagentChecklists).toBe(before.subagentChecklists);
|
||||
expect(after.sessionFailureState).toBe(before.sessionFailureState);
|
||||
expect(after.forwardSubagentText).toBe(before.forwardSubagentText);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a pending rewind point", () => {
|
||||
/** The transcript that a rewind of `u3` leaves: `u3` stays as the dropped branch. */
|
||||
async function rewound(sessionId: string) {
|
||||
const directory = path.join(dir, "projects", "project");
|
||||
await writeTranscript(directory, sessionId, [
|
||||
transcriptUser("u1", "one"),
|
||||
transcriptAssistant("a1", "one"),
|
||||
transcriptUser("u2", "two"),
|
||||
transcriptAssistant("a2", "two"),
|
||||
transcriptUser("u3", "three"),
|
||||
]);
|
||||
await writeRewindPoint(sessionId, { resumeSessionAt: "a2", droppedPromptUuid: "u3" });
|
||||
return {
|
||||
transcript: path.join(directory, `${sessionId}.jsonl`),
|
||||
point: path.join(directory, sessionId, "rewind.json"),
|
||||
};
|
||||
}
|
||||
const cursors = () =>
|
||||
updates
|
||||
.map((notification) => notification.update)
|
||||
.filter((update) => update.sessionUpdate === "cursor_update")
|
||||
.map((update) => update.cursorId);
|
||||
|
||||
it("is left out of the replay, with its cursor", async () => {
|
||||
const sessionId = await start();
|
||||
await rewound(sessionId);
|
||||
updates.length = 0;
|
||||
|
||||
await (agent as any).replaySessionHistory(sessionId);
|
||||
|
||||
expect(cursors()).toEqual(["before:u2"]);
|
||||
const userMessages = updates
|
||||
.map((notification) => notification.update)
|
||||
.filter((update) => update.sessionUpdate === "user_message_chunk");
|
||||
expect(userMessages.map((update) => update.messageId)).toEqual(["u1", "u2"]);
|
||||
});
|
||||
|
||||
it("is where session/load resumes, and its replay stops", async () => {
|
||||
await start();
|
||||
const sessionId = randomUUID();
|
||||
await rewound(sessionId);
|
||||
updates.length = 0;
|
||||
|
||||
await agent.loadSession({ sessionId, cwd: dir, mcpServers: [] });
|
||||
|
||||
expect(queries.at(-1)!.request.options).toMatchObject({
|
||||
resume: sessionId,
|
||||
resumeSessionAt: "a2",
|
||||
});
|
||||
expect(queries.at(-1)!.request.options.resumeDropsTurn).toBeUndefined();
|
||||
expect(cursors()).toEqual(["before:u2"]);
|
||||
});
|
||||
|
||||
it("is where a restart of the query resumes", async () => {
|
||||
const sessionId = await start();
|
||||
await rewound(sessionId);
|
||||
|
||||
await agent.unstable_setProvider({
|
||||
providerId: "main",
|
||||
apiType: "anthropic",
|
||||
baseUrl: "https://other.example",
|
||||
});
|
||||
|
||||
expect(queries.at(-1)!.request.options).toMatchObject({
|
||||
resume: sessionId,
|
||||
resumeSessionAt: "a2",
|
||||
});
|
||||
});
|
||||
|
||||
it("is neither read nor changed by a session/options probe", async () => {
|
||||
await start();
|
||||
const sessionId = randomUUID();
|
||||
const files = await rewound(sessionId);
|
||||
const before = await Promise.all([readFile(files.transcript), readFile(files.point)]);
|
||||
|
||||
await agent.sessionOptions({ sessionId, cwd: dir });
|
||||
|
||||
const options = queries.at(-1)!.request.options;
|
||||
expect(options.resume).toBe(sessionId);
|
||||
expect(options.resumeSessionAt).toBeUndefined();
|
||||
expect(await Promise.all([readFile(files.transcript), readFile(files.point)])).toEqual(
|
||||
before,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@
|
||||
* `session_state_changed`.
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { McpOverAcp } from "../../mcp-servers.js";
|
||||
import { acpProtocolRouter } from "../../serve.js";
|
||||
import { validateV2Notification } from "../acp-scenarios/schema.js";
|
||||
import { writeRewindPoint } from "../../session-rewind.js";
|
||||
import { SettingsManager } from "../../settings.js";
|
||||
import type { AgentHandle } from "../../v2/agent.js";
|
||||
import { v2ElicitationRequest } from "../../v2/elicitation.js";
|
||||
@@ -3159,6 +3160,97 @@ describe("ACP v2 core", () => {
|
||||
expect(replayed.at(-1)).toEqual(cursorOf("u2"));
|
||||
});
|
||||
|
||||
describe("after a rewind", () => {
|
||||
/** `u2` was rewound: it stays in the transcript as the dropped branch. */
|
||||
async function rewound(sessionId: string) {
|
||||
const directory = path.join(tempDir, "claude", "projects", "project");
|
||||
await writeTranscript(directory, sessionId, [
|
||||
transcriptUser("u1", "Build it"),
|
||||
transcriptAssistant("a1", "Built."),
|
||||
transcriptUser("u2", "Test it"),
|
||||
]);
|
||||
await writeRewindPoint(sessionId, { resumeSessionAt: "a1", droppedPromptUuid: "u2" });
|
||||
return {
|
||||
transcript: path.join(directory, `${sessionId}.jsonl`),
|
||||
point: path.join(directory, sessionId, "rewind.json"),
|
||||
};
|
||||
}
|
||||
|
||||
it("resumes at the rewind point, and replays the history before it with its cursors only", async () => {
|
||||
const sessionId = randomUUID();
|
||||
await rewound(sessionId);
|
||||
vi.mocked(getSessionMessages).mockResolvedValueOnce(twoTurns);
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
await agent.request(v2.methods.agent.initialize, {
|
||||
protocolVersion: v2.PROTOCOL_VERSION,
|
||||
info: { name: "v2-test-client", version: "1.0.0" },
|
||||
capabilities: {},
|
||||
});
|
||||
await agent.request(v2.methods.agent.session.resume, {
|
||||
sessionId,
|
||||
cwd,
|
||||
replayFrom: { type: "start" },
|
||||
});
|
||||
});
|
||||
|
||||
expect(sdk.processes.at(-1)!.options).toMatchObject({
|
||||
resume: sessionId,
|
||||
resumeSessionAt: "a1",
|
||||
});
|
||||
const replayed = client.sessionUpdates.slice(
|
||||
0,
|
||||
client.sessionUpdates.findIndex((update) => update.sessionUpdate === "replay_complete"),
|
||||
);
|
||||
expect(
|
||||
replayed.flatMap((update) =>
|
||||
update.sessionUpdate === "user_message" ? [update.messageId] : [],
|
||||
),
|
||||
).toEqual(["u1"]);
|
||||
expect(replayed.map((update) => update.sessionUpdate)).not.toContain("cursor_update");
|
||||
});
|
||||
|
||||
it("rejects a fork at a cursor of the dropped turn", async () => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { response } = await openSession(agent);
|
||||
const { sessionId } = response;
|
||||
await rewound(sessionId);
|
||||
vi.mocked(getSessionMessages).mockResolvedValueOnce(twoTurns);
|
||||
await expect(
|
||||
agent.request(v2.methods.agent.session.fork, {
|
||||
sessionId,
|
||||
cwd,
|
||||
cursorId: "before:u2",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: -32602, data: { cursorId: "before:u2" } });
|
||||
expect(forkSession).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("is neither read nor changed by a session/options probe", async () => {
|
||||
const sessionId = randomUUID();
|
||||
const files = await rewound(sessionId);
|
||||
const before = await Promise.all([readFile(files.transcript), readFile(files.point)]);
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
await agent.request(v2.methods.agent.initialize, {
|
||||
protocolVersion: v2.PROTOCOL_VERSION,
|
||||
info: { name: "v2-test-client", version: "1.0.0" },
|
||||
capabilities: {},
|
||||
});
|
||||
await agent.request(v2.methods.agent.session.options, { sessionId, cwd });
|
||||
});
|
||||
|
||||
const probe = sdk.processes.at(-1)!;
|
||||
expect(probe.options).toMatchObject({ resume: sessionId, persistSession: false });
|
||||
expect(probe.options.resumeSessionAt).toBeUndefined();
|
||||
expect(await Promise.all([readFile(files.transcript), readFile(files.point)])).toEqual(
|
||||
before,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["forks the history before a cursor's message", "before:u2", { upToMessageId: "a1" }],
|
||||
["rejects a cursor that the history does not have", "before:u9", undefined],
|
||||
|
||||
@@ -143,6 +143,7 @@ import {
|
||||
airCustomInstructions,
|
||||
AIR_DIFF_PATCH_CAPABILITY,
|
||||
AIR_PLAN_FILE_CAPABILITY,
|
||||
AIR_SESSION_REWIND_CAPABILITY,
|
||||
AIR_GOAL_KEY,
|
||||
AIR_LOAD_REPLAY_END_CAPABILITY,
|
||||
AIR_LOAD_REPLAY_END_KEY,
|
||||
@@ -221,6 +222,25 @@ import {
|
||||
supportsMcpOAuth,
|
||||
} from "../mcp-oauth.js";
|
||||
import { forkSession } from "../fork-session.js";
|
||||
import {
|
||||
anchoredForkCursorUpdate,
|
||||
type CursorEntity,
|
||||
forkCursorUpdate,
|
||||
hasForkCursor,
|
||||
LastReportedEntity,
|
||||
promptGetsCursor,
|
||||
withRewindCapability,
|
||||
} from "../session-cursors.js";
|
||||
import {
|
||||
cutAtRewindPoint,
|
||||
loadRewindableHistory,
|
||||
parseSessionRewindRequest,
|
||||
prepareRewoundResume,
|
||||
rewindSession,
|
||||
SESSION_REWIND_METHOD,
|
||||
type SessionRewindRequest,
|
||||
type SessionRewindResponse,
|
||||
} from "../session-rewind.js";
|
||||
import {
|
||||
clientSystemPrompt,
|
||||
sessionSystemPrompt,
|
||||
@@ -654,6 +674,9 @@ type Turn = {
|
||||
* so the consumer can't promote them via the replay; it falls back to
|
||||
* promoting the queue head when the result arrives. */
|
||||
isLocalOnlyCommand: boolean;
|
||||
/** Whether the prompt gets a session cursor when Claude Code takes it in
|
||||
* (see {@link promptGetsCursor}). */
|
||||
getsCursor: boolean;
|
||||
/** Whitespace-normalized text this turn delivered as live `notice` updates
|
||||
* (SDK `informational` frames on the notice lane). A hook-blocked turn's
|
||||
* result repeats the block reason verbatim with zero output tokens; the
|
||||
@@ -1445,6 +1468,9 @@ export type Session = {
|
||||
* `initialize` now describes a credential that no longer works, so the next
|
||||
* turn recreates the query before it runs. */
|
||||
needsSignOutRespawn?: boolean;
|
||||
/** The Claude Code session the query runs, when it is not the ACP session
|
||||
* id: a cleared context continues in a new Claude session under the old id. */
|
||||
claudeSessionId?: string;
|
||||
/** The in-flight recreation, so turns that arrive together share one. */
|
||||
signOutRespawn?: Promise<void>;
|
||||
} & sessionIndex.SessionIndexFields;
|
||||
@@ -1653,6 +1679,12 @@ type SessionCreation = {
|
||||
* wrote one; this keeps the ACP session id alive with an empty history.
|
||||
* The SDK accepts a caller-chosen id as long as `resume` is not set. */
|
||||
reuseSessionId?: string;
|
||||
/** With `resume`: the conversation is resumed only up to this transcript
|
||||
* entry, and everything after it is dropped. `resumeDropsTurn` names the
|
||||
* turn that may legitimately be in the dropped range; Claude Code
|
||||
* refuses the resume when it finds anything else there. */
|
||||
resumeSessionAt?: string;
|
||||
resumeDropsTurn?: string;
|
||||
/** Concrete model id from the resumed transcript's last real assistant
|
||||
* message. Claude Code restores from this same record, so it lets us
|
||||
* report the live model without a slow getContextUsage control request. */
|
||||
@@ -1686,6 +1718,10 @@ export class ClaudeAcpAgent {
|
||||
private providerUpdate: Promise<void> | null = null;
|
||||
/** Per session: queue that runs mode/config changes and query restarts one at a time. */
|
||||
private readonly configurationChanges = new Map<string, Promise<void>>();
|
||||
/** The `_session/rewind` of each session that one is running for. It never rejects. */
|
||||
private readonly sessionRewinds = new Map<string, Promise<void>>();
|
||||
/** The session a finished rewind left in place of the one it closed, so a prompt that still holds the old one can follow it. */
|
||||
private readonly rewoundSessions = new WeakMap<Session, Session>();
|
||||
private readonly exitPlan: ExitPlanCoordinator<Session, Turn>;
|
||||
/** The connection's `authStatus` state and pushes, connection-scoped like
|
||||
* `authenticate`/`logout`. */
|
||||
@@ -1723,6 +1759,8 @@ export class ClaudeAcpAgent {
|
||||
* (see {@link endSession}) or the connection ends (see `AnnouncedChildren`).
|
||||
*/
|
||||
private readonly announcedChildren = new AnnouncedChildren();
|
||||
/** What anchors a live cursor: the last entity that the client holds per session. */
|
||||
private readonly lastEntities = new LastReportedEntity();
|
||||
/**
|
||||
* AIR's draft: the model that the last load of each session replayed to each
|
||||
* child session, as the model id and the entry that went out. See
|
||||
@@ -1787,6 +1825,7 @@ export class ClaudeAcpAgent {
|
||||
// Before the client can name the child that a `subagent_update` announces.
|
||||
this.announcedChildren.sending(update);
|
||||
this.mcp.sending(update);
|
||||
this.lastEntities.sending(update as Parameters<LastReportedEntity["sending"]>[0]);
|
||||
},
|
||||
);
|
||||
this.logger = logger ?? console;
|
||||
@@ -1969,6 +2008,12 @@ export class ClaudeAcpAgent {
|
||||
AIR_PLAN_FILE_CAPABILITY,
|
||||
AIR_BACKGROUND_SUBAGENTS_CAPABILITY,
|
||||
...this.sessionIndex.capabilities(),
|
||||
...(clientSupportsAirCapability(
|
||||
request.clientCapabilities,
|
||||
AIR_SESSION_REWIND_CAPABILITY,
|
||||
)
|
||||
? [AIR_SESSION_REWIND_CAPABILITY]
|
||||
: []),
|
||||
),
|
||||
AIR_GOAL_KEY,
|
||||
{
|
||||
@@ -2166,6 +2211,89 @@ export class ClaudeAcpAgent {
|
||||
return this.sessionIndex.forking(sourceId, fork);
|
||||
}
|
||||
|
||||
/**
|
||||
* `_session/rewind` (see `session-rewind.ts`). Queued with the session's
|
||||
* configuration changes, so a mode or model change sent meanwhile lands on
|
||||
* the resumed query. A prompt sent meanwhile waits for it in `startTurn`:
|
||||
* the rewind closes the query the prompt would otherwise run on.
|
||||
*/
|
||||
rewindSession(params: SessionRewindRequest): Promise<SessionRewindResponse> {
|
||||
// Only AIR knows the method, and only when it declared `sessionRewind`.
|
||||
if (!this.supportsSessionRewind()) {
|
||||
return Promise.reject(RequestError.methodNotFound(SESSION_REWIND_METHOD));
|
||||
}
|
||||
const { sessionId } = params;
|
||||
const rewind = (async () => {
|
||||
// Outside the queue: a provider update queues its own restart there.
|
||||
while (this.providerUpdate) await this.providerUpdate;
|
||||
return this.serializeConfigurationChange(sessionId, () => this.rewindLiveSession(params));
|
||||
})();
|
||||
const settled = rewind.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
this.sessionRewinds.set(sessionId, settled);
|
||||
void settled.then(() => {
|
||||
if (this.sessionRewinds.get(sessionId) === settled) this.sessionRewinds.delete(sessionId);
|
||||
});
|
||||
return rewind;
|
||||
}
|
||||
|
||||
private rewindLiveSession(params: SessionRewindRequest): Promise<SessionRewindResponse> {
|
||||
const { sessionId } = params;
|
||||
const session = this.sessions[sessionId];
|
||||
if (!session) throw RequestError.sessionNotFound(sessionId);
|
||||
const creationParams = session.creationParams;
|
||||
if (!creationParams || session.queryClosed) {
|
||||
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
||||
}
|
||||
return rewindSession(params, {
|
||||
logger: this.logger,
|
||||
clearedContext: session.claudeSessionId !== undefined,
|
||||
// A `/remote-control` command in flight answers into the session's output
|
||||
// after the query that the rewind closes was asked for it.
|
||||
claudeIsWorking: () =>
|
||||
this.claudeIsWorking(sessionId, session) || session.remoteControlCommand !== undefined,
|
||||
// A closed query also ends the background tasks and subagents.
|
||||
hasBackgroundWork: () =>
|
||||
[...session.liveBackgroundTasks.values()].some((task) => !task.endedPerLevel),
|
||||
loadHistory: () => loadRewindableHistory(sessionId, this.logger),
|
||||
// The task list and the published failures outlive the dropped turns (and
|
||||
// a failed cut): their entries carry ids of their own, which the transcript
|
||||
// does not attribute to a turn. The ACP message ids are not carried: they
|
||||
// may name a dropped message, and a fork then reads the stored history.
|
||||
replaceQuery: async (resumeAt) => {
|
||||
await this.replaceSessionQuery(sessionId, session, creationParams, resumeAt, {
|
||||
cwd: session.cwd,
|
||||
taskState: session.taskState,
|
||||
subagentChecklists: session.subagentChecklists,
|
||||
forwardSubagentText: session.forwardSubagentText,
|
||||
sessionFailureState: session.sessionFailureState,
|
||||
messageIdToUuid: new Map(),
|
||||
});
|
||||
const recreated = this.sessions[sessionId];
|
||||
if (recreated && recreated !== session) this.rewoundSessions.set(session, recreated);
|
||||
},
|
||||
// The client drops the entities after the cut, which the anchor may name.
|
||||
// The edited message's cursor lies where the dropped one did.
|
||||
rewound: (cursorId) => this.lastEntities.rewind(sessionId, cursorId),
|
||||
abandon: async (error) => {
|
||||
if (error instanceof RequestError && error.code === AUTH_REQUIRED_CODE) {
|
||||
// As after a sign-out: keep the husk, so the prompt after a sign-in
|
||||
// recreates its query instead of meeting "Session not found".
|
||||
session.needsSignOutRespawn = true;
|
||||
return error;
|
||||
}
|
||||
// Not a closed husk: a `session/load` resumes the conversation again.
|
||||
await this.teardownSession(sessionId);
|
||||
return RequestError.internalError(
|
||||
undefined,
|
||||
`The rewind failed and the session could not be resumed: ${error}. Load the session again.`,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async resumeSession(params: ResumeSessionRequest): Promise<ResumeSessionResponse> {
|
||||
const initial = initialConfigOptions(params.configOptions);
|
||||
while (this.providerUpdate) await this.providerUpdate;
|
||||
@@ -2505,6 +2633,9 @@ export class ClaudeAcpAgent {
|
||||
if (origin === "client") this.sessions[params.sessionId]?.idleCompaction?.disarm("prompt");
|
||||
const received = ++this.promptsReceived;
|
||||
while (this.providerUpdate) await this.providerUpdate;
|
||||
// A rewind closes the session's query and resumes a new one.
|
||||
const rewinding = this.sessionRewinds.get(params.sessionId);
|
||||
if (rewinding) await rewinding;
|
||||
let session = this.sessions[params.sessionId];
|
||||
if (!session) {
|
||||
throw RequestError.sessionNotFound(params.sessionId);
|
||||
@@ -2541,13 +2672,17 @@ export class ClaudeAcpAgent {
|
||||
|
||||
// Only a prompt that is the command awaits here: an await on every prompt
|
||||
// would let other work run between its checks and its turn's enqueue.
|
||||
const remoteControl = parseRemoteControlCommand(params.prompt)
|
||||
? await adapterRemoteControlCommand(
|
||||
params.prompt,
|
||||
session.query,
|
||||
session.terminalSlashCommands,
|
||||
)
|
||||
: null;
|
||||
const isRemoteControl = parseRemoteControlCommand(params.prompt) !== null;
|
||||
const askRemoteControl = () =>
|
||||
adapterRemoteControlCommand(params.prompt, session.query, session.terminalSlashCommands);
|
||||
let remoteControl = isRemoteControl ? await askRemoteControl() : null;
|
||||
// A rewind that closed the query during that await did not see the command
|
||||
// (`remoteControlCommand` is not set yet). It goes on with the session the
|
||||
// rewind leaves, and is asked again of its query.
|
||||
while (isRemoteControl && this.rewindToFollow(params.sessionId, session)) {
|
||||
session = await this.followRewind(params.sessionId, session);
|
||||
remoteControl = await askRemoteControl();
|
||||
}
|
||||
if (remoteControl) {
|
||||
// The reply bypasses the turn queue, so it would land inside the output of
|
||||
// a turn that is still running. Refuse instead of interleaving.
|
||||
@@ -2600,6 +2735,16 @@ export class ClaudeAcpAgent {
|
||||
await this.publishTaskPlan(params.sessionId, session.taskState);
|
||||
}
|
||||
|
||||
// A rewind that started during the awaits above did not see this prompt,
|
||||
// which is not queued yet, and closes the query it was set up on. The
|
||||
// prompt goes on with the session the rewind leaves, also when the rewind
|
||||
// finished before this point. Only the subscription guard runs again: it is
|
||||
// per query.
|
||||
if (this.rewindToFollow(params.sessionId, session)) {
|
||||
session = await this.followRewind(params.sessionId, session);
|
||||
if (origin === "client") session.idleCompaction?.disarm("prompt");
|
||||
}
|
||||
|
||||
const userMessage = promptToClaude(params);
|
||||
const promptUuid = randomUUID();
|
||||
userMessage.uuid = promptUuid;
|
||||
@@ -2610,7 +2755,7 @@ export class ClaudeAcpAgent {
|
||||
const isLocalOnlyCommand =
|
||||
firstText.startsWith("/") && LOCAL_ONLY_COMMANDS.has(firstText.split(" ", 1)[0]);
|
||||
|
||||
const fileChangeReport = session.fileChangeReporter?.request(params._meta);
|
||||
let fileChangeReport = session.fileChangeReporter?.request(params._meta);
|
||||
|
||||
const localCommand = this.localCommandMarkdown(params);
|
||||
const localCommandAbort = localCommand ? new AbortController() : undefined;
|
||||
@@ -2631,10 +2776,36 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
|
||||
// A `/remote-control` command still in flight answers into the session's
|
||||
// output; wait for its reply before this prompt's turn can begin. Nothing
|
||||
// below awaits before the turn is queued, so no command can start between.
|
||||
// output; wait for its reply before this prompt's turn can begin. A rewind
|
||||
// may have replaced the session during the awaits above, including the
|
||||
// command's network call, and a command may be in flight on the successor
|
||||
// too (a `/remote-control` prompt that the same rewind held). So wait for
|
||||
// the current session's command, follow a rewind, and look again, until
|
||||
// neither is pending. The check that ends the loop and the turn's enqueue
|
||||
// below have no await between them, so no command can start in between.
|
||||
// A failure of the command's reply is reported to the command's own prompt.
|
||||
if (session.remoteControlCommand) await session.remoteControlCommand.catch(() => {});
|
||||
// A command that was waited for is done: its prompt clears the field in a
|
||||
// `finally` that may run after this wait resumes, so it is not waited for twice.
|
||||
let waited: Promise<void> | undefined;
|
||||
for (;;) {
|
||||
if (session.remoteControlCommand && session.remoteControlCommand !== waited) {
|
||||
waited = session.remoteControlCommand;
|
||||
await waited.catch(() => {});
|
||||
continue;
|
||||
}
|
||||
if (!this.rewindToFollow(params.sessionId, session)) break;
|
||||
const followed = await this.followRewind(params.sessionId, session);
|
||||
if (followed === session) continue;
|
||||
// What the prompt took from the old session (the file change report, the
|
||||
// title context and the idle compaction's disarm) is taken again from
|
||||
// the new one.
|
||||
session = followed;
|
||||
fileChangeReport = session.fileChangeReporter?.request(params._meta);
|
||||
if (origin === "client") {
|
||||
session.titles.onPrompt(params.prompt);
|
||||
session.idleCompaction?.disarm("prompt");
|
||||
}
|
||||
}
|
||||
|
||||
// A `session/close` during the awaits above tore the session down, and
|
||||
// its consumer is gone, so the prompt would never be inserted. End it
|
||||
@@ -2661,6 +2832,7 @@ export class ClaudeAcpAgent {
|
||||
promptUuid,
|
||||
events,
|
||||
isLocalOnlyCommand,
|
||||
getsCursor: promptGetsCursor(params.prompt),
|
||||
...(localCommand ? { localCommand } : {}),
|
||||
...(localCommandAbort ? { localCommandAbort } : {}),
|
||||
...(fileChangeReport ? { fileChangeReport } : {}),
|
||||
@@ -2693,6 +2865,78 @@ export class ClaudeAcpAgent {
|
||||
);
|
||||
}
|
||||
|
||||
/** Checked before `followRewind` so that a prompt which has nothing to follow does not yield. */
|
||||
private rewindToFollow(sessionId: string, session: Session): boolean {
|
||||
return this.sessionRewinds.has(sessionId) || this.rewoundSessions.has(session);
|
||||
}
|
||||
|
||||
/** Waits for a running rewind of the session and returns the session the rewinds left in place of `session`; a session that ended otherwise is returned as it is. */
|
||||
private async followRewind(sessionId: string, session: Session): Promise<Session> {
|
||||
let moved = false;
|
||||
for (;;) {
|
||||
const running = this.sessionRewinds.get(sessionId);
|
||||
if (running) {
|
||||
await running;
|
||||
if (!this.sessions[sessionId]) throw RequestError.sessionNotFound(sessionId);
|
||||
}
|
||||
const next = this.rewoundSessions.get(session);
|
||||
if (next) {
|
||||
session = next;
|
||||
moved = true;
|
||||
continue;
|
||||
}
|
||||
if (running) continue;
|
||||
if (!moved) return session;
|
||||
// Only the end of the chain must be alive: an intermediate session of two
|
||||
// rewinds in one await is closed by the second rewind.
|
||||
if (session.queryClosed) throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
||||
const guard = this.runClaudeSubscriptionGuard(sessionId, session);
|
||||
if (guard) await guard;
|
||||
if (!this.rewoundSessions.has(session) && !this.sessionRewinds.has(sessionId)) {
|
||||
return session;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the client is AIR and declared `sessionRewind`: only it knows `_session/rewind`. */
|
||||
private supportsSessionRewind(): boolean {
|
||||
return (
|
||||
this.toolCallCapabilities.air.client &&
|
||||
clientSupportsAirCapability(this.clientCapabilities, AIR_SESSION_REWIND_CAPABILITY)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a `cursor_update` to a client that declared `session.cursors`, and to
|
||||
* no other: its `SessionUpdate` union is closed. A failed send is logged only,
|
||||
* as the cursor is announced again by the next replay.
|
||||
*
|
||||
* `before` is the entity that this client holds right before the cursor.
|
||||
*
|
||||
* It carries `rewind` only where `_session/rewind` can act: not for a cursor
|
||||
* that is `beforeCompaction` (`rewindable` false), and not in a session whose
|
||||
* context was cleared (`clearedContext`).
|
||||
*/
|
||||
private announceCursor(
|
||||
sessionId: string,
|
||||
update: ReturnType<typeof anchoredForkCursorUpdate>,
|
||||
before: CursorEntity | undefined,
|
||||
{ rewindable: inChain = true }: { rewindable?: boolean } = {},
|
||||
): void {
|
||||
if (this.clientCapabilities?.session?.cursors == null) return;
|
||||
this.lastEntities.recordCursor(sessionId, update.cursorId, before);
|
||||
const rewindable =
|
||||
inChain &&
|
||||
this.supportsSessionRewind() &&
|
||||
this.sessions[sessionId]?.claudeSessionId === undefined;
|
||||
this.client
|
||||
.sessionUpdate({
|
||||
sessionId,
|
||||
update: rewindable ? withRewindCapability(update) : update,
|
||||
} as AcpSessionNotification)
|
||||
.catch((error) => this.logger.error(`Session ${sessionId}: cursor_update failed:`, error));
|
||||
}
|
||||
|
||||
/** Runs the command, and sends its reply (see `runRemoteControlCommand`). */
|
||||
private async runRemoteControlCommand(
|
||||
sessionId: string,
|
||||
@@ -2893,6 +3137,9 @@ export class ClaudeAcpAgent {
|
||||
resumedModelHint?: string | Promise<string | undefined>;
|
||||
replacingSession?: Session;
|
||||
optionsOnly?: boolean;
|
||||
resumeSessionAt?: string;
|
||||
resumeDropsTurn?: string;
|
||||
replayState?: ReplayState;
|
||||
},
|
||||
): Promise<NewSessionResponse> {
|
||||
try {
|
||||
@@ -3651,6 +3898,17 @@ export class ClaudeAcpAgent {
|
||||
turn.insertedReported = true;
|
||||
turn.events.inserted(turn.promptUuid);
|
||||
this.startForeground(params.sessionId, turn);
|
||||
// v1 does not report the prompt the client sent, so the cursor lies after
|
||||
// the entity before it. The first prompt has none, and a session that was
|
||||
// resumed without a replay holds none (no anchor, no cursor).
|
||||
const anchor = this.lastEntities.after(params.sessionId);
|
||||
if (turn.getsCursor && anchor) {
|
||||
this.announceCursor(
|
||||
params.sessionId,
|
||||
anchoredForkCursorUpdate(turn.promptUuid, anchor),
|
||||
this.lastEntities.last(params.sessionId),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Ensure there is an active turn before a user-turn result that carries no
|
||||
@@ -6750,6 +7008,9 @@ export class ClaudeAcpAgent {
|
||||
? stripLocalCommandMetadata(message.message.content)
|
||||
: null;
|
||||
if (remoteContent !== null) {
|
||||
// Before the message itself is reported below.
|
||||
const before = this.lastEntities.last(params.sessionId);
|
||||
const hasHistory = before !== undefined;
|
||||
for (const notification of toAcpNotifications(
|
||||
remoteContent as ContentBlockParam[] | string,
|
||||
"user",
|
||||
@@ -6766,6 +7027,18 @@ export class ClaudeAcpAgent {
|
||||
)) {
|
||||
await sendUpdate(notification);
|
||||
}
|
||||
// This client reported the message with its `messageId`: the
|
||||
// cursor lies before it, as in a replay.
|
||||
if (
|
||||
hasHistory &&
|
||||
promptGetsCursor(
|
||||
typeof remoteContent === "string"
|
||||
? [{ type: "text", text: remoteContent }]
|
||||
: (remoteContent as ContentBlockParam[]),
|
||||
)
|
||||
) {
|
||||
this.announceCursor(params.sessionId, forkCursorUpdate(message.uuid), before);
|
||||
}
|
||||
}
|
||||
// Otherwise an unrelated replay (e.g. the echo of an already-settled turn).
|
||||
break;
|
||||
@@ -7966,6 +8239,7 @@ export class ClaudeAcpAgent {
|
||||
// After the teardown's last updates, which name the children.
|
||||
this.announcedChildren.rootClosed(sessionId);
|
||||
this.mcp.sessionClosed(sessionId);
|
||||
this.lastEntities.forget(sessionId);
|
||||
}
|
||||
|
||||
/** Idempotent: a session that is not loaded here is already closed. */
|
||||
@@ -8089,12 +8363,18 @@ export class ClaudeAcpAgent {
|
||||
): Promise<void> {
|
||||
const replayStartedAt = performance.now();
|
||||
const toolUseCache: ToolUseCache = {};
|
||||
// A replay rebuilds the client's entities, and its cursors anchor to those.
|
||||
this.lastEntities.forget(sessionId);
|
||||
// A load replays the messages before each compaction too, unless reading them fails.
|
||||
const messages = await readHistoryAcrossCompactions(
|
||||
// The rewind cut comes first: the dropped turns get no replay and no cursor.
|
||||
const current = await cutAtRewindPoint(
|
||||
sessionId,
|
||||
resumedMessages ?? (await getSessionMessages(sessionId)),
|
||||
this.logger,
|
||||
);
|
||||
const messages = await readHistoryAcrossCompactions(sessionId, current, this.logger);
|
||||
// A cursor whose resume point a compaction left out cannot be rewound to.
|
||||
const currentUuids = new Set(current.map((message) => message.uuid));
|
||||
const historyLoadedAt = performance.now();
|
||||
this.logger.log(
|
||||
`[session/replay] sessionId=${sessionId} phase=read durationMs=${Math.round(historyLoadedAt - replayStartedAt)} messages=${messages.length}`,
|
||||
@@ -8592,7 +8872,21 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const message of messages) await replayMessage(message);
|
||||
for (const [index, message] of messages.entries()) {
|
||||
// Before the message's own chunk: the cursor lies before the message.
|
||||
const before = this.lastEntities.last(sessionId);
|
||||
await replayMessage(message);
|
||||
// A task notification record is no user message to the client (see `replayMessage`).
|
||||
if (
|
||||
!pending?.stopped &&
|
||||
hasForkCursor(messages, index) &&
|
||||
!isTaskNotificationRecord(message)
|
||||
) {
|
||||
this.announceCursor(sessionId, forkCursorUpdate(message.uuid), before, {
|
||||
rewindable: currentUuids.has(messages[index - 1]!.uuid),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (rfdReplay && !pending?.stopped) {
|
||||
await rfdReplay.finish(clientSupportsNotices(this.clientCapabilities), sessionId);
|
||||
this.replayedSubagents.set(sessionId, rfdReplay);
|
||||
@@ -10166,6 +10460,15 @@ export class ClaudeAcpAgent {
|
||||
const timing = new SessionTiming(this.logger, "create", sessionId, createStartedAt);
|
||||
timing.phase("validate-cwd");
|
||||
|
||||
// A resume stops at a pending rewind point, or the dropped turns come back.
|
||||
// The `session/options` probe persists nothing, so it leaves the transcript
|
||||
// and `rewind.json` alone. A rewind passes its own point.
|
||||
const resumeSessionAt =
|
||||
creationOpts.resumeSessionAt ??
|
||||
(creationOpts.resume !== undefined && !creationOpts.optionsOnly
|
||||
? await prepareRewoundResume(creationOpts.resume, this.logger)
|
||||
: undefined);
|
||||
|
||||
// Most session/load calls already carry a transcript snapshot so history
|
||||
// replay and model restoration share one local read. A few resume paths
|
||||
// intentionally call createSession directly (legacy session/new metadata,
|
||||
@@ -10564,6 +10867,13 @@ export class ClaudeAcpAgent {
|
||||
],
|
||||
},
|
||||
...(creationOpts.resume !== undefined && { resume: creationOpts.resume }),
|
||||
...(creationOpts.resume !== undefined &&
|
||||
resumeSessionAt !== undefined && {
|
||||
resumeSessionAt,
|
||||
...(creationOpts.resumeDropsTurn !== undefined && {
|
||||
resumeDropsTurn: creationOpts.resumeDropsTurn,
|
||||
}),
|
||||
}),
|
||||
...(creationOpts.forkSession !== undefined && { forkSession: creationOpts.forkSession }),
|
||||
// The probe neither reports session updates through our hooks nor
|
||||
// starts the MCP servers in the client's options or workspace settings.
|
||||
@@ -10842,6 +11152,9 @@ export class ClaudeAcpAgent {
|
||||
resumedFromHistory: creationOpts.resume !== undefined,
|
||||
cwd: params.cwd,
|
||||
sessionFingerprint: computeSessionFingerprint(params),
|
||||
...(creationOpts.publicSessionId && options.sessionId
|
||||
? { claudeSessionId: options.sessionId }
|
||||
: {}),
|
||||
creationParams: params,
|
||||
unservedMcpServers,
|
||||
settingsManager,
|
||||
@@ -11027,6 +11340,8 @@ export class ClaudeAcpAgent {
|
||||
sessionId: string,
|
||||
session: Session,
|
||||
creationParams: NewSessionRequest,
|
||||
resumeAt?: { resumeSessionAt: string; resumeDropsTurn?: string },
|
||||
keepState?: ReplayState,
|
||||
): Promise<void> {
|
||||
this.closeQueryStream(session);
|
||||
// Keep the old record visible so closeSession and dispose can mark it torn down.
|
||||
@@ -11034,6 +11349,8 @@ export class ClaudeAcpAgent {
|
||||
await this.recreateLiveSession(withoutEffort(creationParams), sessionId, {
|
||||
permissionMode: session.modes.currentModeId as PermissionMode,
|
||||
replacingSession: session,
|
||||
...resumeAt,
|
||||
...(keepState ? { replayState: keepState } : {}),
|
||||
});
|
||||
const recreated = this.sessions[sessionId];
|
||||
if (!recreated || recreated.tornDown) return;
|
||||
@@ -11571,6 +11888,13 @@ export function v1AgentApp(
|
||||
.onRequest(methods.agent.providers.disable, (ctx) => agent.unstable_disableProvider(ctx.params))
|
||||
.onRequest(methods.agent.logout, (ctx) => agent.logout(ctx.params))
|
||||
.onRequest(methods.agent.auth.status, () => agent.authStatusResponse())
|
||||
.onRequest<SessionRewindRequest, SessionRewindResponse>(
|
||||
SESSION_REWIND_METHOD,
|
||||
{ parse: parseSessionRewindRequest },
|
||||
// Registered before `session/prompt`: the lock is taken in the same tick as the request,
|
||||
// so a prompt sent right after it waits in `startTurn`.
|
||||
ofRootSession("rewind", (ctx) => agent.rewindSession(ctx.params)),
|
||||
)
|
||||
.onRequest(
|
||||
methods.agent.session.prompt,
|
||||
ofRootSession("prompt", (ctx) => runPromptWithCancellation(agent, ctx.params, ctx.signal)),
|
||||
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
import { mergeEffortSettings } from "../session-effort.js";
|
||||
import { configuredSettings, resolveThinkingConfig } from "../session-env.js";
|
||||
import { resolveInitialPermissionMode } from "../session-mode.js";
|
||||
import { cutAtRewindPoint, prepareRewoundResume } from "../session-rewind.js";
|
||||
import { sanitizeTitle } from "../session-titles.js";
|
||||
import { renameSession } from "../session-index/rename.js";
|
||||
import {
|
||||
@@ -519,8 +520,14 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
const { sessionId, replayFrom } = params;
|
||||
// The replay: the messages before each compaction too, unless reading them fails.
|
||||
const acrossCompactions = (chain: Promise<SessionMessage[]>, cwd: string) => {
|
||||
const messages = chain.then((read) =>
|
||||
readHistoryAcrossCompactions(sessionId, read, this.logger, cwd),
|
||||
// The rewind cut comes first: the dropped turns get no replay and no cursor.
|
||||
const messages = chain.then(async (read) =>
|
||||
readHistoryAcrossCompactions(
|
||||
sessionId,
|
||||
await cutAtRewindPoint(sessionId, read, this.logger),
|
||||
this.logger,
|
||||
cwd,
|
||||
),
|
||||
);
|
||||
// A resume that fails before the replay leaves them unawaited.
|
||||
chain.catch(() => {});
|
||||
@@ -1139,6 +1146,11 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
) {
|
||||
const request = await validatedSetup(params);
|
||||
const client = clientOptions(params._meta);
|
||||
// A resume stops at a pending rewind point, or the dropped turns come back.
|
||||
// The `session/options` probe (`persist: false`) leaves the transcript and
|
||||
// `rewind.json` alone.
|
||||
const resumeSessionAt =
|
||||
resume !== undefined && persist ? await prepareRewoundResume(resume, this.logger) : undefined;
|
||||
const served = await this.mcpServersOf(sessionId, request, client, mcpServersRefused);
|
||||
const mcpServers = served.configs;
|
||||
// After a provider change that is still listing its models.
|
||||
@@ -1312,6 +1324,7 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
...STARTUP_FAILURE_RESULTS_ENV,
|
||||
},
|
||||
...(resume !== undefined ? { resume } : { sessionId }),
|
||||
...(resumeSessionAt !== undefined ? { resumeSessionAt } : {}),
|
||||
...(persist ? {} : { persistSession: false }),
|
||||
};
|
||||
let q: Query;
|
||||
@@ -1464,7 +1477,7 @@ async function validatedSetup(
|
||||
async function storedPromptIds(sessionId: string, cwd: string, logger: Logger): Promise<string[]> {
|
||||
const messages = await readHistoryAcrossCompactions(
|
||||
sessionId,
|
||||
await getSessionMessages(sessionId, { dir: cwd }),
|
||||
await cutAtRewindPoint(sessionId, await getSessionMessages(sessionId, { dir: cwd }), logger),
|
||||
logger,
|
||||
cwd,
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user