mirror of
https://github.com/stablyai/orca.git
synced 2026-10-30 16:47:34 +00:00
* feat(agent-session-journal): save each chat's open root turn beside its epoch A restart could only tell whether a chat was cut mid-turn by replaying its whole journal. journal_sessions now keeps the open root turn (open_turn_id, open_turn_since), set by the row that opens a turn and cleared only by a finish the provider reported, in that row's own transaction. A turn a quit, crash or Stop cut short stays open, which is what the next launch reads as Interrupted. Journal schema version 5 adds the two nullable columns with a forward migration; a new epoch starts with no turn open. * fix(native-chat): restore chat tabs at startup without replaying any history Startup opened every chat in the saved tab index and replayed its whole journal into the main process to learn its status. With hundreds of tabs and gigabytes of history, Orca froze in GC on every launch. Startup now lists each restored chat from its record and publishes its row as Interrupted (a turn was open when its host stopped, or the last quit's resume offer lists it) or Done, through the status stream and the agent-status sink, reading only each chat's journal_sessions row and its newest row's time. A chat's history is read when something opens it; that open settles what the gone generation left running and publishes the journal's own row over the restored one. No other startup path replays chats: restart offers list from their markers without opening chats, and orchestration mail opens the chats it must read one at a time. Opened chats are capped at 24 resident folds; opening one past the cap closes the least recently active folds that are only a cache, with the idle sweep's own close test. * Fix lazy chat restoration and cache ownership * Restore saved chat work across runtime restarts * Wait for committed structural progress in migration fixture * Correct restored ownership and bounded journal recovery * Preserve bounded work selection during legacy recovery * Complete deferred restart status publication * Fix restart recovery test fixtures * Use legal legacy recovery fixtures * Correct population delete observation * Bound legacy journal replay in a readonly worker * Repair legacy worker proof oracles * Reduce legacy scratch key serialization cost * Decode population meter namespaces with scratch UTF-16 encoding * Consolidate structured session imports for CI * Remove redundant casts and document checked type exceptions * Correct compiler contracts and retain journal fixture invariants * Fix checked test fixture contracts after compiler validation * Name population fixture identity type in exported signature * Preserve historical quit presentation after rewind * Fix structured session retry and remote worker delivery * Preserve settlement and restored status contracts * Enable legacy chat readiness on standalone hosts * Repair structured session static checks * Verify retained submission identity across rewinds * Show saved chat status without replaying history at startup * Keep chats closed when startup status finishes loading * Keep startup owner recovery independent of history loading * Preserve intentional quit verdicts in saved chat status * Use a checked host fixture in startup restoration tests * Group saved startup roster publication and verify scoped status work * Use checked array access in status cut counters * Complete checked saved status fixture typing * Declare portable roster counter contract * Use current saved chat startup APIs in contracts * Preserve complete chat tab authority across startup * Repair checked startup restoration test consumers * Keep authority fixture module mocks in test entries * Consolidate authority test fixture imports * Check restore fixture contracts and recorded queue recovery --------- Co-authored-by: m4air <m4air@Mac.localdomain> Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
137 lines
5.9 KiB
TypeScript
137 lines
5.9 KiB
TypeScript
// Install lazily after Electron finalizes the profile path; runtimes without structured requests need no store. Journal-open failures install a refusal.
|
|
|
|
import type { AgentSessionResumeTrigger } from '../../shared/agent-session-resume-marker'
|
|
import {
|
|
structuredAgentSessionTeardownTrigger,
|
|
tearDownRuntime,
|
|
type InstalledRuntime
|
|
} from './agent-session/structured-agent-session-runtime-teardown'
|
|
import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host'
|
|
import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry'
|
|
import { stopAgentSessionAttachments } from './structured-agent-session-attachment-wiring'
|
|
import {
|
|
openAgentSessionRecordStoreOnce,
|
|
releaseAgentSessionRecordStore
|
|
} from './agent-session-record-store-slot'
|
|
import { agentModelCatalogStore } from '../native-chat/agent-model-catalog/agent-model-catalog-store'
|
|
import {
|
|
neverThrowingStructuredAgentSessionLogger,
|
|
type StructuredAgentSessionLogger
|
|
} from '../native-chat/agent-session-wire/structured-agent-session-logger'
|
|
import { migrateLegacyNativeChatVisualsFolders } from '../native-chat/native-chat-scratch-folder-migration'
|
|
|
|
export { hasPersistedStructuredAgentSessionStore } from './agent-session-record-store-slot'
|
|
|
|
export type { StructuredAgentSessionRuntimeDeps } from './structured-agent-session-runtime-contract'
|
|
import type { StructuredAgentSessionRuntimeDeps } from './structured-agent-session-runtime-contract'
|
|
|
|
let installing: Promise<InstalledRuntime> | null = null
|
|
|
|
export const CLAUDE_STRUCTURED_AUTH_POLICY_REQUIRED =
|
|
'structured agent-session host requires a Claude auth policy resolver'
|
|
|
|
export const STRUCTURED_AGENT_LAUNCH_ARGS_REQUIRED =
|
|
'structured agent-session host requires a launch arguments resolver'
|
|
|
|
export const STRUCTURED_AGENT_SESSION_LOGGER_REQUIRED =
|
|
'structured agent-session host requires a logger'
|
|
|
|
/** Keep failed teardowns after clearing the install slot so later stops retry their indexed conversations and journal connection. */
|
|
const pendingTeardown = new Set<InstalledRuntime>()
|
|
|
|
export function ensureStructuredAgentSessionHost(
|
|
deps: StructuredAgentSessionRuntimeDeps
|
|
): Promise<StructuredAgentSessionHost> {
|
|
// A failed open must not poison the slot forever — the next call retries.
|
|
installing ??= install(deps).catch((error) => {
|
|
installing = null
|
|
throw error
|
|
})
|
|
return installing.then((installed) => installed.host)
|
|
}
|
|
|
|
/** Wait until observed exits publish and host reconciliation settles; callbacks alone cannot tell callers when lease updates land. */
|
|
export async function waitForStructuredAgentSessionRecovery(): Promise<void> {
|
|
const installed = await installing?.catch(() => null)
|
|
await installed?.waitForRecovery()
|
|
}
|
|
|
|
/** Stop every provider child; retain failed teardowns for retry after the install slot clears. */
|
|
export async function stopStructuredAgentSessionRuntime(options?: {
|
|
trigger?: AgentSessionResumeTrigger
|
|
}): Promise<void> {
|
|
const trigger = options?.trigger ?? structuredAgentSessionTeardownTrigger()
|
|
const pending = installing
|
|
installing = null
|
|
setStructuredAgentSessionHost(null)
|
|
stopAgentSessionAttachments()
|
|
const outstanding = [...pendingTeardown]
|
|
pendingTeardown.clear()
|
|
const installed = pending ? await pending.catch(() => null) : null
|
|
if (installed) {
|
|
outstanding.push(installed)
|
|
}
|
|
// A store admission opened with no host built on it has no teardown to close its database.
|
|
const recordStore = await releaseAgentSessionRecordStore()
|
|
if (
|
|
recordStore &&
|
|
!outstanding.some((runtime) => runtime.journalDatabase === recordStore.journalDatabase)
|
|
) {
|
|
recordStore.journalDatabase.close()
|
|
}
|
|
const failures: unknown[] = []
|
|
for (const runtime of outstanding) {
|
|
try {
|
|
await tearDownRuntime(runtime, trigger)
|
|
} catch (error) {
|
|
pendingTeardown.add(runtime)
|
|
failures.push(error)
|
|
}
|
|
}
|
|
await agentModelCatalogStore.flushPersistence()
|
|
if (failures.length === 1) {
|
|
throw failures[0]
|
|
}
|
|
if (failures.length > 1) {
|
|
throw new AggregateError(failures, 'structured agent-session runtime teardown failed')
|
|
}
|
|
}
|
|
|
|
async function install(deps: StructuredAgentSessionRuntimeDeps): Promise<InstalledRuntime> {
|
|
// A default policy could attribute sign-in failures to the wrong account.
|
|
if (typeof deps.resolveClaudeAuthPolicy !== 'function') {
|
|
throw new Error(CLAUDE_STRUCTURED_AUTH_POLICY_REQUIRED)
|
|
}
|
|
if (typeof deps.resolveLaunchArgs !== 'function') {
|
|
throw new Error(STRUCTURED_AGENT_LAUNCH_ARGS_REQUIRED)
|
|
}
|
|
const declared: Partial<StructuredAgentSessionLogger> | undefined = deps.logger
|
|
if (typeof declared?.warn !== 'function' || typeof declared.error !== 'function') {
|
|
throw new Error(STRUCTURED_AGENT_SESSION_LOGGER_REQUIRED)
|
|
}
|
|
const logger = neverThrowingStructuredAgentSessionLogger(deps.logger)
|
|
// The store launch admission may already have opened; a failed install leaves it to that slot.
|
|
const recordStore = await openAgentSessionRecordStoreOnce({
|
|
stateDirectory: deps.stateDirectory,
|
|
legacySessionTabIds: deps.legacySessionTabIds ?? [],
|
|
hostId: deps.hostId,
|
|
logger
|
|
})
|
|
try {
|
|
// Without the Arguments source there is nothing to fill from; missing modes run Ask.
|
|
if (deps.resolveAgentFullAccess) {
|
|
await recordStore.store.backfillChatPermissionModes(deps.resolveAgentFullAccess)
|
|
}
|
|
} catch (error) {
|
|
// Missing choices safely run Ask; the next host install retries this pass.
|
|
logger.warn('saving existing chat permission choices failed', {
|
|
scope: 'permission-mode-backfill',
|
|
error
|
|
})
|
|
}
|
|
// Before the host serves reads: a chat opened right after an update finds its visuals in place.
|
|
await migrateLegacyNativeChatVisualsFolders(deps.stateDirectory, logger)
|
|
const { installOnJournal } = await import('./structured-agent-session-host-assembly')
|
|
return await installOnJournal({ ...deps, logger }, recordStore)
|
|
}
|