* fix(agent-sleep): keep finished and interrupted agent sessions resumable after sleeping a workspace Manual workspace sleep ran a liveness filter over the panes it was about to kill (isValidManualSleepLiveAgentEntry), then wiped every pre-existing sleeping record in the worktree. A done, interrupted, typed-into, or >30-min-idle pane therefore lost its only resume handle and woke as a bare shell. A second filter at wake discarded any record carrying `interrupted: true`, which also killed interrupted sessions across an app restart. Capture now records every resumable pane, normalizing only `updatedAt` and `interrupted` and preserving the entry's real `state` so a finished pane keeps its passive record and resumes in place when its tab is opened instead of spawning a duplicate tab. The wake-side interrupted check is gone. A legacy-orchestration-worker block is carried onto the replacement record, and the Pi-compatible promoted checkpoint is no longer overwritten by a re-derived live record. Closes #11598 * fix(agent-sleep): keep durable slept records a repeat sleep cannot re-derive removeSleepingRecordsReplacedByManualWorktreeSleep wiped every record in the worktree, and only the freshly captured set was merged back. A slept `done` pane stays passive until its tab is opened, so a second sleep found no live status row to rebuild its record from and deleted the pane's only `--resume` handle with nothing written back — the original loss of #11598, one wake/sleep cycle later. The wipe now skips a record with no replacement in the new capture set when it is a durable capture (`origin` `worktree-sleep` or `quit`). Provisional `live`/legacy checkpoints are still cleared, so an unresumable Pi row does not survive a sleep it cannot back. Co-authored-by: Orca <help@stably.ai> * fix(agent-sleep): keep a slept workspace's finished panes out of the mobile wake fan-out A manual sleep now records every finished pane, and those passive records fed wakeSleepingAgentsForWorktreeInBackground step (b), which background-mounts one tab per passive record. A phone opening a slept 12-tab workspace would have cold-restored 12 agents at once, undoing the process shedding the sleep was for. Manual-sleep captures of finished panes carry restoreOnTabOpenOnly; step (b) skips them and the pane resumes in place when its own tab is opened, which is what desktop activation already did and what the phone's per-tab mount provides. Co-authored-by: Orca <help@stably.ai> * fix(agent-sleep): close the retained-row and shared-claim gaps in slept-session capture Three narrow holes left by the manual-sleep capture rewrite, all in the same "a slept session must stay resumable" contract: - The retained pass captured `retained.entry` verbatim, so a retained row - stale by construction, since it exists only after the pane's pty died - produced a `working` record that wake then discarded on the >30min staleness rule. It now takes the same `updatedAt`/`interrupted` normalization and the same `automaticResumeBlockedBy` carry-over as the live pass. - The retained pass also ran after the `origin: 'live'` promotion loop without its guard, so a pane holding both a promoted checkpoint and a retained row had the checkpoint (connectionId, transcript identity, active `working` class) overwritten by a re-derived passive record. - The mobile wake filtered `restoreOnTabOpenOnly` records *after* canonicalization, so a lazy record sharing a provider-session claim with an eligible hibernated record could win the claim, delete the hibernated record as a duplicate, and then be skipped - stranding the session with nothing mounted. --------- Co-authored-by: Orca <help@stably.ai>
131 lines
4.5 KiB
TypeScript
131 lines
4.5 KiB
TypeScript
import { z } from 'zod'
|
|
import {
|
|
getAgentResumeArgv,
|
|
normalizeAgentProviderSession,
|
|
RESUMABLE_TUI_AGENTS
|
|
} from './agent-session-resume'
|
|
import { isValidTerminalTabId } from './terminal-tab-id'
|
|
|
|
const terminalTabIdSchema = z
|
|
.string()
|
|
.min(1)
|
|
.refine(isValidTerminalTabId, 'terminal tab id must not contain ":"')
|
|
|
|
const agentProviderSessionSchema = z.preprocess(
|
|
(raw) => normalizeAgentProviderSession(raw) ?? undefined,
|
|
z.object({
|
|
key: z.enum(['session_id', 'conversation_id']),
|
|
id: z.string().min(1).max(512),
|
|
// Why: Pi resumes by its authoritative session file, so dropping this
|
|
// field during hydration makes an otherwise valid record unusable.
|
|
transcriptPath: z.string().min(1).optional()
|
|
})
|
|
)
|
|
|
|
function hasUnsafeLaunchEnvChars(value: string): boolean {
|
|
for (let i = 0; i < value.length; i += 1) {
|
|
const code = value.charCodeAt(i)
|
|
if (code <= 0x1f || code === 0x7f) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
function isUnsafeObjectKey(value: string): boolean {
|
|
return value === '__proto__' || value === 'constructor' || value === 'prototype'
|
|
}
|
|
|
|
const sleepingAgentLaunchEnvSchema = z.preprocess(
|
|
(raw) => {
|
|
if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
return undefined
|
|
}
|
|
const cleaned: Record<string, string> = Object.create(null)
|
|
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
|
|
const trimmedKey = key.trim()
|
|
if (
|
|
trimmedKey.length === 0 ||
|
|
isUnsafeObjectKey(trimmedKey) ||
|
|
trimmedKey.includes('=') ||
|
|
hasUnsafeLaunchEnvChars(trimmedKey) ||
|
|
typeof value !== 'string' ||
|
|
value.includes('\0')
|
|
) {
|
|
return undefined
|
|
}
|
|
cleaned[trimmedKey] = value
|
|
}
|
|
return { ...cleaned }
|
|
},
|
|
z.record(z.string(), z.string())
|
|
)
|
|
|
|
const sleepingAgentLaunchConfigBaseSchema = z.object({
|
|
agentCommand: z.string().optional(),
|
|
agentArgs: z.string(),
|
|
agentEnv: sleepingAgentLaunchEnvSchema,
|
|
// Why: AI Vault can scan arbitrary OMP roots, so cold restore must retain
|
|
// the exact provider resume locator instead of reconstructing its store.
|
|
ompResumeFilePath: z
|
|
.string()
|
|
.trim()
|
|
.min(1)
|
|
.max(32 * 1024)
|
|
.refine((value) => !hasUnsafeLaunchEnvChars(value))
|
|
.optional()
|
|
})
|
|
|
|
export const sleepingAgentLaunchConfigSchema = z.preprocess((raw) => {
|
|
const parsed = sleepingAgentLaunchConfigBaseSchema.safeParse(raw)
|
|
return parsed.success ? parsed.data : undefined
|
|
}, sleepingAgentLaunchConfigBaseSchema.optional())
|
|
|
|
const sleepingAgentSessionRecordSchema = z
|
|
.object({
|
|
paneKey: z.string().refine((value) => value.length > 0),
|
|
tabId: terminalTabIdSchema.optional(),
|
|
worktreeId: z.string().min(1),
|
|
agent: z.enum(RESUMABLE_TUI_AGENTS),
|
|
providerSession: agentProviderSessionSchema,
|
|
prompt: z.string(),
|
|
state: z.enum(['working', 'blocked', 'waiting', 'done']),
|
|
capturedAt: z.number().finite().positive(),
|
|
updatedAt: z.number().finite().positive(),
|
|
terminalTitle: z.string().optional(),
|
|
lastAssistantMessage: z.string().optional(),
|
|
interrupted: z.boolean().optional(),
|
|
connectionId: z.string().nullable().optional(),
|
|
launchConfig: sleepingAgentLaunchConfigSchema.optional(),
|
|
origin: z.enum(['worktree-sleep', 'quit', 'live']).optional(),
|
|
automaticResumeBlockedBy: z.enum(['legacy-orchestration-worker']).optional(),
|
|
restoreOnTabOpenOnly: z.boolean().optional()
|
|
})
|
|
.refine(
|
|
(record) => getAgentResumeArgv(record.agent, record.providerSession) !== null,
|
|
// Why: a hydrated record must be directly resumable; Pi additionally needs
|
|
// its persisted transcript path and agents must use their supported key.
|
|
{ message: 'provider session is not resumable for this agent', path: ['providerSession'] }
|
|
)
|
|
|
|
export const sleepingAgentSessionsByPaneKeySchema = z.preprocess((raw) => {
|
|
if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
return undefined
|
|
}
|
|
|
|
const cleaned: Record<string, z.infer<typeof sleepingAgentSessionRecordSchema>> = Object.create(
|
|
null
|
|
)
|
|
for (const [paneKey, value] of Object.entries(raw as Record<string, unknown>)) {
|
|
if (isUnsafeObjectKey(paneKey)) {
|
|
continue
|
|
}
|
|
const parsed = sleepingAgentSessionRecordSchema.safeParse(value)
|
|
if (parsed.success && parsed.data.paneKey === paneKey) {
|
|
cleaned[paneKey] = parsed.data
|
|
}
|
|
}
|
|
|
|
return Object.keys(cleaned).length > 0 ? { ...cleaned } : undefined
|
|
}, z.record(z.string(), sleepingAgentSessionRecordSchema).optional())
|