mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
feat(codex): fork running sessions through the last completed turn (#2369)
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { ApiSessionClient } from '@/api/apiSession';
|
||||
import type { AgentState, Metadata } from '@/api/types';
|
||||
import type { SessionBootstrapResult } from '@/agent/sessionFactory';
|
||||
import { SharedCodexRoot, type RootHost } from './root';
|
||||
import { SharedCodexRoot, latestCompletedForkCutoff, type RootHost } from './root';
|
||||
import { codexPlanProposalId } from './plan';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
import { asyncQuestionsForItem } from './asyncQuestions';
|
||||
@@ -59,7 +61,7 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
async function fixture(opts?: { hubArchived?: boolean; end?: RootHost['end']; create?: RootHost['create'] }) {
|
||||
const directory = await mkdtemp('/tmp/hapi-shared-root-');
|
||||
const directory = await mkdtemp(join(tmpdir(), 'hapi-shared-root-'));
|
||||
let state: AgentState = { steeringActive: true };
|
||||
let metadata: Metadata = { path: directory, host: 'test', flavor: 'codex' };
|
||||
let reconnect: (() => void) | null = null;
|
||||
@@ -636,3 +638,66 @@ describe('shared steering availability', () => {
|
||||
await vi.waitFor(() => expect(end).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
});
|
||||
|
||||
describe('latest completed list fork', () => {
|
||||
it('uses an inclusive fixed cutoff while later source turns advance', async () => {
|
||||
const initialSettings = vi.fn(async () => {});
|
||||
const create = vi.fn<RootHost['create']>(async (_method, params) => {
|
||||
expect(params).toMatchObject({ threadId: 'thread', lastTurnId: 'two' });
|
||||
expect(params).not.toHaveProperty('beforeTurnId');
|
||||
f.native.thread.turns.push({ id: 'later', status: 'inProgress', items: [] });
|
||||
return { threadId: 'child', session: { sessionId: 'child-session' }, initialSettings,
|
||||
readThread: async () => ({ turns: f.native.thread.turns.slice(0, 2) }) } as unknown as SharedCodexRoot;
|
||||
});
|
||||
const f = await fixture({ create });
|
||||
f.native.thread.turns = [
|
||||
{ id: 'one', status: 'completed', items: [{ id: 'u1', type: 'userMessage', clientId: 'first' }] },
|
||||
{ id: 'two', status: 'completed', items: [{ id: 'u2', type: 'userMessage', clientId: 'second' }] },
|
||||
{ id: 'three', status: 'inProgress', items: [{ id: 'u3', type: 'userMessage', clientId: 'running' }] }
|
||||
];
|
||||
await f.root.refresh(); await f.root.activate();
|
||||
expect(f.metadata().capabilities?.conversationHistory?.forkLatestCompleted).toBe(true);
|
||||
const request = vi.spyOn(f.root.client, 'request');
|
||||
await expect(f.rpc.get(RPC_METHODS.ForkConversation)!({ latestCompleted: true })).resolves.toEqual({
|
||||
nativeSessionId: 'child', sessionId: 'child-session', completedTurnId: 'two'
|
||||
});
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
expect(f.state().steeringActive).toBe(true);
|
||||
expect(request.mock.calls.some(([method]) => method === 'turn/interrupt')).toBe(false);
|
||||
});
|
||||
it('refuses empty, unknown and mixed boundary requests before mutation', async () => {
|
||||
const create = vi.fn<RootHost['create']>();
|
||||
const f = await fixture({ create }); await f.root.activate();
|
||||
const fork = f.rpc.get(RPC_METHODS.ForkConversation)!;
|
||||
await expect(fork({ latestCompleted: true })).rejects.toThrow('No completed');
|
||||
f.native.thread.turns = [{ id: 'bad', status: 'unknown', items: [] }];
|
||||
await expect(fork({ latestCompleted: true })).rejects.toThrow('prefix');
|
||||
await expect(fork({ latestCompleted: true, messageLocalId: 'first' })).rejects.toThrow();
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('completed native prefix validation', () => {
|
||||
it('rejects duplicate or unknown native turn identities and states', () => {
|
||||
expect(() => latestCompletedForkCutoff([{ id: 'one', status: 'completed' }, { id: 'one', status: 'inProgress' }])).toThrow('ambiguous');
|
||||
expect(() => latestCompletedForkCutoff([{ id: 'one', status: 'unknown' }, { id: 'two', status: 'completed' }])).toThrow('prefix');
|
||||
expect(() => latestCompletedForkCutoff([{ status: 'completed' }])).toThrow('ambiguous');
|
||||
});
|
||||
it('uses the last completed turn and excludes a failed trailing turn', () => {
|
||||
expect(latestCompletedForkCutoff([{ id: 'one', status: 'completed' }, { id: 'two', status: 'failed' }, { id: 'three', status: 'inProgress' }])).toBe('one');
|
||||
expect(latestCompletedForkCutoff([{ id: 'one', status: 'completed' }, { id: 'two', status: 'completed' }])).toBe('two');
|
||||
});
|
||||
});
|
||||
|
||||
it('closes a native child whose inherited prefix does not match the requested cutoff', async () => {
|
||||
const child = { threadId: 'wrong-child', session: { sessionId: 'wrong-session' },
|
||||
readThread: async () => ({ turns: [{ id: 'one' }, { id: 'running' }] }) } as unknown as SharedCodexRoot;
|
||||
const end = vi.fn(async () => {});
|
||||
const create = vi.fn<RootHost['create']>(async () => child);
|
||||
const f = await fixture({ create, end });
|
||||
f.native.thread.turns = [{ id: 'one', status: 'completed', items: [] }, { id: 'running', status: 'inProgress', items: [] }];
|
||||
await f.root.refresh(); await f.root.activate();
|
||||
await expect(f.rpc.get(RPC_METHODS.ForkConversation)!({ latestCompleted: true })).rejects.toThrow('does not match');
|
||||
expect(end).toHaveBeenCalledWith(child);
|
||||
expect(f.state().steeringActive).toBe(true);
|
||||
});
|
||||
|
||||
@@ -97,6 +97,9 @@ export class SharedCodexRoot {
|
||||
}
|
||||
if (method === 'turn/completed' && (!this.currentTurn || record(record(params).turn).id === this.currentTurn)) {
|
||||
this.turnRevision++; this.currentTurn = undefined; this.interrupted = record(record(params).turn).status === 'interrupted';
|
||||
if (record(record(params).turn).status === 'completed') this.session.updateMetadata(metadata => ({ ...metadata,
|
||||
capabilities: { ...metadata.capabilities, conversationHistory: { ...metadata.capabilities?.conversationHistory,
|
||||
forkLatestCompleted: true } } }));
|
||||
this.publishSteering();
|
||||
}
|
||||
const p = record(params);
|
||||
@@ -233,7 +236,7 @@ export class SharedCodexRoot {
|
||||
...metadata.capabilities, concurrentClients: true, terminal: true,
|
||||
// In-place rewind needs a native + hub commit barrier. Do not
|
||||
// advertise a destructive operation we cannot make atomic yet.
|
||||
conversationHistory: { forkCurrent: true, forkAtMessage: true, rewindToMessage: false }
|
||||
conversationHistory: { forkCurrent: true, forkAtMessage: true, forkLatestCompleted: false, rewindToMessage: false }
|
||||
} }));
|
||||
this.session.updateAgentState(state => ({ ...state, controlledByUser: false, startingMode: undefined, codexPlanProposalId: null, codexCompactionPendingMessageIds: [], requests: {},
|
||||
completedRequests: { ...state.completedRequests, ...Object.fromEntries(Object.entries(state.requests ?? {}).map(([id, request]) =>
|
||||
@@ -386,6 +389,12 @@ export class SharedCodexRoot {
|
||||
const id = string(last?.id);
|
||||
this.latestTurn = id && last ? { id, status: string(last.status) ?? 'unknown', planId: planProposalForTurn(this.threadId, last) } : undefined;
|
||||
}
|
||||
const canForkLatest = turns.some(turn => turn.status === 'completed')
|
||||
|| (this.lazyHistory() && this.session.getMetadata()?.capabilities?.conversationHistory?.forkLatestCompleted === true);
|
||||
if (this.session.getMetadata()?.capabilities?.conversationHistory?.forkLatestCompleted !== canForkLatest) {
|
||||
this.session.updateMetadata(metadata => ({ ...metadata, capabilities: { ...metadata.capabilities,
|
||||
conversationHistory: { ...metadata.capabilities?.conversationHistory, forkLatestCompleted: canForkLatest } } }));
|
||||
}
|
||||
await this.projectHistory(this.projection, thread); await this.queue.reconcile(); this.alive();
|
||||
}
|
||||
private async refreshChildren(subscribe: boolean): Promise<void> {
|
||||
@@ -582,7 +591,30 @@ export class SharedCodexRoot {
|
||||
const child = await this.newConversation(); return { sessionId: child.session.sessionId };
|
||||
});
|
||||
rpc.registerHandler(RPC_METHODS.ForkConversation, async raw => {
|
||||
const { messageLocalId } = z.object({ messageLocalId: z.string().optional() }).parse(raw);
|
||||
const { messageLocalId, latestCompleted } = z.object({ messageLocalId: z.string().optional(), latestCompleted: z.boolean().optional() })
|
||||
.refine(value => !(value.messageLocalId && value.latestCompleted)).parse(raw);
|
||||
if (latestCompleted) {
|
||||
const thread = await this.readThread(this.threadId, true);
|
||||
const turns = (Array.isArray(thread.turns) ? thread.turns : []).map(record);
|
||||
const cutoff = latestCompletedForkCutoff(turns);
|
||||
// An explicit inclusive native cutoff remains fixed even if the source advances.
|
||||
// Shared children hydrate directly from native fork history, never a moving Hub tail.
|
||||
const child = await this.host.create('thread/fork', { ...this.freshParams(), threadId: this.threadId,
|
||||
lastTurnId: cutoff }, this);
|
||||
try {
|
||||
const expected = turns.slice(0, turns.findIndex(turn => turn.id === cutoff) + 1).map(turn => string(turn.id));
|
||||
const inherited = await child.readThread(child.threadId, true);
|
||||
const actual = (Array.isArray(inherited.turns) ? inherited.turns : []).map(value => string(record(value).id));
|
||||
if (actual.length !== expected.length || actual.some((id, index) => id !== expected[index])) {
|
||||
throw new Error('Native fork history does not match the completed-turn cutoff');
|
||||
}
|
||||
await child.initialSettings({ collaborationMode: this.settings.collaborationMode });
|
||||
return { nativeSessionId: child.threadId, sessionId: child.session.sessionId, completedTurnId: cutoff };
|
||||
} catch (error) {
|
||||
await this.host.end(child).catch(cleanup => logger.debug('[Codex shared] invalid fork cleanup failed', cleanup));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (this.currentTurn && !messageLocalId) throw new Error('Session is busy');
|
||||
const beforeTurnId = messageLocalId ? this.projection.turnFor(messageLocalId) : undefined;
|
||||
if (messageLocalId && !beforeTurnId) throw new Error('No native history point for this message');
|
||||
@@ -683,3 +715,17 @@ export class SharedCodexRoot {
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve an inclusive immutable prefix from authoritative native history. */
|
||||
export function latestCompletedForkCutoff(turns: Record<string, unknown>[]): string {
|
||||
const ids = turns.map(turn => string(turn.id));
|
||||
if (ids.some(id => !id) || new Set(ids).size !== ids.length) throw new Error('Native turn history is ambiguous');
|
||||
let completed: string | undefined;
|
||||
for (const turn of turns) {
|
||||
if (turn.status === 'inProgress' || turn.status === 'in_progress') break;
|
||||
if (!['completed', 'interrupted', 'failed'].includes(string(turn.status) ?? '')) throw new Error('Native history prefix is not complete');
|
||||
if (turn.status === 'completed') completed = string(turn.id);
|
||||
}
|
||||
if (!completed) throw new Error('No completed turn is available to fork');
|
||||
return completed;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user