Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
9 changes: 8 additions & 1 deletion cli/src/cursor/cursorAcpRemoteLauncher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,14 +248,21 @@ describe('cursorAcpRemoteLauncher', () => {
const session = makeSession('old-stream-json-id');

await expect(cursorAcpRemoteLauncher(session)).rejects.toThrow(
/Legacy stream-json sessions cannot be loaded via ACP/
/Failed to resume Cursor ACP session \(session not found\)/
);

expect(harness.loadSessionCalled).toBe(true);
expect(harness.newSessionCalled).toBe(false);
expect(legacyLauncher).not.toHaveBeenCalled();
});

it('sends ready after successful ACP bootstrap for hub resume handshake', async () => {
const session = makeSession('resume-thread-1');
await cursorAcpRemoteLauncher(session);

expect(session.client.sendSessionEvent).toHaveBeenCalledWith({ type: 'ready' });
});

it('throws when resume id is set but session/load is unsupported', async () => {
harness.supportsLoadSession = false;
const session = makeSession('some-session-id');
Expand Down
6 changes: 5 additions & 1 deletion cli/src/cursor/cursorAcpRemoteLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,9 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase {
});
} catch (error) {
logger.warn('[cursor-acp] session/load failed', formatAcpLoadError(error));
const detail = error instanceof Error ? error.message : String(error);
throw new Error(
'Failed to resume Cursor ACP session. Legacy stream-json sessions cannot be loaded via ACP.'
`Failed to resume Cursor ACP session (${detail}). Legacy stream-json sessions cannot be loaded via ACP.`
);
}
} else if (resumeSessionId) {
Expand Down Expand Up @@ -179,6 +180,9 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase {
session.sendSessionEvent({ type: 'ready' });
};

// Hub reopen/resume waits for this before merging archived rows (#917).
sendReady();

while (!this.shouldExit) {
const waitSignal = this.abortController.signal;
const batch = await session.queue.waitForMessagesAndGetAsString(waitSignal);
Expand Down
28 changes: 5 additions & 23 deletions cli/src/cursor/utils/cursorProtocol.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,5 @@
import type { Metadata } from '@hapi/protocol/schemas';

export type CursorSessionProtocol = 'acp' | 'stream-json';

export function isLegacyCursorSession(metadata: Metadata | null | undefined): boolean {
if (metadata?.flavor !== 'cursor') {
return false;
}
if (metadata.cursorSessionProtocol === 'acp') {
return false;
}
if (metadata.cursorSessionProtocol === 'stream-json') {
return Boolean(metadata.cursorSessionId);
}
return Boolean(metadata.cursorSessionId);
}

export function resolveCursorRemoteProtocol(metadata: Metadata | null | undefined): CursorSessionProtocol {
if (isLegacyCursorSession(metadata)) {
return 'stream-json';
}
return 'acp';
}
export {
isLegacyCursorSession,
resolveCursorRemoteProtocol,
type CursorSessionProtocol
} from '@hapi/protocol/cursorProtocol'
6 changes: 6 additions & 0 deletions hub/src/sync/messageService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { Server } from 'socket.io'
import { randomUUID } from 'node:crypto'
import type { Store, CancelQueuedMessageResult } from '../store'
import { EventPublisher } from './eventPublisher'
import { isSessionReadyMessage } from './sessionActivity'

type StoredMessageForDelivery = ReturnType<Store['messages']['getMessages']>[number]

Expand Down Expand Up @@ -91,6 +92,11 @@ export class MessageService {
return toVisibleDecryptedMessages(stored)
}

hasSessionReadyEvent(sessionId: string, limit: number = 100): boolean {
const stored = this.store.messages.getMessages(sessionId, limit)
return stored.some((message) => isSessionReadyMessage(message.content))
}

getSessionExport(
sessionId: string,
session: Session,
Expand Down
9 changes: 9 additions & 0 deletions hub/src/sync/sessionActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ function isReadyEventContent(content: unknown): boolean {
return data?.type === 'ready'
}

export function isSessionReadyMessage(content: unknown): boolean {
const message = unwrapRoleWrappedRecordEnvelope(content)
if (!message || message.role !== 'agent') {
return false
}

return isReadyEventContent(message.content)
}

export function shouldRecordSessionActivity(content: unknown): boolean {
const message = unwrapRoleWrappedRecordEnvelope(content)
if (!message) {
Expand Down
69 changes: 69 additions & 0 deletions hub/src/sync/sessionCache.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { AgentStateSchema, MetadataSchema, TeamStateSchema } from '@hapi/protocol/schemas'
import { resolveCursorRemoteProtocol } from '@hapi/protocol/cursorProtocol'
import type { CodexCollaborationMode, PermissionMode, Session, SessionPatch } from '@hapi/protocol/types'
import type { Store } from '../store'
import { clampAliveTime } from './aliveTime'
import { EventPublisher } from './eventPublisher'
import { extractTodoWriteTodosFromMessageContent, TodosSchema } from './todos'
import { extractBackgroundTaskDelta } from './backgroundTasks'
import { isSessionReadyMessage } from './sessionActivity'

const QUEUED_MESSAGE_THINKING_GRACE_MS = 15_000
// tiann/hapi#919: metadata writers (renameSession, clearSessionArchiveMetadata,
Expand Down Expand Up @@ -696,6 +698,61 @@ export class SessionCache {
throw new Error('Session was modified concurrently. Please try again.')
}

/**
* Stamp `cursorSessionProtocol: 'stream-json'` on pre-#799 Cursor rows without
* clearing archive metadata. Used during archived reopen (#917): we defer
* `clearSessionArchiveMetadata` until resume succeeds, but the spawned CLI
* reads protocol from the existing row when bootstrapping a `--resume` spawn.
*/
async stampLegacyCursorSessionProtocol(sessionId: string): Promise<{ cursorSessionProtocol: 'stream-json' }> {
for (let attempt = 0; attempt < METADATA_RETRY_ATTEMPTS; attempt += 1) {
const session = this.sessions.get(sessionId) ?? this.refreshSession(sessionId)
if (!session) {
throw new Error('Session not found')
}

const currentMetadata = session.metadata
if (!currentMetadata) {
throw new Error('Session metadata missing')
}

if (
currentMetadata.flavor !== 'cursor'
|| typeof currentMetadata.cursorSessionId !== 'string'
|| currentMetadata.cursorSessionId.length === 0
|| currentMetadata.cursorSessionProtocol !== undefined
) {
throw new Error('Session is not a legacy Cursor row needing protocol stamp')
}

const next: Record<string, unknown> = {
...currentMetadata,
cursorSessionProtocol: 'stream-json'
}

const result = this.store.sessions.updateSessionMetadata(
sessionId,
next,
session.metadataVersion,
session.namespace,
{ touchUpdatedAt: false }
)

if (result.result === 'error') {
throw new Error('Failed to update session metadata')
}

if (result.result === 'success') {
this.refreshSession(sessionId)
return { cursorSessionProtocol: 'stream-json' }
}

this.refreshSession(sessionId)
}

throw new Error('Session was modified concurrently. Please try again.')
}

/**
* Restore archive-related metadata fields that were captured before a reopen attempt.
* Used when `resumeSession` fails after `clearSessionArchiveMetadata` already ran so the
Expand Down Expand Up @@ -1165,6 +1222,13 @@ export class SessionCache {
mergeAgentState: false
})
} else {
const candidateMetadata = candidate?.metadata
const isArchivedCursorAcp = candidateMetadata?.lifecycleState === 'archived'
&& candidateMetadata?.flavor === 'cursor'
&& resolveCursorRemoteProtocol(candidateMetadata) === 'acp'
if (isArchivedCursorAcp && !this.hasSessionReadyEvent(targetId)) {
continue
}
await this.mergeSessions(id, targetId, targetNamespace)
}
} catch {
Expand All @@ -1177,4 +1241,9 @@ export class SessionCache {
this.deduplicatePending.delete(agentId.value)
}
}

private hasSessionReadyEvent(sessionId: string): boolean {
return this.store.messages.getMessages(sessionId, 100)
.some((message) => isSessionReadyMessage(message.content))
}
}
Loading
Loading