fix(desktop): make Bot Mode switches hydrate canonical chats
This commit is contained in:
@@ -1,4 +1,9 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { exec as execCallback, spawn } from 'node:child_process'
|
||||
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
import { test } from 'vitest'
|
||||
|
||||
@@ -26,12 +31,14 @@ import {
|
||||
scrapeReadyPort,
|
||||
spawnLogPath,
|
||||
spawnRemoteDashboard,
|
||||
spawnTokenPath,
|
||||
validateRemotePath,
|
||||
writeLockfile
|
||||
} from './remote-lifecycle'
|
||||
|
||||
const OWNERSHIP_ID = '0123456789abcdef0123456789abcdef'
|
||||
const SPAWN_NONCE = '0123456789abcdef'
|
||||
const exec = promisify(execCallback)
|
||||
|
||||
function ownedLock(over: any = {}) {
|
||||
return {
|
||||
@@ -299,6 +306,135 @@ test('pidIsOurDashboard requires the exact serve ownership nonce', async () => {
|
||||
assert.equal(await pidIsOurDashboard(fakeSsh([[/print\("OWNED"/, 'FOREIGN\n']]), 5, SPAWN_NONCE, '/x/hermes'), false)
|
||||
})
|
||||
|
||||
test('pidIsOurDashboard accepts the venv entrypoint an installer wrapper execs into', async () => {
|
||||
let ownershipProbe = ''
|
||||
|
||||
const ssh = fakeSsh([
|
||||
[
|
||||
/python3 -c/,
|
||||
(command: string) => {
|
||||
ownershipProbe = command
|
||||
|
||||
return 'OWNED\n'
|
||||
}
|
||||
]
|
||||
])
|
||||
|
||||
assert.equal(
|
||||
await pidIsOurDashboard(
|
||||
ssh,
|
||||
5,
|
||||
SPAWN_NONCE,
|
||||
'~/.local/bin/hermes',
|
||||
'/Users/cd9c/.hermes',
|
||||
OWNERSHIP_ID,
|
||||
'ops'
|
||||
),
|
||||
true
|
||||
)
|
||||
assert.match(ownershipProbe, /hermes-agent.*venv.*bin.*hermes/)
|
||||
assert.match(ownershipProbe, /desktop-ssh.*0123456789abcdef\.token/)
|
||||
assert.match(ownershipProbe, /expected_profile=.*ops/)
|
||||
})
|
||||
|
||||
test.skipIf(process.platform === 'win32')(
|
||||
'pidIsOurDashboard recognizes an installer wrapper after it execs python + entrypoint',
|
||||
async () => {
|
||||
const temp = await mkdtemp(path.join(os.tmpdir(), 'hermes wrapper ownership '))
|
||||
const installDir = path.join(temp, 'install dir')
|
||||
const venvBin = path.join(installDir, 'venv', 'bin')
|
||||
const pythonLink = path.join(venvBin, 'python')
|
||||
const entrypoint = path.join(installDir, 'hermes')
|
||||
const launcher = path.join(temp, 'hermes launcher')
|
||||
const python = (await exec('command -v python3')).stdout.trim()
|
||||
const tokenPath = path.join(os.homedir(), spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE).replace(/^~\//, ''))
|
||||
|
||||
await mkdir(venvBin, { recursive: true })
|
||||
await symlink(python, pythonLink)
|
||||
await writeFile(entrypoint, 'import time\ntime.sleep(30)\n', 'utf8')
|
||||
await writeFile(launcher, `#!/bin/bash\nexec "${pythonLink}" "${entrypoint}" "$@"\n`, 'utf8')
|
||||
await chmod(launcher, 0o755)
|
||||
|
||||
const backendFlags = [
|
||||
'--host', '127.0.0.1', '--port', '0',
|
||||
'--ssh-session-token-file', tokenPath,
|
||||
'--ssh-owner-nonce', SPAWN_NONCE
|
||||
]
|
||||
|
||||
const children: ReturnType<typeof spawn>[] = []
|
||||
|
||||
const spawnInstaller = (args: string[]) => {
|
||||
const process = spawn(launcher, args, { stdio: 'ignore' })
|
||||
|
||||
children.push(process)
|
||||
|
||||
return process
|
||||
}
|
||||
|
||||
const child = spawnInstaller(['--profile', 'ops', 'serve', '--isolated', ...backendFlags])
|
||||
|
||||
const ssh = {
|
||||
exec: async (command: string) => (await exec(command, { shell: '/bin/bash' })).stdout
|
||||
}
|
||||
|
||||
const waitForEntrypoint = async (process: ReturnType<typeof spawn>) => {
|
||||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||||
const command = (await exec(`ps -ww -o command= -p ${process.pid}`)).stdout
|
||||
|
||||
if (command.includes(entrypoint)) {
|
||||
return true
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 25))
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
assert.equal(await waitForEntrypoint(child), true, 'wrapper must exec into the fake installer entrypoint')
|
||||
assert.equal(
|
||||
await pidIsOurDashboard(ssh, child.pid, SPAWN_NONCE, launcher, '/unrelated/hermes-home', OWNERSHIP_ID, 'ops'),
|
||||
true
|
||||
)
|
||||
assert.equal(
|
||||
await pidIsOurDashboard(ssh, child.pid, SPAWN_NONCE, launcher, '/unrelated/hermes-home', 'fedcba9876543210fedcba9876543210', 'ops'),
|
||||
false
|
||||
)
|
||||
assert.equal(
|
||||
await pidIsOurDashboard(ssh, child.pid, SPAWN_NONCE, launcher, '/unrelated/hermes-home', OWNERSHIP_ID, 'wrong-profile'),
|
||||
false
|
||||
)
|
||||
|
||||
const misplacedIsolated = spawnInstaller(['--profile', 'ops', '--isolated', 'serve', ...backendFlags])
|
||||
|
||||
assert.equal(await waitForEntrypoint(misplacedIsolated), true)
|
||||
assert.equal(
|
||||
await pidIsOurDashboard(ssh, misplacedIsolated.pid, SPAWN_NONCE, launcher, '/unrelated/hermes-home', OWNERSHIP_ID, 'ops'),
|
||||
false,
|
||||
'--isolated before serve must remain foreign'
|
||||
)
|
||||
|
||||
const conflictingProfile = spawnInstaller([
|
||||
'--profile', 'ops', 'serve', '--isolated', ...backendFlags, '--profile', 'foreign'
|
||||
])
|
||||
|
||||
assert.equal(await waitForEntrypoint(conflictingProfile), true)
|
||||
assert.equal(
|
||||
await pidIsOurDashboard(ssh, conflictingProfile.pid, SPAWN_NONCE, launcher, '/unrelated/hermes-home', OWNERSHIP_ID, 'ops'),
|
||||
false,
|
||||
'a duplicate conflicting profile must remain foreign'
|
||||
)
|
||||
} finally {
|
||||
for (const process of children) {
|
||||
process.kill('SIGTERM')
|
||||
}
|
||||
|
||||
await rm(temp, { force: true, recursive: true })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
test('cleanupStale kills ONLY a provably-ours pid, always drops the lockfile', async () => {
|
||||
const notOurs = fakeSsh([[/print\("OWNED"/, 'FOREIGN\n']])
|
||||
await cleanupStale(notOurs, OWNERSHIP_ID, {
|
||||
|
||||
@@ -91,6 +91,10 @@ function spawnLogPath(ownershipId, spawnNonce) {
|
||||
return `${ownershipDirectory(ownershipId)}/${validateSpawnNonce(spawnNonce)}.log`
|
||||
}
|
||||
|
||||
function spawnTokenPath(ownershipId, spawnNonce) {
|
||||
return `${ownershipDirectory(ownershipId)}/${validateSpawnNonce(spawnNonce)}.token`
|
||||
}
|
||||
|
||||
// shell-single-quote a value for safe interpolation into a remote command.
|
||||
function shq(value) {
|
||||
return `'${String(value).replace(/'/g, `'\\''`)}'`
|
||||
@@ -395,7 +399,15 @@ async function remotePidAlive(ssh, pid) {
|
||||
|
||||
// A pid is "provably ours" only if its remote cmdline carries our dashboard
|
||||
// args — never kill a pid we can't positively identify as our dashboard.
|
||||
async function pidIsOurDashboard(ssh, pid, spawnNonce, hermesPath = '') {
|
||||
async function pidIsOurDashboard(
|
||||
ssh,
|
||||
pid,
|
||||
spawnNonce,
|
||||
hermesPath = '',
|
||||
hermesHome = '',
|
||||
ownershipId = '',
|
||||
profile = ''
|
||||
) {
|
||||
if (!pid || !/^[0-9a-f]{16}$/.test(String(spawnNonce || '')) || !hermesPath) {
|
||||
return false
|
||||
}
|
||||
@@ -405,13 +417,25 @@ async function pidIsOurDashboard(ssh, pid, spawnNonce, hermesPath = '') {
|
||||
'import os,shlex,subprocess,sys\n' +
|
||||
`pid=${Number(pid)}\n` +
|
||||
`expected=os.path.expanduser(${shq(hermesPath)})\n` +
|
||||
// The installer-facing launcher is intentionally preserved for invocation
|
||||
// (#74411), but it may `exec python <install-dir>/hermes`, leaving neither
|
||||
// launcher nor HERMES_HOME-derived entrypoint in argv. The ownership-scoped
|
||||
// token path + random nonce + exact profile below are the alternative proof.
|
||||
`hermes_home=os.path.expanduser(${shq(hermesHome)}) if ${shq(hermesHome)} else ""\n` +
|
||||
'expected_entries={expected}\n' +
|
||||
'if hermes_home:\n' +
|
||||
' expected_entries.add(os.path.join(hermes_home,"hermes-agent","venv","bin","hermes"))\n' +
|
||||
`expected_token=os.path.expanduser(${shq(
|
||||
ownershipId ? spawnTokenPath(ownershipId, spawnNonce) : ''
|
||||
)})\n` +
|
||||
`expected_profile=${shq(profile)}\n` +
|
||||
`nonce=${shq(spawnNonce)}\n` +
|
||||
'try:\n' +
|
||||
' raw=open(f"/proc/{pid}/cmdline","rb").read()\n' +
|
||||
' args=[x.decode("utf-8","surrogateescape") for x in raw.split(b"\\0") if x]\n' +
|
||||
'except OSError:\n' +
|
||||
' try:\n' +
|
||||
' line=subprocess.check_output(["ps","-o","command=","-p",str(pid)],text=True).strip()\n' +
|
||||
' line=subprocess.check_output(["ps","-ww","-o","command=","-p",str(pid)],text=True).strip()\n' +
|
||||
' except subprocess.CalledProcessError:\n' +
|
||||
' # pid already gone — a dead process is FOREIGN, not a transport error\n' +
|
||||
' print("FOREIGN");sys.exit(0)\n' +
|
||||
@@ -420,9 +444,21 @@ async function pidIsOurDashboard(ssh, pid, spawnNonce, hermesPath = '') {
|
||||
'try:\n' +
|
||||
' serve=args.index("serve")\n' +
|
||||
' owner=args.index("--ssh-owner-nonce",serve+1)\n' +
|
||||
' direct=args[0]==expected\n' +
|
||||
' python_entry=len(args)>1 and args[1]==expected and os.path.basename(args[0]).startswith("python")\n' +
|
||||
' ok=(direct or python_entry) and "--isolated" in args[serve+1:] and args[owner+1]==nonce\n' +
|
||||
' token=args.index("--ssh-session-token-file",serve+1) if expected_token else -1\n' +
|
||||
' isolated=args.index("--isolated",serve+1)\n' +
|
||||
' profile_arg=args.index("--profile") if expected_profile else -1\n' +
|
||||
' serve_count=args.count("serve")\n' +
|
||||
' owner_count=args.count("--ssh-owner-nonce")\n' +
|
||||
' token_count=args.count("--ssh-session-token-file")\n' +
|
||||
' isolated_count=args.count("--isolated")\n' +
|
||||
' profile_count=args.count("--profile")\n' +
|
||||
' direct=args[0] in expected_entries\n' +
|
||||
' python_entry=len(args)>1 and args[1] in expected_entries and os.path.basename(args[0]).startswith("python")\n' +
|
||||
' token_ok=not expected_token or args[token+1]==expected_token\n' +
|
||||
' isolated_ok=isolated_count==1 and isolated>serve\n' +
|
||||
' profile_ok=(profile_count==1 and profile_arg<serve and args[profile_arg+1]==expected_profile) if expected_profile else profile_count==0\n' +
|
||||
' spawn_proof=bool(expected_token) and owner_count==1 and token_count==1 and token_ok and profile_ok\n' +
|
||||
' ok=(direct or python_entry or spawn_proof) and serve_count==1 and isolated_ok and owner_count==1 and args[owner+1]==nonce and token_ok and profile_ok\n' +
|
||||
'except (ValueError,IndexError):pass\n' +
|
||||
'print("OWNED" if ok else "FOREIGN")'
|
||||
|
||||
@@ -439,7 +475,19 @@ async function pidIsOurDashboard(ssh, pid, spawnNonce, hermesPath = '') {
|
||||
|
||||
// Kill the stale dashboard ONLY if provably ours, then drop the lockfile.
|
||||
async function cleanupStale(ssh, ownershipId, lock, pidAlive = true) {
|
||||
if (pidAlive && lock && (await pidIsOurDashboard(ssh, lock.pid, lock.spawnNonce, lock.hermesPath))) {
|
||||
if (
|
||||
pidAlive &&
|
||||
lock &&
|
||||
(await pidIsOurDashboard(
|
||||
ssh,
|
||||
lock.pid,
|
||||
lock.spawnNonce,
|
||||
lock.hermesPath,
|
||||
lock.hermesHome,
|
||||
ownershipId,
|
||||
lock.profile
|
||||
))
|
||||
) {
|
||||
try {
|
||||
const result = (
|
||||
await ssh.exec(
|
||||
@@ -554,8 +602,7 @@ async function spawnRemoteDashboard(ssh, { hermesPath, profile, token, ownership
|
||||
}
|
||||
|
||||
const spawnNonce = crypto.randomBytes(8).toString('hex')
|
||||
const tokenDir = ownershipDirectory(ownershipId)
|
||||
const tokenFilePath = `${tokenDir}/${spawnNonce}.token`
|
||||
const tokenFilePath = spawnTokenPath(ownershipId, spawnNonce)
|
||||
const logPath = spawnLogPath(ownershipId, spawnNonce)
|
||||
|
||||
const tokenUploadPy =
|
||||
@@ -741,7 +788,18 @@ async function connect(deps) {
|
||||
|
||||
if (lock) {
|
||||
const pidAlive = await remotePidAlive(ssh, lock.pid)
|
||||
const owned = pidAlive && (await pidIsOurDashboard(ssh, lock.pid, lock.spawnNonce, lock.hermesPath))
|
||||
|
||||
const owned =
|
||||
pidAlive &&
|
||||
(await pidIsOurDashboard(
|
||||
ssh,
|
||||
lock.pid,
|
||||
lock.spawnNonce,
|
||||
lock.hermesPath,
|
||||
lock.hermesHome,
|
||||
ownershipId,
|
||||
lock.profile
|
||||
))
|
||||
|
||||
const reusable =
|
||||
pidAlive &&
|
||||
@@ -936,6 +994,7 @@ export {
|
||||
shq,
|
||||
spawnLogPath,
|
||||
spawnRemoteDashboard,
|
||||
spawnTokenPath,
|
||||
SUPPORTED_REMOTE_OS,
|
||||
validateRemotePath,
|
||||
writeLockfile
|
||||
|
||||
@@ -59,6 +59,7 @@ import {
|
||||
$resumeExhaustedSessionId,
|
||||
$resumeFailedSessionId,
|
||||
$selectedStoredSessionId,
|
||||
$sessionResumeRequest,
|
||||
$sessions,
|
||||
sessionMatchesStoredId,
|
||||
sessionPinId,
|
||||
@@ -206,6 +207,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
|
||||
const freshDraftReady = useStore($freshDraftReady)
|
||||
const resumeFailedSessionId = useStore($resumeFailedSessionId)
|
||||
const resumeExhaustedSessionId = useStore($resumeExhaustedSessionId)
|
||||
const sessionResumeRequest = useStore($sessionResumeRequest)
|
||||
const selectedStoredSessionId = useStore($selectedStoredSessionId)
|
||||
const messagingSessions = useStore($messagingSessions)
|
||||
const sessions = useStore($sessions)
|
||||
@@ -685,6 +687,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
|
||||
resumeSession,
|
||||
resumeFailedSessionId,
|
||||
resumeExhaustedSessionId,
|
||||
sessionResumeRequest,
|
||||
routedSessionId,
|
||||
runtimeIdByStoredSessionIdRef,
|
||||
selectedStoredSessionId,
|
||||
|
||||
@@ -120,6 +120,14 @@ describe('openSession', () => {
|
||||
expect(navigate).toHaveBeenCalledWith('/c/s1')
|
||||
})
|
||||
|
||||
it('main routes to the workspace even when the session is already open as a tile', () => {
|
||||
focusOpenSession.mockReturnValue('tile')
|
||||
openSession('s1', navigate, 'main')
|
||||
expect(navigate).toHaveBeenCalledWith('/c/s1')
|
||||
expect(focusOpenSession).not.toHaveBeenCalled()
|
||||
expect(openSessionTile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('tab focuses an existing open session instead of stacking another', () => {
|
||||
focusOpenSession.mockReturnValue('tile')
|
||||
openSession('s1', navigate, 'tab')
|
||||
|
||||
@@ -25,7 +25,7 @@ import { canOpenSessionWindow, openSessionInNewWindow } from '@/store/windows'
|
||||
|
||||
import { $workspaceIsPage, sessionRoute } from './routes'
|
||||
|
||||
export type OpenSessionIntent = 'in-place' | 'stack' | 'tab' | 'window'
|
||||
export type OpenSessionIntent = 'in-place' | 'main' | 'stack' | 'tab' | 'window'
|
||||
|
||||
export type OpenSessionNavigate = (to: string, options?: { replace?: boolean }) => void
|
||||
|
||||
@@ -97,6 +97,15 @@ export function openSession(
|
||||
resolved = 'tab'
|
||||
}
|
||||
|
||||
if (resolved === 'main') {
|
||||
// Canonical relationship chats explicitly own the main workspace. Route
|
||||
// even when the session is already open as a tile; resumeSession removes
|
||||
// that redundant tile when the main surface binds.
|
||||
navigate(sessionRoute(storedSessionId))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// A `stack` open arrives from outside the workspace, so unlike a sidebar
|
||||
// click it can't assume main is spendable: it behaves like `tab`, except main
|
||||
// IS fair game while it's only a blank draft, and an already-open blank draft
|
||||
|
||||
@@ -23,6 +23,7 @@ interface HarnessProps {
|
||||
resumeSession: (sessionId: string, focus: boolean) => Promise<unknown>
|
||||
resumeFailedSessionId?: null | string
|
||||
resumeExhaustedSessionId?: null | string
|
||||
sessionResumeRequest?: null | { sequence: number; sessionId: string }
|
||||
routedSessionId: null | string
|
||||
runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>
|
||||
selectedStoredSessionId: null | string
|
||||
@@ -30,8 +31,13 @@ interface HarnessProps {
|
||||
startFreshSessionDraft: (focus: boolean) => unknown
|
||||
}
|
||||
|
||||
function RouteResumeHarness({ resumeFailedSessionId = null, resumeExhaustedSessionId = null, ...props }: HarnessProps) {
|
||||
useRouteResume({ ...props, resumeExhaustedSessionId, resumeFailedSessionId })
|
||||
function RouteResumeHarness({
|
||||
resumeFailedSessionId = null,
|
||||
resumeExhaustedSessionId = null,
|
||||
sessionResumeRequest = null,
|
||||
...props
|
||||
}: HarnessProps) {
|
||||
useRouteResume({ ...props, resumeExhaustedSessionId, resumeFailedSessionId, sessionResumeRequest })
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -304,6 +310,44 @@ describe('useRouteResume', () => {
|
||||
expect(resumeSession).toHaveBeenCalledTimes(1)
|
||||
expect(resumeSession).toHaveBeenCalledWith('session-1', true)
|
||||
})
|
||||
|
||||
it('re-resumes an already-active same route when a plugin explicitly requests hydration', () => {
|
||||
const resumeSession = vi.fn(async () => undefined)
|
||||
const startFreshSessionDraft = vi.fn()
|
||||
const activeSessionIdRef: MutableRefObject<null | string> = { current: 'runtime-1' }
|
||||
const creatingSessionRef = { current: false }
|
||||
const runtimeIdByStoredSessionIdRef = { current: new Map([['session-1', 'runtime-1']]) }
|
||||
const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'session-1' }
|
||||
|
||||
const props = {
|
||||
activeSessionId: 'runtime-1',
|
||||
activeSessionIdRef,
|
||||
creatingSessionRef,
|
||||
currentView: 'chat',
|
||||
freshDraftReady: false,
|
||||
gatewayState: 'open',
|
||||
locationPathname: '/session-1',
|
||||
resumeSession,
|
||||
routedSessionId: 'session-1',
|
||||
runtimeIdByStoredSessionIdRef,
|
||||
selectedStoredSessionId: 'session-1',
|
||||
selectedStoredSessionIdRef,
|
||||
startFreshSessionDraft
|
||||
}
|
||||
|
||||
const { rerender } = render(<RouteResumeHarness {...props} />)
|
||||
expect(resumeSession).not.toHaveBeenCalled()
|
||||
|
||||
rerender(
|
||||
<RouteResumeHarness
|
||||
{...props}
|
||||
sessionResumeRequest={{ sequence: 1, sessionId: 'session-1' }}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(resumeSession).toHaveBeenCalledTimes(1)
|
||||
expect(resumeSession).toHaveBeenCalledWith('session-1', true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useRouteResume bounded auto-retry after a failed resume', () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { type MutableRefObject, useEffect, useRef } from 'react'
|
||||
|
||||
import { isNewChatRoute } from '@/app/routes'
|
||||
import { setResumeExhaustedSessionId } from '@/store/session'
|
||||
import { type SessionResumeRequest, setResumeExhaustedSessionId } from '@/store/session'
|
||||
import { markSelectionRestore } from '@/store/session-states'
|
||||
|
||||
interface RouteResumeOptions {
|
||||
@@ -24,6 +24,7 @@ interface RouteResumeOptions {
|
||||
// armed->cleared edge is an unambiguous "give me a fresh backoff cycle"
|
||||
// signal the effect below uses to reset the attempt counter.
|
||||
resumeExhaustedSessionId: string | null
|
||||
sessionResumeRequest: SessionResumeRequest | null
|
||||
routedSessionId: string | null
|
||||
runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>
|
||||
selectedStoredSessionId: string | null
|
||||
@@ -77,6 +78,7 @@ export function useRouteResume({
|
||||
resumeSession,
|
||||
resumeFailedSessionId,
|
||||
resumeExhaustedSessionId,
|
||||
sessionResumeRequest,
|
||||
routedSessionId,
|
||||
runtimeIdByStoredSessionIdRef,
|
||||
selectedStoredSessionId,
|
||||
@@ -102,6 +104,7 @@ export function useRouteResume({
|
||||
// for a fresh backoff cycle on the SAME session (the auto-retry loop itself
|
||||
// never touches this latch, so it can't spuriously trigger the reset).
|
||||
const prevResumeExhaustedRef = useRef<string | null>(null)
|
||||
const handledResumeRequestRef = useRef(0)
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
|
||||
useEffect(() => {
|
||||
@@ -128,6 +131,10 @@ export function useRouteResume({
|
||||
Boolean(cachedRuntime) &&
|
||||
cachedRuntime === activeSessionIdRef.current
|
||||
|
||||
const explicitlyRequested =
|
||||
sessionResumeRequest?.sessionId === routedSessionId &&
|
||||
sessionResumeRequest.sequence > handledResumeRequestRef.current
|
||||
|
||||
// Self-heal a desynced view: the route points at a session that isn't the
|
||||
// loaded one. A create/stream race can leave selected/active null while
|
||||
// the route stays on /:sid (symptom: brand-new chat shows "Thinking" then
|
||||
@@ -148,13 +155,18 @@ export function useRouteResume({
|
||||
// we're stranded on a routed session that never loaded. The first two
|
||||
// guard against a transient /:sid re-resume during "new chat" state clears
|
||||
// before the pathname updates from /:sid -> /.
|
||||
const shouldResume = pathnameChanged || gatewayBecameOpen || stuckOnRoutedSession
|
||||
const shouldResume = pathnameChanged || gatewayBecameOpen || stuckOnRoutedSession || explicitlyRequested
|
||||
|
||||
// On a reconnect (gatewayBecameOpen) re-resume even when the route looks
|
||||
// `alreadyActive`: the cached runtime id can be stale once the gateway
|
||||
// rebinds/reaps the session on its side, and trusting it strands Desktop on
|
||||
// a dead id ("session not found"). Otherwise keep skipping when already active.
|
||||
if ((gatewayBecameOpen || !alreadyActive) && shouldResume && !creatingSessionRef.current) {
|
||||
// a dead id ("session not found"). An explicit plugin reselect similarly
|
||||
// bypasses the warm-id skip when the focused transcript disappeared.
|
||||
if ((gatewayBecameOpen || explicitlyRequested || !alreadyActive) && shouldResume && !creatingSessionRef.current) {
|
||||
if (explicitlyRequested) {
|
||||
handledResumeRequestRef.current = sessionResumeRequest.sequence
|
||||
}
|
||||
|
||||
// The window's FIRST resume re-attaches the pre-reload route rather
|
||||
// than navigating anywhere, so the selection listener must not home
|
||||
// focus/tabs to the workspace over the persisted layout (see
|
||||
@@ -190,6 +202,7 @@ export function useRouteResume({
|
||||
gatewayState,
|
||||
locationPathname,
|
||||
resumeSession,
|
||||
sessionResumeRequest,
|
||||
routedSessionId,
|
||||
runtimeIdByStoredSessionIdRef,
|
||||
selectedStoredSessionId,
|
||||
|
||||
@@ -2903,6 +2903,26 @@ function showsHandle(name, meta, bot) {
|
||||
// In-flight creations, keyed by bot name — double-clicking a row must not
|
||||
// mint two canonical chats.
|
||||
const canonicalCreations = new Map()
|
||||
let botOpenGeneration = 0
|
||||
|
||||
async function openStoredBotChat(name, storedId, summary) {
|
||||
if (!storedId || typeof host.openSession !== 'function') {
|
||||
throw new Error('This Hermes Desktop version cannot open stored sessions')
|
||||
}
|
||||
|
||||
const hasAuthoritativeCount =
|
||||
typeof summary?.message_count === 'number' && Number.isFinite(summary.message_count)
|
||||
const expectHistory = hasAuthoritativeCount ? summary.message_count > 0 : true
|
||||
|
||||
await host.openSession(storedId, {
|
||||
profile: name,
|
||||
intent: 'main',
|
||||
awaitHydration: true,
|
||||
expectHistory
|
||||
})
|
||||
|
||||
return storedId
|
||||
}
|
||||
|
||||
/** Create the bot's ONE forever chat: a real session opened with a kickoff
|
||||
* message (the gateway prunes zero-message sessions, so the chat is born
|
||||
@@ -2938,7 +2958,7 @@ function createCanonicalChat(name) {
|
||||
|
||||
if (sid && typeof host.openSession === 'function') {
|
||||
try {
|
||||
await host.openSession(sid, { profile: name })
|
||||
await host.openSession(sid, { profile: name, intent: 'main' })
|
||||
opened = true
|
||||
} catch {
|
||||
// The stored row may not exist until the kickoff persists it. Retry
|
||||
@@ -2953,7 +2973,7 @@ function createCanonicalChat(name) {
|
||||
await host.request('prompt.submit', { session_id: runtime, text: 'Hey, tell me about yourself!' })
|
||||
|
||||
if (!opened && sid && typeof host.openSession === 'function') {
|
||||
await host.openSession(sid, { profile: name })
|
||||
await host.openSession(sid, { profile: name, intent: 'main' })
|
||||
}
|
||||
} catch {
|
||||
// The chat already exists. Keep the pin so the next click
|
||||
@@ -2987,13 +3007,9 @@ async function openBotCanonicalChat(name, pinned, history) {
|
||||
// Grandfather: adopt the conversation the row already previews.
|
||||
const adoptId = history?.id
|
||||
if (adoptId && typeof host.openSession === 'function') {
|
||||
try {
|
||||
await host.openSession(adoptId, { profile: name })
|
||||
saveBotMeta(name, { chat: adoptId })
|
||||
return adoptId
|
||||
} catch {
|
||||
// Adoption raced a vanishing session — fall through to creation.
|
||||
}
|
||||
await openStoredBotChat(name, adoptId, history)
|
||||
saveBotMeta(name, { chat: adoptId })
|
||||
return adoptId
|
||||
}
|
||||
return createCanonicalChat(name)
|
||||
}
|
||||
@@ -3019,27 +3035,22 @@ async function openBotCanonicalChat(name, pinned, history) {
|
||||
|
||||
if (lookupFailed) {
|
||||
// Transient gateway state (or an older backend): the pin is innocent
|
||||
// until proven guilty — try it as-is, and only a rejected open clears.
|
||||
try {
|
||||
await host.openSession(pinned, { profile: name })
|
||||
return pinned
|
||||
} catch {
|
||||
saveBotMeta(name, { chat: null })
|
||||
return createCanonicalChat(name)
|
||||
}
|
||||
// until proven guilty — try it as-is. A rejected open is still ambiguous:
|
||||
// it can be the same reconnect/hydration outage that broke this lookup, so
|
||||
// preserve the forever-chat pin and surface Retry instead of forking it.
|
||||
return openStoredBotChat(name, pinned, history)
|
||||
}
|
||||
|
||||
if (preferred) {
|
||||
try {
|
||||
await host.openSession(preferred.resolved_id || preferred.id, { profile: name })
|
||||
await openStoredBotChat(name, preferred.resolved_id || preferred.id, preferred)
|
||||
return pinned
|
||||
} catch (error) {
|
||||
// The precise lookup JUST confirmed this session exists, so a failed
|
||||
// open is transient (reconnect, backend restart). Clearing the pin or
|
||||
// minting a replacement here would fork the bot's forever-chat on
|
||||
// every hiccup — report and keep everything as it is.
|
||||
host.notifyError?.(error, `Could not open ${name}'s chat — try again`)
|
||||
return pinned
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3047,13 +3058,9 @@ async function openBotCanonicalChat(name, pinned, history) {
|
||||
// recovery): re-anchor on the previewed session when there is one.
|
||||
const recoveryId = history?.id
|
||||
if (recoveryId && typeof host.openSession === 'function') {
|
||||
try {
|
||||
await host.openSession(recoveryId, { profile: name })
|
||||
saveBotMeta(name, { chat: recoveryId })
|
||||
return recoveryId
|
||||
} catch {
|
||||
// Fall through to a fresh chat.
|
||||
}
|
||||
await openStoredBotChat(name, recoveryId, history)
|
||||
saveBotMeta(name, { chat: recoveryId })
|
||||
return recoveryId
|
||||
}
|
||||
saveBotMeta(name, { chat: null })
|
||||
return createCanonicalChat(name)
|
||||
@@ -4358,6 +4365,7 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {
|
||||
}
|
||||
|
||||
const open = async () => {
|
||||
const generation = ++botOpenGeneration
|
||||
haptic('tap')
|
||||
$selectedBot.set(bot.name)
|
||||
|
||||
@@ -4389,14 +4397,26 @@ function BotRow({ bot, onDelete, onEdit, onGroup }) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const id = await openBotCanonicalChat(bot.name, pinnedChat, bot.last_session)
|
||||
if (generation !== botOpenGeneration) {
|
||||
return
|
||||
}
|
||||
|
||||
if (id) {
|
||||
try {
|
||||
const id = await openBotCanonicalChat(bot.name, pinnedChat, previewSession)
|
||||
|
||||
if (generation === botOpenGeneration && id) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the older-gateway draft below.
|
||||
} catch (error) {
|
||||
if (generation === botOpenGeneration) {
|
||||
host.notifyError?.(error, `Could not open ${displayName(bot, meta)}'s chat — try again`)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (generation !== botOpenGeneration) {
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof host.newChat === 'function') {
|
||||
@@ -8896,6 +8916,7 @@ function BotsPane() {
|
||||
gatewayState,
|
||||
metaByName: allMeta,
|
||||
onOpen: bot => {
|
||||
const generation = ++botOpenGeneration
|
||||
haptic('tap')
|
||||
$selectedBot.set(bot.name)
|
||||
|
||||
@@ -8926,14 +8947,30 @@ function BotsPane() {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const id = await openBotCanonicalChat(bot.name, pinnedChat, bot.last_session)
|
||||
if (generation !== botOpenGeneration) {
|
||||
return
|
||||
}
|
||||
|
||||
if (id) {
|
||||
try {
|
||||
const id = await openBotCanonicalChat(
|
||||
bot.name,
|
||||
pinnedChat,
|
||||
bot.preferred_session || bot.last_session
|
||||
)
|
||||
|
||||
if (generation === botOpenGeneration && id) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the older-gateway draft below.
|
||||
} catch (error) {
|
||||
if (generation === botOpenGeneration) {
|
||||
host.notifyError?.(error, `Could not open ${displayName(bot)}'s chat — try again`)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (generation !== botOpenGeneration) {
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof host.newChat === 'function') {
|
||||
|
||||
@@ -94,5 +94,5 @@ test('ActiveNowStrip renders above the roster, is a live region, and is click-ac
|
||||
assert.match(source, /jsx\(BotFace,\s*\{[\s\S]*?mood: 'work'/)
|
||||
assert.match(source, /let pinnedChat = botRosterMeta\(bot, allMeta\)\?\.chat/)
|
||||
assert.match(source, /await prepareBotSource\(bot, pinnedChat\)/)
|
||||
assert.match(source, /openBotCanonicalChat\(bot\.name, pinnedChat, bot\.last_session\)/)
|
||||
assert.match(source, /bot\.preferred_session \|\| bot\.last_session/)
|
||||
})
|
||||
|
||||
@@ -64,7 +64,7 @@ test('grandfather: no pin + no history keeps the creation flow', async () => {
|
||||
assert.equal(runtime.requests.some(r => r.method === 'session.create'), true)
|
||||
})
|
||||
|
||||
test('grandfather: adoption open failure falls back to creation without pinning', async () => {
|
||||
test('grandfather: adoption hydration failure surfaces without forking a replacement chat', async () => {
|
||||
const runtime = loadOpenPath({
|
||||
openSession: async id => {
|
||||
if (id === 'hist-1') throw new Error('session vanished')
|
||||
@@ -73,18 +73,19 @@ test('grandfather: adoption open failure falls back to creation without pinning'
|
||||
method === 'session.create' ? { stored_session_id: 'stored-2', session_id: 'runtime-2' } : {}
|
||||
})
|
||||
|
||||
const result = await runtime.openBotCanonicalChat('ops', null, HISTORY)
|
||||
|
||||
assert.equal(result, 'stored-2')
|
||||
await assert.rejects(runtime.openBotCanonicalChat('ops', null, HISTORY), /session vanished/)
|
||||
assert.equal(runtime.saved.some(s => s.patch?.chat === 'hist-1'), false,
|
||||
'a failed adoption must not persist the dead id as the pin')
|
||||
assert.equal(runtime.requests.some(r => r.method === 'session.create'), false,
|
||||
'a transient hydration failure must not fork the canonical chat')
|
||||
})
|
||||
|
||||
// ── precise pin verification (no session.list pagination/hidden semantics) ─
|
||||
|
||||
test('pin: preferred_session present opens the resolved session and keeps the pin', async () => {
|
||||
const opened = []
|
||||
const runtime = loadOpenPath({
|
||||
openSession: async () => undefined,
|
||||
openSession: async (id, options) => { opened.push({ id, options }) },
|
||||
request: async method => {
|
||||
if (method === 'profiles.list') {
|
||||
return {
|
||||
@@ -104,6 +105,15 @@ test('pin: preferred_session present opens the resolved session and keeps the pi
|
||||
const result = await runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY)
|
||||
|
||||
assert.equal(result, 'pin-1')
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(opened)), [{
|
||||
id: 'pin-1',
|
||||
options: {
|
||||
profile: 'ops',
|
||||
intent: 'main',
|
||||
awaitHydration: true,
|
||||
expectHistory: true
|
||||
}
|
||||
}])
|
||||
assert.equal(runtime.saved.length, 0, 'a live pin must not be rewritten')
|
||||
assert.equal(runtime.requests.some(r => r.method === 'session.create'), false)
|
||||
// The pin is verified through the precise resolver, never session.list.
|
||||
@@ -178,8 +188,7 @@ test('pin: gone pin + no history clears the pin and creates', async () => {
|
||||
])
|
||||
})
|
||||
|
||||
test('pin: precise hit but failed open keeps the pin and reports', async () => {
|
||||
const notes = []
|
||||
test('pin: precise hit but failed hydration keeps the pin and surfaces the failure', async () => {
|
||||
const runtime = loadOpenPath({
|
||||
openSession: async () => { throw new Error('socket hiccup') },
|
||||
request: async method => {
|
||||
@@ -197,15 +206,11 @@ test('pin: precise hit but failed open keeps the pin and reports', async () => {
|
||||
return {}
|
||||
}
|
||||
})
|
||||
runtime.host.notifyError = (error, title) => notes.push({ error: String(error), title })
|
||||
|
||||
const result = await runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY)
|
||||
|
||||
assert.equal(result, 'pin-1')
|
||||
await assert.rejects(runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY), /socket hiccup/)
|
||||
assert.equal(runtime.saved.length, 0, 'a confirmed-live pin must survive a transient open failure')
|
||||
assert.equal(runtime.requests.some(r => r.method === 'session.create'), false,
|
||||
'must not fork the forever-chat on a hiccup')
|
||||
assert.equal(notes.length, 1, 'the user gets told the open failed')
|
||||
})
|
||||
|
||||
// ── transient failures must never destroy the pin ──────────────────────────
|
||||
@@ -227,10 +232,8 @@ test('transient: profiles.list failure keeps the pin when the direct open works'
|
||||
'a hiccup must not mint a replacement chat')
|
||||
})
|
||||
|
||||
test('transient: profiles.list failure + failed direct open clears pin and creates', async () => {
|
||||
test('transient: profiles.list failure + failed direct open preserves pin and surfaces Retry', async () => {
|
||||
const runtime = loadOpenPath({
|
||||
// Only the stale PIN's open is rejected; the creation flow's own
|
||||
// openSession calls must succeed.
|
||||
openSession: async id => {
|
||||
if (id === 'pin-1') throw new Error('resume rejected')
|
||||
},
|
||||
@@ -241,13 +244,10 @@ test('transient: profiles.list failure + failed direct open clears pin and creat
|
||||
}
|
||||
})
|
||||
|
||||
const result = await runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY)
|
||||
|
||||
assert.equal(result, 'stored-4')
|
||||
assert.deepEqual(runtime.saved, [
|
||||
{ name: 'ops', patch: { chat: null } },
|
||||
{ name: 'ops', patch: { chat: 'stored-4' } }
|
||||
])
|
||||
await assert.rejects(runtime.openBotCanonicalChat('ops', 'pin-1', HISTORY), /resume rejected/)
|
||||
assert.deepEqual(runtime.saved, [], 'an inconclusive outage must never clear the canonical pin')
|
||||
assert.equal(runtime.requests.some(r => r.method === 'session.create'), false,
|
||||
'an inconclusive outage must never fork the canonical chat')
|
||||
})
|
||||
|
||||
// ── preferred_session_ids request shaping (pure helper) ────────────────────
|
||||
|
||||
@@ -46,6 +46,7 @@ function renderBotRow(input = 'alpha') {
|
||||
botAppearance: () => ({ shape: 'round', color: '#000', image: null }),
|
||||
botGroups: () => [],
|
||||
botHandle: value => value,
|
||||
botOpenGeneration: 0,
|
||||
botRosterMeta: (_bot, metaByName) => metaByName?.[_bot.name] ?? null,
|
||||
cn: (...values) => values.filter(Boolean).join(' '),
|
||||
createCanonicalChat: async () => null,
|
||||
@@ -172,6 +173,7 @@ test('behavior: remote default does not open this-device chat when the source di
|
||||
botAppearance: () => ({ shape: 'round', color: '#000', image: null }),
|
||||
botGroups: () => [],
|
||||
botHandle: value => value,
|
||||
botOpenGeneration: 0,
|
||||
botRosterMeta: () => null,
|
||||
cn: (...values) => values.filter(Boolean).join(' '),
|
||||
createCanonicalChat: async () => null,
|
||||
|
||||
@@ -126,8 +126,8 @@ test('source contract: bot rows and Active now activate the owner before canonic
|
||||
assert.match(pluginSource, /async function prepareBotSource\(bot, pinnedChat\)/)
|
||||
assert.match(pluginSource, /await host\.ensureAgent\(bot\.connectionId, bot\.name\)/)
|
||||
assert.match(pluginSource, /host\.request\('profiles\.list', \{\}\)/)
|
||||
assert.match(pluginSource, /const open = async \(\) => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat, bot\.last_session\)/)
|
||||
assert.match(pluginSource, /onOpen: bot => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat, bot\.last_session\)/)
|
||||
assert.match(pluginSource, /const open = async \(\) => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*openBotCanonicalChat\(bot\.name, pinnedChat, previewSession\)/)
|
||||
assert.match(pluginSource, /onOpen: bot => \{[\s\S]*await prepareBotSource\(bot, pinnedChat\)[\s\S]*bot\.preferred_session \|\| bot\.last_session/)
|
||||
assert.match(pluginSource, /openBotSessionsWorkspace\(bot\)[\s\S]*children: 'Sessions'/)
|
||||
})
|
||||
|
||||
|
||||
+156
-14
@@ -46,6 +46,7 @@ import {
|
||||
import { notify, notifyError } from '@/store/notifications'
|
||||
import {
|
||||
$activeGatewayProfile,
|
||||
$gatewaySwapTarget,
|
||||
$profiles,
|
||||
ensureGatewayAgent,
|
||||
ensureGatewayProfile,
|
||||
@@ -62,7 +63,10 @@ import {
|
||||
$currentCwd,
|
||||
$currentModel,
|
||||
$gatewayState,
|
||||
$selectedStoredSessionId
|
||||
$messages,
|
||||
$selectedStoredSessionId,
|
||||
requestSessionResume,
|
||||
setResumeExhaustedSessionId
|
||||
} from '@/store/session'
|
||||
import {
|
||||
$focusedRuntimeId,
|
||||
@@ -194,6 +198,88 @@ const $activeConnectionId = computed($connection, connection => {
|
||||
return connection.mode === 'local' ? 'local' : null
|
||||
})
|
||||
|
||||
const DEFAULT_SESSION_HYDRATION_TIMEOUT_MS = 20_000
|
||||
let openSessionGeneration = 0
|
||||
|
||||
interface PluginOpenSessionOptions {
|
||||
awaitHydration?: boolean
|
||||
expectHistory?: boolean
|
||||
hydrationTimeoutMs?: number
|
||||
intent?: OpenSessionIntent
|
||||
keepAllProfilesScope?: boolean
|
||||
profile?: null | string
|
||||
}
|
||||
|
||||
function waitForFocusedSessionHydration({
|
||||
expectHistory,
|
||||
generation,
|
||||
profile,
|
||||
storedSessionId,
|
||||
timeoutMs
|
||||
}: {
|
||||
expectHistory: boolean
|
||||
generation: number
|
||||
profile: string
|
||||
storedSessionId: string
|
||||
timeoutMs: number
|
||||
}): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false
|
||||
const unbinds: Array<() => void> = []
|
||||
let timer: number | undefined
|
||||
|
||||
const finish = (error?: Error) => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
|
||||
settled = true
|
||||
|
||||
if (timer !== undefined) {
|
||||
window.clearTimeout(timer)
|
||||
}
|
||||
|
||||
for (const unbind of unbinds) {
|
||||
unbind()
|
||||
}
|
||||
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
}
|
||||
|
||||
const check = () => {
|
||||
if (generation !== openSessionGeneration) {
|
||||
finish(new Error('Session open was superseded by a newer selection.'))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const profileMatches = normalizeProfileKey($activeGatewayProfile.get()) === profile
|
||||
const sessionMatches = $selectedStoredSessionId.get() === storedSessionId
|
||||
const runtimeReady = Boolean($activeSessionId.get())
|
||||
const historyReady = !expectHistory || Boolean($messages.get().length)
|
||||
|
||||
if (profileMatches && sessionMatches && runtimeReady && historyReady) {
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
unbinds.push($activeGatewayProfile.listen(check))
|
||||
unbinds.push($selectedStoredSessionId.listen(check))
|
||||
unbinds.push($activeSessionId.listen(check))
|
||||
unbinds.push($messages.listen(check))
|
||||
|
||||
timer = window.setTimeout(() => {
|
||||
finish(new Error(`Timed out loading ${profile}'s session history.`))
|
||||
}, timeoutMs)
|
||||
|
||||
check()
|
||||
})
|
||||
}
|
||||
|
||||
export const host = {
|
||||
state: {
|
||||
/** Runtime id of the active chat session (null on a fresh draft). */
|
||||
@@ -375,9 +461,12 @@ export const host = {
|
||||
|
||||
openSession: async (
|
||||
storedSessionId: string,
|
||||
options: { intent?: OpenSessionIntent; keepAllProfilesScope?: boolean; profile?: null | string } = {}
|
||||
options: PluginOpenSessionOptions = {}
|
||||
): Promise<void> => {
|
||||
const generation = ++openSessionGeneration
|
||||
const profile = (options.profile ?? '').trim()
|
||||
const targetProfile = normalizeProfileKey(profile || $activeGatewayProfile.get())
|
||||
const expectHistory = options.expectHistory ?? false
|
||||
|
||||
if (profile && profile !== $activeGatewayProfile.get()) {
|
||||
await ensureGatewayProfile(profile)
|
||||
@@ -387,19 +476,72 @@ export const host = {
|
||||
}
|
||||
}
|
||||
|
||||
openSession(
|
||||
storedSessionId,
|
||||
(to: string, opts?: { replace?: boolean }) => {
|
||||
const target = to.startsWith('#') ? to : `#${to}`
|
||||
if (generation !== openSessionGeneration) {
|
||||
throw new Error('Session open was superseded by a newer selection.')
|
||||
}
|
||||
|
||||
if (opts?.replace) {
|
||||
window.location.replace(target)
|
||||
} else {
|
||||
window.location.hash = target
|
||||
}
|
||||
},
|
||||
options.intent ?? 'in-place'
|
||||
)
|
||||
if (options.awaitHydration) {
|
||||
// Keep the target-specific overlay visible through transcript hydration,
|
||||
// not merely through the gateway/profile activation that precedes it.
|
||||
$gatewaySwapTarget.set(targetProfile)
|
||||
}
|
||||
|
||||
const mainMessages = $messages.get()
|
||||
|
||||
const needsExplicitResume =
|
||||
options.awaitHydration &&
|
||||
$selectedStoredSessionId.get() === storedSessionId &&
|
||||
(!$activeSessionId.get() || (expectHistory && !mainMessages.length))
|
||||
|
||||
try {
|
||||
openSession(
|
||||
storedSessionId,
|
||||
(to: string, opts?: { replace?: boolean }) => {
|
||||
const target = to.startsWith('#') ? to : `#${to}`
|
||||
|
||||
if (opts?.replace) {
|
||||
window.location.replace(target)
|
||||
} else {
|
||||
window.location.hash = target
|
||||
}
|
||||
},
|
||||
options.intent ?? 'in-place'
|
||||
)
|
||||
|
||||
if (needsExplicitResume) {
|
||||
// Re-selecting a routed Bot Chat normally focuses the existing main
|
||||
// surface without changing the URL. If that surface lost its runtime or
|
||||
// transcript, the route effect otherwise gets no signal to re-resume it.
|
||||
requestSessionResume(storedSessionId)
|
||||
}
|
||||
|
||||
if (options.awaitHydration) {
|
||||
await waitForFocusedSessionHydration({
|
||||
expectHistory,
|
||||
generation,
|
||||
profile: targetProfile,
|
||||
storedSessionId,
|
||||
timeoutMs: Math.max(1, options.hydrationTimeoutMs ?? DEFAULT_SESSION_HYDRATION_TIMEOUT_MS)
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
if (
|
||||
options.awaitHydration &&
|
||||
generation === openSessionGeneration &&
|
||||
error instanceof Error &&
|
||||
error.message.startsWith('Timed out loading ')
|
||||
) {
|
||||
// Reuse the core stranded-session surface: it renders the explicit
|
||||
// error and Retry button, and the normal resume path clears the latch.
|
||||
setResumeExhaustedSessionId(storedSessionId)
|
||||
}
|
||||
|
||||
throw error
|
||||
} finally {
|
||||
if (options.awaitHydration && generation === openSessionGeneration) {
|
||||
$gatewaySwapTarget.set(null)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/** Open (or re-front) a plugin-rendered MAIN-AREA workspace tile — the same
|
||||
|
||||
@@ -26,7 +26,10 @@ vi.mock('@/store/session', async () => {
|
||||
$currentCwd: atom(''),
|
||||
$currentModel: atom(''),
|
||||
$gatewayState: atom('open'),
|
||||
$selectedStoredSessionId: atom(null)
|
||||
$messages: atom([]),
|
||||
$selectedStoredSessionId: atom(null),
|
||||
requestSessionResume: vi.fn(),
|
||||
setResumeExhaustedSessionId: vi.fn()
|
||||
}
|
||||
})
|
||||
vi.mock('@/store/session-states', async () => {
|
||||
@@ -56,6 +59,7 @@ vi.mock('@/store/profile', async () => {
|
||||
|
||||
return {
|
||||
$activeGatewayProfile: atom('remote-worker'),
|
||||
$gatewaySwapTarget: atom(null),
|
||||
$profiles: profiles,
|
||||
ensureGatewayAgent: vi.fn(),
|
||||
ensureGatewayProfile: vi.fn(),
|
||||
@@ -93,9 +97,29 @@ vi.mock('@/store/gateway', async () => {
|
||||
})
|
||||
|
||||
const { host } = await import('./index')
|
||||
const { openSession: openSessionCore } = await import('@/app/open-session')
|
||||
const { deleteProfile } = await import('@/hermes')
|
||||
const { requestGatewayForAgent, requestGatewayForProfile, retireLocalProfileGateways } = await import('@/store/gateway')
|
||||
const { $profiles, refreshProfiles } = await import('@/store/profile')
|
||||
|
||||
const {
|
||||
$activeGatewayProfile,
|
||||
$gatewaySwapTarget,
|
||||
$profiles,
|
||||
ensureGatewayProfile,
|
||||
refreshProfiles
|
||||
} = await import('@/store/profile')
|
||||
|
||||
const { $focusedRuntimeId, $focusedSessionState, $focusedStoredSessionId } = await import('@/store/session-states')
|
||||
|
||||
const {
|
||||
$activeSessionId,
|
||||
$messages,
|
||||
$selectedStoredSessionId,
|
||||
requestSessionResume,
|
||||
setResumeExhaustedSessionId
|
||||
} = await import('@/store/session')
|
||||
|
||||
const setMockAtom = <T>(store: unknown, value: T) => (store as { set(next: T): void }).set(value)
|
||||
|
||||
const profile = (name: string): ProfileInfo => ({
|
||||
has_env: false,
|
||||
@@ -109,6 +133,14 @@ const profile = (name: string): ProfileInfo => ({
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
$activeGatewayProfile.set('remote-worker')
|
||||
$gatewaySwapTarget.set(null)
|
||||
setMockAtom($focusedRuntimeId, null)
|
||||
setMockAtom($focusedStoredSessionId, null)
|
||||
setMockAtom($focusedSessionState, null)
|
||||
setMockAtom($activeSessionId, null)
|
||||
setMockAtom($selectedStoredSessionId, null)
|
||||
setMockAtom($messages, [])
|
||||
$profiles.set([profile('cached-only')])
|
||||
delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
|
||||
})
|
||||
@@ -262,3 +294,146 @@ describe('connection-aware plugin host APIs', () => {
|
||||
expect(requestGatewayForProfile).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('profile-aware plugin session opens', () => {
|
||||
it('waits until the target Bot Chat runtime and history are on main before resolving', async () => {
|
||||
vi.mocked(ensureGatewayProfile).mockImplementationOnce(async (target: null | string | undefined) => {
|
||||
$activeGatewayProfile.set(target || 'default')
|
||||
})
|
||||
|
||||
let resolved = false
|
||||
|
||||
const opening = host
|
||||
.openSession('bot-chat', {
|
||||
profile: 'hyoseob',
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1_000
|
||||
})
|
||||
.then(() => {
|
||||
resolved = true
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
|
||||
expect(openSessionCore).toHaveBeenCalledWith('bot-chat', expect.any(Function), 'in-place')
|
||||
expect(resolved).toBe(false)
|
||||
expect($gatewaySwapTarget.get()).toBe('hyoseob')
|
||||
|
||||
setMockAtom($focusedStoredSessionId, 'bot-chat')
|
||||
setMockAtom($focusedRuntimeId, 'runtime-tile')
|
||||
setMockAtom($focusedSessionState, {
|
||||
messages: [{ id: 'tile-history', parts: [], role: 'assistant' }],
|
||||
storedSessionId: 'bot-chat'
|
||||
} as never)
|
||||
|
||||
await Promise.resolve()
|
||||
expect(resolved).toBe(false)
|
||||
|
||||
setMockAtom($selectedStoredSessionId, 'bot-chat')
|
||||
setMockAtom($activeSessionId, 'runtime-hyoseob')
|
||||
setMockAtom($messages, [])
|
||||
|
||||
await Promise.resolve()
|
||||
expect(resolved).toBe(false)
|
||||
|
||||
setMockAtom($messages, [{ id: 'history-1', parts: [], role: 'user' }] as never)
|
||||
|
||||
await opening
|
||||
expect(resolved).toBe(true)
|
||||
expect($gatewaySwapTarget.get()).toBeNull()
|
||||
})
|
||||
|
||||
it('requests a fresh resume when the same main Bot Chat lost its transcript', async () => {
|
||||
$activeGatewayProfile.set('hyoseob')
|
||||
setMockAtom($selectedStoredSessionId, 'bot-chat')
|
||||
setMockAtom($activeSessionId, 'runtime-stale')
|
||||
setMockAtom($messages, [])
|
||||
|
||||
const opening = host.openSession('bot-chat', {
|
||||
profile: 'hyoseob',
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1_000
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
expect(requestSessionResume).toHaveBeenCalledWith('bot-chat')
|
||||
|
||||
setMockAtom($activeSessionId, 'runtime-refreshed')
|
||||
setMockAtom($messages, [{ id: 'history-restored', parts: [], role: 'assistant' }] as never)
|
||||
|
||||
await opening
|
||||
expect($gatewaySwapTarget.get()).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts an explicitly empty Bot Chat once its main runtime is bound', async () => {
|
||||
$activeGatewayProfile.set('hyoseob')
|
||||
|
||||
const opening = host.openSession('empty-bot-chat', {
|
||||
profile: 'hyoseob',
|
||||
awaitHydration: true,
|
||||
expectHistory: false,
|
||||
hydrationTimeoutMs: 1_000
|
||||
})
|
||||
|
||||
setMockAtom($selectedStoredSessionId, 'empty-bot-chat')
|
||||
setMockAtom($activeSessionId, 'runtime-empty')
|
||||
setMockAtom($messages, [])
|
||||
|
||||
await opening
|
||||
expect($activeSessionId.get()).toBe('runtime-empty')
|
||||
expect($gatewaySwapTarget.get()).toBeNull()
|
||||
})
|
||||
|
||||
it('arms the core Retry surface when Bot Chat hydration times out', async () => {
|
||||
$activeGatewayProfile.set('hyoseob')
|
||||
|
||||
await expect(
|
||||
host.openSession('stranded-bot-chat', {
|
||||
profile: 'hyoseob',
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1
|
||||
})
|
||||
).rejects.toThrow(/timed out loading/i)
|
||||
|
||||
expect(setResumeExhaustedSessionId).toHaveBeenCalledWith('stranded-bot-chat')
|
||||
expect($gatewaySwapTarget.get()).toBeNull()
|
||||
})
|
||||
|
||||
it('lets the latest rapid bot selection win and cancels the older hydration wait', async () => {
|
||||
vi.mocked(ensureGatewayProfile).mockImplementation(async (target: null | string | undefined) => {
|
||||
$activeGatewayProfile.set(target || 'default')
|
||||
})
|
||||
|
||||
const firstOutcome = host
|
||||
.openSession('chat-a', {
|
||||
profile: 'jimin',
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1_000
|
||||
})
|
||||
.then(() => 'resolved', error => String(error))
|
||||
|
||||
await Promise.resolve()
|
||||
|
||||
const second = host.openSession('chat-b', {
|
||||
profile: 'hyoseob',
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1_000
|
||||
})
|
||||
|
||||
setMockAtom($selectedStoredSessionId, 'chat-b')
|
||||
setMockAtom($activeSessionId, 'runtime-b')
|
||||
setMockAtom($messages, [{ id: 'history-b', parts: [], role: 'assistant' }] as never)
|
||||
|
||||
await second
|
||||
expect(await firstOutcome).toMatch(/superseded/i)
|
||||
expect($activeGatewayProfile.get()).toBe('hyoseob')
|
||||
expect($selectedStoredSessionId.get()).toBe('chat-b')
|
||||
expect($gatewaySwapTarget.get()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -598,6 +598,12 @@ export const $awaitingResponse = atom(false)
|
||||
// resume on the next render/focus/reconnect instead of stranding the window.
|
||||
// Null whenever the active route has a healthy (or in-flight) resume.
|
||||
export const $resumeFailedSessionId = atom<string | null>(null)
|
||||
export interface SessionResumeRequest {
|
||||
sequence: number
|
||||
sessionId: string
|
||||
}
|
||||
let sessionResumeRequestSequence = 0
|
||||
export const $sessionResumeRequest = atom<SessionResumeRequest | null>(null)
|
||||
// Stored-session id whose resume has EXHAUSTED its bounded auto-retries (the
|
||||
// terminal-failure latch above kept failing through all MAX_RESUME_RETRIES
|
||||
// attempts). Distinct from $resumeFailedSessionId, which is armed *during* the
|
||||
@@ -771,6 +777,17 @@ export const markSessionRead = (storedSessionId: string | null | undefined) => {
|
||||
export const setMessages = (next: Updater<ChatMessage[]>) => updateAtom($messages, next)
|
||||
export const setFreshDraftReady = (next: Updater<boolean>) => updateAtom($freshDraftReady, next)
|
||||
export const setResumeFailedSessionId = (next: Updater<string | null>) => updateAtom($resumeFailedSessionId, next)
|
||||
|
||||
export const requestSessionResume = (sessionId: string) => {
|
||||
const id = sessionId.trim()
|
||||
|
||||
if (!id) {
|
||||
return
|
||||
}
|
||||
|
||||
$sessionResumeRequest.set({ sequence: ++sessionResumeRequestSequence, sessionId: id })
|
||||
}
|
||||
|
||||
export const setResumeExhaustedSessionId = (next: Updater<string | null>) => updateAtom($resumeExhaustedSessionId, next)
|
||||
export const setBusy = (next: Updater<boolean>) => updateAtom($busy, next)
|
||||
export const setAwaitingResponse = (next: Updater<boolean>) => updateAtom($awaitingResponse, next)
|
||||
|
||||
Reference in New Issue
Block a user