mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-04 00:01:41 +00:00
* feat: add message-level conversation fork and rewind Expose native Codex/Grok/Claude history controls through hub REST+RPC and web ConfirmDialog actions, without file rewind or composed forks. Also reconcile the duplicate hub V14→V15 migration so typecheck can pass. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: hydrate fork transcript and consume Claude --fork-session Forked HAPI children now copy the source transcript prefix so navigation is not a blank thread, and Claude drops --fork-session after the first launch so relaunches do not branch again. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: harden fork/rewind concurrency and durable history points Skip pending scheduled rows when hydrating fork transcripts, serialize fork/rewind per session, and persist conversation history points/indexes across existing-session bootstrap and Grok relaunches. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: close remaining fork/rewind races and UI anchoring Block sends and scheduled maturation while history actions run, order fork prefixes by invocation time, inherit history locators into children, and only offer Fork current on the live tail boundary. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: address remaining fork/rewind bot findings Materialize Claude --fork-session before the first child prompt, validate HAPI history boundaries before native RPC, expose forkCurrent on a latest user boundary, fully demote unsupported conversationHistory capabilities, and fix the truncate test setup order. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: align fork-current ids and Claude fork bootstrap Compare the latest fork boundary in assistant-ui threadMessageId space, spawn Claude forks with the persisted session mode, and preserve forkedFrom across existing-session bootstrap. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: close fork/rewind consistency holes at the contract layer Hold the source history lock until Claude child binds a distinct native id, persist Codex localId→turnId locators, and mark/block diverged sessions when native rewind outruns HAPI truncate. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: use Codex stable lastTurnId for historical fork Map HAPI's exclusive boundary to the previous turn's inclusive lastTurnId so native fork context matches the hydrated transcript. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: require exact Grok native resume for fork children Reject newSession fallback when forkedFrom is set, and keep the hub history lock until the child binds the forked grokSessionId. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: kill active fork children before failed-fork cleanup Bind/readiness failures can leave the child process running; deleteSession rejects active rows, so terminate first then remove the HAPI session. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: close remaining fork lock, hydrate, and todos gaps Reject mode switches during history actions, batch-copy fork transcripts in one SQLite transaction, and rebuild todos after fork hydrate / rewind truncate. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: allow Codex historical fork before the first turn Use experimental beforeTurnId when there is no previous turn for the stable inclusive lastTurnId boundary. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: mark Grok history busy immediately after dequeue Hub idle checks clear once messages-consumed fires; hold the busy flag across permission sync and rewind-points lookup before prompt starts. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: encode copied conversation history content * fix(web): hide local conversation history actions * style(codex): remove trailing whitespace * fix(fork): preserve children when cleanup is unconfirmed * fix(history): confirm cleanup and guard rewind divergence * fix(history): probe capabilities before advertising --------- Co-authored-by: Cursor <cursoragent@cursor.com>
163 lines
6.3 KiB
TypeScript
163 lines
6.3 KiB
TypeScript
import { ApiClient, ApiSessionClient } from '@/lib';
|
|
import { MessageQueue2 } from '@/utils/MessageQueue2';
|
|
import { logger } from '@/ui/logger';
|
|
import { AgentSessionBase } from '@/agent/sessionBase';
|
|
import type { SessionEffort, SessionModel } from '@/api/types';
|
|
import type { EnhancedMode } from './loop';
|
|
import type { PermissionMode } from './loop';
|
|
import type { LocalLaunchExitReason } from '@/agent/localLaunchPolicy';
|
|
|
|
type LocalLaunchFailure = {
|
|
message: string;
|
|
exitReason: LocalLaunchExitReason;
|
|
};
|
|
|
|
export class Session extends AgentSessionBase<EnhancedMode> {
|
|
readonly claudeEnvVars?: Record<string, string>;
|
|
claudeArgs?: string[];
|
|
readonly mcpServers: Record<string, any>;
|
|
readonly allowedTools?: string[];
|
|
readonly hookSettingsPath: string;
|
|
/** Settings for the interactive TUI: also forwards permission-mode-carrying hooks. */
|
|
readonly localHookSettingsPath: string;
|
|
readonly startedBy: 'runner' | 'terminal';
|
|
readonly startingMode: 'local' | 'remote';
|
|
localLaunchFailure: LocalLaunchFailure | null = null;
|
|
private nativeSkillNames = new Set<string>();
|
|
|
|
constructor(opts: {
|
|
api: ApiClient;
|
|
client: ApiSessionClient;
|
|
path: string;
|
|
logPath: string;
|
|
sessionId: string | null;
|
|
claudeEnvVars?: Record<string, string>;
|
|
claudeArgs?: string[];
|
|
mcpServers: Record<string, any>;
|
|
messageQueue: MessageQueue2<EnhancedMode>;
|
|
onModeChange: (mode: 'local' | 'remote') => void;
|
|
allowedTools?: string[];
|
|
mode?: 'local' | 'remote';
|
|
startedBy: 'runner' | 'terminal';
|
|
startingMode: 'local' | 'remote';
|
|
hookSettingsPath: string;
|
|
localHookSettingsPath?: string;
|
|
permissionMode?: PermissionMode;
|
|
model?: SessionModel;
|
|
effort?: SessionEffort;
|
|
}) {
|
|
super({
|
|
api: opts.api,
|
|
client: opts.client,
|
|
path: opts.path,
|
|
logPath: opts.logPath,
|
|
sessionId: opts.sessionId,
|
|
messageQueue: opts.messageQueue,
|
|
onModeChange: opts.onModeChange,
|
|
mode: opts.mode,
|
|
sessionLabel: 'Session',
|
|
sessionIdLabel: 'Claude Code',
|
|
applySessionIdToMetadata: (metadata, sessionId) => ({
|
|
...metadata,
|
|
claudeSessionId: sessionId
|
|
}),
|
|
permissionMode: opts.permissionMode,
|
|
model: opts.model,
|
|
effort: opts.effort
|
|
});
|
|
|
|
this.claudeEnvVars = opts.claudeEnvVars;
|
|
this.claudeArgs = opts.claudeArgs;
|
|
this.mcpServers = opts.mcpServers;
|
|
this.allowedTools = opts.allowedTools;
|
|
this.hookSettingsPath = opts.hookSettingsPath;
|
|
this.localHookSettingsPath = opts.localHookSettingsPath ?? opts.hookSettingsPath;
|
|
this.startedBy = opts.startedBy;
|
|
this.startingMode = opts.startingMode;
|
|
this.permissionMode = opts.permissionMode;
|
|
this.model = opts.model;
|
|
this.effort = opts.effort;
|
|
}
|
|
|
|
setPermissionMode = (mode: PermissionMode): void => {
|
|
this.permissionMode = mode;
|
|
};
|
|
|
|
// Override base getPermissionMode to return the Claude-narrow type. Safe
|
|
// because the only writer (setPermissionMode above) accepts only Claude
|
|
// PermissionMode, so the field cannot hold a foreign flavor value.
|
|
getPermissionMode(): PermissionMode | undefined {
|
|
return this.permissionMode as PermissionMode | undefined;
|
|
}
|
|
|
|
setModel = (model: SessionModel): void => {
|
|
this.model = model;
|
|
};
|
|
|
|
setEffort = (effort: SessionEffort): void => {
|
|
this.effort = effort;
|
|
};
|
|
|
|
setNativeSkillNames = (names: readonly string[]): void => {
|
|
this.nativeSkillNames = new Set(names);
|
|
};
|
|
|
|
expandSkillReference = (message: string, trailingContext = ''): string => {
|
|
const match = /^\s*\$([^\s]+)(?=\s|$)/.exec(message);
|
|
if (!match || !this.nativeSkillNames.has(match[1])) return message;
|
|
const expanded = `/${match[1]}${message.slice(match[0].length)}`;
|
|
return trailingContext ? `${expanded}\n\n${trailingContext}` : expanded;
|
|
};
|
|
|
|
recordLocalLaunchFailure = (message: string, exitReason: LocalLaunchExitReason): void => {
|
|
this.localLaunchFailure = { message, exitReason };
|
|
};
|
|
|
|
/**
|
|
* Clear the current session ID (used by /clear command)
|
|
*/
|
|
clearSessionId = (): void => {
|
|
this.sessionId = null;
|
|
logger.debug('[Session] Session ID cleared');
|
|
};
|
|
|
|
/**
|
|
* Consume one-time Claude flags from claudeArgs after Claude spawn.
|
|
* Handles: --resume (with or without session ID) and --fork-session.
|
|
* `--fork-session` must be one-shot; keeping it across relaunches would
|
|
* branch again off the already-forked native id.
|
|
*/
|
|
consumeOneTimeFlags = (): void => {
|
|
if (!this.claudeArgs) return;
|
|
|
|
const filteredArgs: string[] = [];
|
|
for (let i = 0; i < this.claudeArgs.length; i++) {
|
|
if (this.claudeArgs[i] === '--resume') {
|
|
// Check if next arg looks like a UUID (contains dashes and alphanumeric)
|
|
if (i + 1 < this.claudeArgs.length) {
|
|
const nextArg = this.claudeArgs[i + 1];
|
|
// Simple UUID pattern check - contains dashes and is not another flag
|
|
if (!nextArg.startsWith('-') && nextArg.includes('-')) {
|
|
// Skip both --resume and the UUID
|
|
i++; // Skip the UUID
|
|
logger.debug(`[Session] Consumed --resume flag with session ID: ${nextArg}`);
|
|
} else {
|
|
// Just --resume without UUID
|
|
logger.debug('[Session] Consumed --resume flag (no session ID)');
|
|
}
|
|
} else {
|
|
// --resume at the end of args
|
|
logger.debug('[Session] Consumed --resume flag (no session ID)');
|
|
}
|
|
} else if (this.claudeArgs[i] === '--fork-session') {
|
|
logger.debug('[Session] Consumed --fork-session flag');
|
|
} else {
|
|
filteredArgs.push(this.claudeArgs[i]);
|
|
}
|
|
}
|
|
|
|
this.claudeArgs = filteredArgs.length > 0 ? filteredArgs : undefined;
|
|
logger.debug(`[Session] Consumed one-time flags, remaining args:`, this.claudeArgs);
|
|
};
|
|
}
|