Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 35 additions & 15 deletions docs/design/web-shell-history-pagination.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,33 @@ transcript becomes scrollable or history is exhausted. A failed or partial page
leaves the current transcript intact, stops automatic retries, and surfaces the
existing daemon notice path.

### Live-session retention

The 50,000-block store limit remains a final safety cap. Web Shell also applies
a 500-block reload trigger to sessions that remain open for a long time. Once a
transcript exceeds that trigger, the agent is idle, no SSE event has arrived for
two minutes, and the reader remains at the live tail, Web Shell reloads the same
session with `historyPageSize: 100`. The old SSE subscription is closed by the
normal session-switch cleanup. The load response supplies the bounded replay
and its atomic `lastEventId`; the provider rebuilds the transcript and starts a
new SSE subscription from that watermark.

The existing transcript remains mounted while this background load is in
flight. Once the bounded replay arrives, the provider resets and dispatches it
in one store notification, so the reader never sees an empty or loading state.

Loading an already attached session with a page size refreshes only its UI
replay. It does not restart the agent or reload the model-facing conversation.
The bridge reads a fresh persisted page while the session EventBus watermark is
stable and returns it through the normal load envelope. If events arrive during
that read, the bridge retries and otherwise falls back to its existing replay.

After reload, upward scrolling follows the same `beforeRecordId` and opaque
cursor pagination used by historical sessions. Scrolling upward cancels the
reload timer. Returning to the live tail starts a new two-minute quiet period.
Main and split views own independent providers, SSE subscriptions, timers,
cursors, and retained windows.

## Consistency and failure handling

- Initial history and the SSE watermark remain coupled through `session/load`.
Expand All @@ -138,18 +165,11 @@ existing daemon notice path.

## Affected areas

| Layer | Change |
| ------------------------ | ------------------------------------------------------------ |
| Core transcript reader | Backward cursor and exclusive record boundary |
| ACP replay | Record UUID metadata and latest-suffix selection |
| ACP bridge / serve route | Paged-load metadata, validation, and `hasMore` propagation |
| TypeScript SDK | Restore option, backward page option, restored history state |
| WebUI provider | Isolated prepend, page state, stale-request protection |
| Web Shell | Opt-in page size and automatic top-loading behavior |

## Open questions and follow-ups

- A session created and kept live for its entire lifetime has no persisted
record UUID on its live EventBus frames. This change pages sessions restored
through the new load path; adding record identity to live emission is a
separate recording/emission coordination change.
| Layer | Change |
| ------------------------ | ---------------------------------------------------------- |
| Core transcript reader | Backward cursor and exclusive record boundary |
| ACP replay | Record UUID metadata and latest-suffix selection |
| ACP bridge / serve route | Paged-load metadata, validation, and `hasMore` propagation |
| TypeScript SDK | Restore page-size option and restored history state |
| WebUI provider | Isolated prepend, page state, stale-request protection |
| Web Shell | Opt-in page size and automatic top-loading behavior |
81 changes: 81 additions & 0 deletions packages/acp-bridge/src/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2918,6 +2918,87 @@ describe('createAcpSessionBridge', () => {
await bridge.shutdown();
});

it('refreshes an attached load from a bounded persisted page', async () => {
const handle = makeChannel({
loadSessionImpl: () => ({
_meta: {
'qwen.session.loadReplay': {
v: 1,
updates: [
{
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'initial prompt' },
},
],
},
},
}),
extMethodImpl: (method, params) => {
if (method !== SERVE_STATUS_EXT_METHODS.sessionTranscript) {
throw new Error(`unexpected extMethod ${method}`);
}
return {
v: 1,
sessionId: params['sessionId'],
events: [
{
v: 1,
type: 'session_update',
data: {
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'latest prompt' },
_meta: { 'qwen.session.recordId': 'record-latest' },
},
},
],
hasMore: true,
};
},
});
const bridge = makeBridge({ channelFactory: async () => handle.channel });
const loaded = await bridge.loadSession({
sessionId: 'persisted-live-refresh',
workspaceCwd: WS_A,
historyReplay: 'response',
historyPageSize: 100,
});

const refreshed = await bridge.loadSession({
sessionId: loaded.sessionId,
workspaceCwd: WS_A,
clientId: loaded.clientId,
historyReplay: 'response',
historyPageSize: 100,
});

expect(handle.agent.loadSessionCalls).toHaveLength(1);
expect(handle.agent.extMethodCalls).toContainEqual({
method: SERVE_STATUS_EXT_METHODS.sessionTranscript,
params: {
cwd: WS_A,
sessionId: loaded.sessionId,
direction: 'backward',
limit: 100,
},
});
expect(refreshed).toMatchObject({
attached: true,
historyHasMore: true,
lastEventId: loaded.lastEventId,
compactedReplay: [
{
type: 'session_update',
data: {
content: { type: 'text', text: 'latest prompt' },
},
},
],
liveJournal: [],
});

await bridge.shutdown();
});

it('restores artifacts from response-mode load replay when no snapshot is available', async () => {
const handles: ChannelHandle[] = [];
const factory: ChannelFactory = async () => {
Expand Down
103 changes: 72 additions & 31 deletions packages/acp-bridge/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ import type {
BridgeWorkspaceMemoryRememberRequest,
BridgeWorkspaceMemoryRememberResult,
BridgeSessionTranscriptPage,
BridgeSessionTranscriptPageRequest,
BridgeGenerationStreamEvent,
} from './bridgeTypes.js';
import type {
Expand Down Expand Up @@ -3872,6 +3873,68 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
return publicState;
};

async function requestSessionTranscriptPage(
req: BridgeSessionTranscriptPageRequest,
): Promise<BridgeSessionTranscriptPage> {
const info = await ensureChannel();
try {
const response = await withWorkspaceControl(info, () =>
withTimeout(
Promise.race([
info.connection.extMethod(
SERVE_STATUS_EXT_METHODS.sessionTranscript,
{ ...req, cwd: boundWorkspace },
),
getChannelClosedReject(info),
]),
Math.max(initTimeoutMs, SESSION_TRANSCRIPT_TIMEOUT_MS),
SERVE_STATUS_EXT_METHODS.sessionTranscript,
),
);
return response as unknown as BridgeSessionTranscriptPage;
} catch (err) {
if (isAcpSessionResourceNotFound(err, req.sessionId)) {
throw new SessionNotFoundError(req.sessionId);
}
throw err;
} finally {
if (hasNoChannelWork(info)) {
await startIdleTimer(info, 'session transcript');
}
}
}

async function refreshedReplayFieldsFor(
entry: SessionEntry,
historyPageSize: number,
): Promise<ReturnType<typeof replayFieldsFor>> {
for (let attempt = 0; attempt < 2; attempt++) {
const lastEventId = entry.events.lastEventId;
const page = await requestSessionTranscriptPage({
Comment thread
ytahdn marked this conversation as resolved.
Resolved
sessionId: entry.sessionId,
direction: 'backward',
limit: historyPageSize,
});
if (
byId.get(entry.sessionId) === entry &&
!entry.promptActive &&
entry.events.lastEventId === lastEventId
) {
return {
compactedReplay: page.events,
liveJournal: [],
lastEventId,
...(page.partial === true ? { partial: true as const } : {}),
...(page.replayError !== undefined
? { replayError: page.replayError }
: {}),
...(page.hasMore ? { historyHasMore: true as const } : {}),
};
}
}
return replayFieldsFor(entry, 'load');
}

async function restoreSession(
action: 'load' | 'resume',
req: BridgeRestoreSessionRequest,
Expand Down Expand Up @@ -3900,6 +3963,13 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
'The session is closing; retry after close completes',
);
}
const replayFields =
action === 'load' && req.historyPageSize !== undefined
? await refreshedReplayFieldsFor(existing, req.historyPageSize)
: replayFieldsFor(existing, action);
if (byId.get(req.sessionId) !== existing) {
throw new SessionNotFoundError(req.sessionId);
}
Comment thread
ytahdn marked this conversation as resolved.
Resolved
existing.attachCount++;
const clientId = registerClient(existing, req.clientId);
recordAttachRef(existing, clientId);
Expand All @@ -3920,7 +3990,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
// caller saw; spawn-only sessions don't carry a state payload.
state: existing.restoreState ?? {},
hasActivePrompt: existing.promptActive,
...replayFieldsFor(existing, action),
...replayFields,
};
}

Expand Down Expand Up @@ -6293,36 +6363,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
},

async getSessionTranscriptPage(req) {
const info = await ensureChannel();
try {
const response = await withWorkspaceControl(info, () =>
withTimeout(
Promise.race([
info.connection.extMethod(
SERVE_STATUS_EXT_METHODS.sessionTranscript,
{ ...req, cwd: boundWorkspace },
),
getChannelClosedReject(info),
]),
Math.max(initTimeoutMs, SESSION_TRANSCRIPT_TIMEOUT_MS),
SERVE_STATUS_EXT_METHODS.sessionTranscript,
),
);
return response as unknown as BridgeSessionTranscriptPage;
} catch (err) {
// A missing transcript file (ENOENT without a cursor) surfaces from the
// child as a raw resourceNotFound JSON-RPC error. Translate it to
// SessionNotFoundError so the route maps it to HTTP 404 — mirroring the
// load/resume path above — instead of falling through to a 500.
if (isAcpSessionResourceNotFound(err, req.sessionId)) {
throw new SessionNotFoundError(req.sessionId);
}
throw err;
} finally {
if (hasNoChannelWork(info)) {
await startIdleTimer(info, 'session transcript');
}
}
return requestSessionTranscriptPage(req);
},

async cancelSessionTask(sessionId, taskId, taskKind) {
Expand Down
2 changes: 2 additions & 0 deletions packages/acp-bridge/src/bridgeTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,8 @@ export interface BridgeSessionTranscriptPageRequest {
sessionId: string;
cursor?: string;
beforeRecordId?: string;
/** Internal newest-page read used to refresh an attached session's UI. */
direction?: 'backward';
limit?: number;
}

Expand Down
41 changes: 41 additions & 0 deletions packages/cli/src/acp-integration/acpAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7707,6 +7707,47 @@ describe('QwenAgent MCP SSE/HTTP support', () => {
await agentPromise;
});

it('flushes the live recording before reading the latest persisted page', async () => {
const innerConfig = await setupSessionMocks(VALID_SESSION_ID);
const recording = innerConfig.getChatRecordingService();
const readPage = vi.fn().mockResolvedValue({
sessionId: VALID_SESSION_ID,
records: [],
hasMore: false,
startTime: 'start',
lastUpdated: 'end',
});
vi.mocked(SessionTranscriptReader).mockImplementation(
() =>
({
readPage,
}) as unknown as InstanceType<typeof SessionTranscriptReader>,
);
mockHistoryReplayPage.mockResolvedValue({ pendingToolCalls: [] });
const { agent, agentPromise } = await bootAcpAgent();
await agent.newSession({ cwd: '/tmp', mcpServers: [] });

const result = await agent.extMethod(
SERVE_STATUS_EXT_METHODS.sessionTranscript,
{
sessionId: VALID_SESSION_ID,
direction: 'backward',
limit: 100,
},
);

expect(recording?.flush).toHaveBeenCalledOnce();
expect(readPage).toHaveBeenCalledWith(VALID_SESSION_ID, {
direction: 'backward',
limit: 100,
maxBytes: 4 * 1024 * 1024,
});
expect(result['hasMore']).toBe(false);

mockConnectionState.resolve();
await agentPromise;
});

it('disposes a pending transcript config superseded by newer settings', async () => {
const oldSettings = makeCoreSettings('English');
const newSettings = makeCoreSettings('Japanese');
Expand Down
23 changes: 23 additions & 0 deletions packages/cli/src/acp-integration/acpAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6820,6 +6820,19 @@ class QwenAgent implements Agent {
'Transcript cursor and record boundary are mutually exclusive',
);
}
const rawDirection = params['direction'];
if (rawDirection !== undefined && rawDirection !== 'backward') {
throw RequestError.invalidParams(
Comment thread
ytahdn marked this conversation as resolved.
Resolved
undefined,
'Invalid transcript direction',
);
}
if (rawCursor !== undefined && rawDirection !== undefined) {
throw RequestError.invalidParams(
undefined,
'Transcript cursor and direction are mutually exclusive',
);
}
const rawLimit = params['limit'];
if (
rawLimit !== undefined &&
Expand All @@ -6836,12 +6849,22 @@ class QwenAgent implements Agent {
try {
const settings = loadSettingsCached(cwd);
return await runWithAcpRuntimeOutputDir(settings, cwd, async () => {
if (rawDirection === 'backward') {
await this.sessions
.get(sessionId)
?.getConfig()
.getChatRecordingService()
?.flush();
}
const reader = new SessionTranscriptReader(cwd);
const page = await reader.readPage(sessionId, {
...(typeof rawCursor === 'string' ? { cursor: rawCursor } : {}),
...(typeof rawBeforeRecordId === 'string'
? { beforeRecordId: rawBeforeRecordId }
: {}),
...(rawDirection === 'backward'
? { direction: rawDirection }
: {}),
...(typeof rawLimit === 'number' ? { limit: rawLimit } : {}),
maxBytes: SESSION_TRANSCRIPT_MAX_PAGE_BYTES,
});
Expand Down
Loading
Loading