fix(desktop): bound Bot owner wake races
This commit is contained in:
committed by
Teknium
parent
b42d8279ed
commit
856fc66d19
@@ -5104,6 +5104,28 @@ function isCanonicalBotChatHistory(history) {
|
||||
return rootTitle === CANONICAL_CHAT_TITLE || (!rootTitle && title === CANONICAL_CHAT_TITLE)
|
||||
}
|
||||
|
||||
function botModeGatewayNeedsUpdate(error) {
|
||||
const message = String(error?.message || error || '')
|
||||
|
||||
return /(?:method not found|no handler for|unknown method|unsupported rpc)/i.test(message)
|
||||
}
|
||||
|
||||
function notifyBotOpenFailure(error, bot, fallbackMessage) {
|
||||
if (botModeGatewayNeedsUpdate(error)) {
|
||||
const gateway = bot.connectionLabel || bot.connectionId || 'this gateway'
|
||||
|
||||
host.notify?.({
|
||||
kind: 'error',
|
||||
title: 'Update this gateway to use Bot Mode',
|
||||
message: `Update ${gateway}, then try again.`
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
host.notifyError?.(error, fallbackMessage)
|
||||
}
|
||||
|
||||
/** THE identity lookup: the profile's session titled exactly "Bot Chat",
|
||||
* consulted on the bot's OWN source. The core UNIQUE title index guarantees
|
||||
* at most ONE such row per profile db — Profile → Named Session is an exact
|
||||
@@ -5115,7 +5137,6 @@ function isCanonicalBotChatHistory(history) {
|
||||
* authorizes this RPC. */
|
||||
async function findExistingCanonicalChat(owner) {
|
||||
const { bot, name, route } = botOwner(owner)
|
||||
|
||||
// FAIL CLOSED. A failed registry lookup MUST NOT read as "no Bot Chat
|
||||
// exists" — that is the one remaining way to fork a bot's forever chat.
|
||||
// The failure lives exactly in the post-update window: the desktop
|
||||
@@ -5346,7 +5367,8 @@ async function openRosterBot(bot) {
|
||||
$groupChatWorkspace.set(previousGroup)
|
||||
}
|
||||
syncBotsHomeWorkspace()
|
||||
host.notifyError?.(error, `Could not reach ${bot.connectionLabel || 'the gateway'}`)
|
||||
|
||||
notifyBotOpenFailure(error, bot, `Could not reach ${bot.connectionLabel || 'the gateway'}`)
|
||||
}
|
||||
|
||||
return false
|
||||
@@ -5378,7 +5400,8 @@ async function openRosterBot(bot) {
|
||||
$groupChatWorkspace.set(previousGroup)
|
||||
}
|
||||
syncBotsHomeWorkspace()
|
||||
host.notifyError?.(error, `Could not open ${displayName(bot, meta)}'s chat — try again`)
|
||||
|
||||
notifyBotOpenFailure(error, bot, `Could not open ${displayName(bot, meta)}'s chat — try again`)
|
||||
}
|
||||
|
||||
return false
|
||||
@@ -13947,6 +13970,11 @@ export default {
|
||||
group ? 'New group conversations start in the group composer.' : 'Select a Bot or group first.'
|
||||
)
|
||||
} else {
|
||||
// Strand any owner wake still dialing. Its SDK open will fail the
|
||||
// workspace token too; this plugin generation prevents that expected
|
||||
// cancellation from repainting Bots home or showing an error after
|
||||
// the user deliberately returned to Sessions.
|
||||
botOpenGeneration += 1
|
||||
host.setWorkspaceScope?.('sessions')
|
||||
}
|
||||
// A generic composer has no stored-session owner, so passive sync
|
||||
|
||||
@@ -41,6 +41,8 @@ function load({ focusedStoredSessionId = null, paneVisibility = true, openWorksp
|
||||
const notifications = []
|
||||
const requests = []
|
||||
const invalidations = []
|
||||
const sessionOpens = []
|
||||
const workspaceScopes = []
|
||||
const paneVisible = new Map()
|
||||
const focused = atom(focusedStoredSessionId)
|
||||
|
||||
@@ -54,6 +56,23 @@ function load({ focusedStoredSessionId = null, paneVisibility = true, openWorksp
|
||||
requests.push({ method, params })
|
||||
return Promise.resolve({})
|
||||
},
|
||||
requestProfile: (route, method, params) => {
|
||||
requests.push({ method, params, route })
|
||||
if (method === 'profiles.list') {
|
||||
return Promise.resolve({ profiles: [{ name: route.targetProfile || route.profile }] })
|
||||
}
|
||||
if (method === 'session.list') {
|
||||
return Promise.resolve({
|
||||
sessions: [{ id: `chat-${route.connectionId}-${route.profile}`, title: 'Bot Chat', message_count: 1 }]
|
||||
})
|
||||
}
|
||||
return Promise.resolve({})
|
||||
},
|
||||
openSession: async (id, options) => sessionOpens.push({ id, options }),
|
||||
setWorkspaceScope: (mode, ownerKey = null) => {
|
||||
workspaceScopes.push({ mode, ownerKey })
|
||||
return true
|
||||
},
|
||||
notify: params => notifications.push(params),
|
||||
notifyError: (error, fallback) => notifications.push({ kind: 'error', message: fallback, error }),
|
||||
ensureAgent: async () => undefined,
|
||||
@@ -142,7 +161,19 @@ globalThis.__home = {
|
||||
|
||||
vm.runInNewContext(source, context, { filename: 'plugin.js' })
|
||||
|
||||
return { ...context.__home, closed, focused, host, invalidations, notifications, opened, paneVisible, requests }
|
||||
return {
|
||||
...context.__home,
|
||||
closed,
|
||||
focused,
|
||||
host,
|
||||
invalidations,
|
||||
notifications,
|
||||
opened,
|
||||
paneVisible,
|
||||
requests,
|
||||
sessionOpens,
|
||||
workspaceScopes
|
||||
}
|
||||
}
|
||||
|
||||
/** Every door that would create, activate, or route something. A passive
|
||||
@@ -398,9 +429,9 @@ test('an unknown source list is not proof of deletion', () => {
|
||||
assert.equal(t.ghostRosterOwner('work-vps::researcher', [{ connectionId: 'local', reachable: true }]), null)
|
||||
})
|
||||
|
||||
// ── explicit open: local routes, remote never does ──────────────────────────
|
||||
// ── explicit open: every reachable owner routes exactly ────────────────────
|
||||
|
||||
test('opening a remote bot selects it and routes nothing', async () => {
|
||||
test('opening a remote bot selects and opens its exact owner chat', async () => {
|
||||
const t = load()
|
||||
t.setPluginCtx({ storage: { set: () => undefined } })
|
||||
t.$botsPaneVisible.set(true)
|
||||
@@ -415,13 +446,20 @@ test('opening a remote bot selects it and routes nothing', async () => {
|
||||
|
||||
const result = await t.openRosterBot(bot)
|
||||
|
||||
assert.equal(result, false, 'a remote row does not open a chat')
|
||||
assert.equal(result, true)
|
||||
assert.equal(t.$selectedRosterKey.get(), 'work-vps::researcher')
|
||||
assert.equal(t.$openBotChat.get(), null)
|
||||
assertNothingRouted(t, 'clicking a remote row')
|
||||
const openBotChat = t.$openBotChat.get()
|
||||
assert.equal(openBotChat?.key, 'work-vps::researcher')
|
||||
assert.equal(openBotChat?.openedRegistryId, 'chat-work-vps-researcher')
|
||||
assert.equal(t.sessionOpens.length, 1)
|
||||
assert.equal(t.sessionOpens[0].options.workspaceMode, 'bots')
|
||||
assert.equal(t.sessionOpens[0].options.workspaceOwnerKey, 'bot:work-vps::researcher')
|
||||
assert.equal(t.sessionOpens[0].options.keepAllProfilesScope, true)
|
||||
assert.equal(t.sessionOpens[0].options.route.connectionId, 'work-vps')
|
||||
assert.ok(t.requests.every(request => request.route?.connectionId === 'work-vps'))
|
||||
})
|
||||
|
||||
test('a remote owner fronts the Bots home without closing the group tab', async () => {
|
||||
test('a remote owner opens its chat without closing an unrelated group tab', async () => {
|
||||
const t = load()
|
||||
t.setPluginCtx({ storage: { set: () => undefined } })
|
||||
t.$botsPaneVisible.set(true)
|
||||
@@ -435,13 +473,14 @@ test('a remote owner fronts the Bots home without closing the group tab', async
|
||||
remoteSource: true
|
||||
})
|
||||
|
||||
assert.equal(result, false)
|
||||
assert.equal(t.botsHomeVisible(), true)
|
||||
assert.equal(result, true)
|
||||
assert.equal(t.botsHomeVisible(), false)
|
||||
assert.equal(t.$groupChatWorkspace.get(), null)
|
||||
assert.equal(groupEntry.disposed, false, 'explicit selection must not close an unrelated group tab')
|
||||
assert.equal(t.sessionOpens.length, 1)
|
||||
})
|
||||
|
||||
test('a remote owner preserves a group when the Bots home cannot open', async () => {
|
||||
test('a remote owner does not depend on the informational home surface', async () => {
|
||||
const t = load()
|
||||
t.setPluginCtx({ storage: { set: () => undefined } })
|
||||
t.$botsPaneVisible.set(true)
|
||||
@@ -458,9 +497,10 @@ test('a remote owner preserves a group when the Bots home cannot open', async ()
|
||||
remoteSource: true
|
||||
})
|
||||
|
||||
assert.equal(result, false)
|
||||
assert.equal(t.$groupChatWorkspace.get(), 'Launch room')
|
||||
assert.equal(result, true)
|
||||
assert.equal(t.$groupChatWorkspace.get(), null)
|
||||
assert.equal(groupEntry.disposed, false)
|
||||
assert.equal(t.sessionOpens.length, 1)
|
||||
})
|
||||
|
||||
test('a failed local open leaves no phantom owner in the center', async () => {
|
||||
@@ -469,9 +509,9 @@ test('a failed local open leaves no phantom owner in the center', async () => {
|
||||
t.$botsPaneVisible.set(true)
|
||||
t.$openBotChat.set({ key: 'local::writer', openedRegistryId: 'previous' })
|
||||
|
||||
// A source-scoped row on a desktop that cannot activate it: prepareBotSource
|
||||
// A source-scoped row on a desktop that cannot address it: prepareBotSource
|
||||
// refuses rather than letting the open fall through to the live gateway.
|
||||
delete t.host.ensureAgent
|
||||
delete t.host.requestProfile
|
||||
const bot = { connectionId: 'work-vps', name: 'writer', sourceScoped: true }
|
||||
|
||||
const result = await t.openRosterBot(bot)
|
||||
@@ -482,6 +522,26 @@ test('a failed local open leaves no phantom owner in the center', async () => {
|
||||
assertNothingRouted(t, 'a refused local open')
|
||||
})
|
||||
|
||||
test('an older gateway gets an actionable Bot Mode update message', async () => {
|
||||
const t = load()
|
||||
t.setPluginCtx({ storage: { set: () => undefined } })
|
||||
t.$botsPaneVisible.set(true)
|
||||
t.host.requestProfile = async () => {
|
||||
throw new Error('Unknown method profiles.list')
|
||||
}
|
||||
|
||||
const result = await t.openRosterBot({
|
||||
connectionId: 'work-vps',
|
||||
connectionLabel: 'Work',
|
||||
name: 'writer',
|
||||
sourceScoped: true
|
||||
})
|
||||
|
||||
assert.equal(result, false)
|
||||
assert.equal(t.notifications.at(-1).title, 'Update this gateway to use Bot Mode')
|
||||
assert.equal(t.notifications.at(-1).message, 'Update Work, then try again.')
|
||||
})
|
||||
|
||||
test('a missing profile-scoped draft API returns to the home without navigating', async () => {
|
||||
const t = load()
|
||||
t.setPluginCtx({ storage: { set: () => undefined } })
|
||||
@@ -662,7 +722,7 @@ test('a persisted layout that restored the home behind the draft gets re-fronted
|
||||
assert.equal(t.botsHomeVisible(), true)
|
||||
})
|
||||
|
||||
test('an explicit remote selection fronts the home over a focused chat', async () => {
|
||||
test('an explicit remote selection opens its owner tab without moving the focused Sessions chat', async () => {
|
||||
const t = load({ focusedStoredSessionId: 'local-scout-chat' })
|
||||
t.setPluginCtx({ storage: { set: () => undefined } })
|
||||
t.$botsPaneVisible.set(true)
|
||||
@@ -671,19 +731,19 @@ test('an explicit remote selection fronts the home over a focused chat', async (
|
||||
t.syncBotsHomeWorkspace()
|
||||
assert.deepEqual(t.opened, [])
|
||||
|
||||
// …but clicking the same-named twin on another gateway is a gesture at
|
||||
// that owner: the home fronts, the chat stays alive underneath.
|
||||
// …but clicking the same-named twin on another gateway opens that owner in
|
||||
// Bot Mode while the Sessions chat stays alive underneath.
|
||||
await t.openRosterBot({ connectionId: 'work-vps', connectionLabel: 'Work', name: 'scout', remoteSource: true })
|
||||
|
||||
assert.equal(t.opened.length, 1)
|
||||
assert.equal(t.opened.length, 0)
|
||||
assert.equal(t.sessionOpens.length, 1)
|
||||
assert.equal(t.$selectedRosterKey.get(), 'work-vps::scout')
|
||||
assert.equal(t.$openBotChat.get(), null)
|
||||
assertNothingRouted(t, 'explicit remote selection')
|
||||
assert.equal(t.$openBotChat.get().key, 'work-vps::scout')
|
||||
assert.equal(t.focused.get(), 'local-scout-chat')
|
||||
|
||||
// Browsing more remote owners reuses the fronted home instead of
|
||||
// re-registering it (a stale disposer would tear down the newer one).
|
||||
// Browsing more remote owners opens that owner without reusing the first.
|
||||
await t.openRosterBot({ connectionId: 'work-vps', connectionLabel: 'Work', name: 'relay', remoteSource: true })
|
||||
assert.equal(t.opened.length, 1)
|
||||
assert.equal(t.sessionOpens.length, 2)
|
||||
assert.equal(t.$selectedRosterKey.get(), 'work-vps::relay')
|
||||
})
|
||||
|
||||
@@ -701,8 +761,8 @@ test('an explicit Bots-home gesture fronts the selected owner over a Sessions co
|
||||
|
||||
test('source contract: sidebar entry and boot restore reconcile passively after layout hydration', () => {
|
||||
assert.match(pluginSource, /const syncWorkspaceSurfaces = \(\) =>/)
|
||||
assert.match(pluginSource, /stopSidebarSync = \$sidebarVisible\.listen\(visible => \{[\s\S]{0,450}?syncWorkspaceSurfaces\(\)/)
|
||||
assert.doesNotMatch(pluginSource, /stopSidebarSync = \$sidebarVisible\.listen\(visible => \{[\s\S]{0,450}?syncWorkspaceSurfaces\(Boolean\(visible\)\)/)
|
||||
assert.match(pluginSource, /stopSidebarSync = \$sidebarVisible\.listen\(visible => \{[\s\S]{0,1500}?syncWorkspaceSurfaces\(\)/)
|
||||
assert.doesNotMatch(pluginSource, /stopSidebarSync = \$sidebarVisible\.listen\(visible => \{[\s\S]{0,1500}?syncWorkspaceSurfaces\(Boolean\(visible\)\)/)
|
||||
assert.match(
|
||||
pluginSource,
|
||||
/\$botChatFocused\.set\(sessionOwnsWorkspace\(\)\)[\s\S]{0,500}?syncWorkspaceSurfaces\(\)[\s\S]{0,120}?scheduleSurfaceSync\(\)/
|
||||
@@ -818,20 +878,28 @@ test('the home never yanks the center back from a sibling tab the user chose', (
|
||||
assert.deepEqual(t.closed, [])
|
||||
})
|
||||
|
||||
test('older shells without the main-area door simply have no home', async () => {
|
||||
test('older shells without owner routing fail with an update path', async () => {
|
||||
const t = load({ openWorkspace: false, paneVisibility: false })
|
||||
t.setPluginCtx({ storage: { set: () => undefined } })
|
||||
t.$botsPaneVisible.set(true)
|
||||
delete t.host.requestProfile
|
||||
delete t.host.openSession
|
||||
|
||||
t.syncBotsHomeWorkspace()
|
||||
assert.deepEqual(t.opened, [])
|
||||
|
||||
// And the remote row keeps its previous guidance toast instead.
|
||||
await t.openRosterBot({ connectionId: 'work-vps', connectionLabel: 'Work', name: 'researcher', remoteSource: true })
|
||||
// A remote row cannot guess through the active gateway on an old shell.
|
||||
await t.openRosterBot({
|
||||
connectionId: 'work-vps',
|
||||
connectionLabel: 'Work',
|
||||
name: 'researcher',
|
||||
remoteSource: true,
|
||||
sourceScoped: true
|
||||
})
|
||||
|
||||
assert.equal(t.notifications.length, 1)
|
||||
// Guidance is presentation only; remote mention delivery remains backend-owned.
|
||||
assert.match(t.notifications[0].message, /message @researcher from a Bot Chat/)
|
||||
assert.match(t.notifications[0].message, /Could not reach Work/)
|
||||
assert.match(String(t.notifications[0].error), /Update Hermes Desktop/)
|
||||
assertNothingRouted(t, 'remote row on an older shell')
|
||||
})
|
||||
|
||||
@@ -906,15 +974,15 @@ test('an unavailable owner offers retry instead of a dead Open chat button', ()
|
||||
assert.doesNotMatch(view, /its work keeps running on that gateway/)
|
||||
})
|
||||
|
||||
test('an available remote owner explains the supported Bot Chat path without a fake direct action', () => {
|
||||
test('an available remote owner offers the same direct chat action', () => {
|
||||
const start = pluginSource.indexOf('function BotsHomeView(')
|
||||
const view = pluginSource.slice(start, pluginSource.indexOf('function closeBotsHomeWorkspace('))
|
||||
|
||||
assert.match(view, /unavailable \|\| !bot\.remoteSource/)
|
||||
assert.match(view, /This bot lives on \$\{gateway\}\. Mention it from any Bot Chat to send it a message\./)
|
||||
assert.match(view, /children: 'Open chat'/)
|
||||
assert.match(view, /Open this bot’s continuous chat/)
|
||||
assert.doesNotMatch(view, /Copy @/)
|
||||
assert.doesNotMatch(view, /remoteCopy/)
|
||||
assert.doesNotMatch(view, /ensureAgent|requestProfile|newChat/)
|
||||
assert.doesNotMatch(view, /Mention it from any Bot Chat/)
|
||||
})
|
||||
|
||||
test('an unavailable owner never presents a guessed mention handle', () => {
|
||||
|
||||
@@ -33,6 +33,8 @@ import {
|
||||
revealTreePane
|
||||
} from '@/components/pane-shell/tree/store'
|
||||
import {
|
||||
$workspaceMode,
|
||||
$workspaceOwnerKey,
|
||||
setWorkspaceScope as publishWorkspaceScope,
|
||||
type WorkspaceNewSessionTarget
|
||||
} from '@/components/pane-shell/workspace-scope'
|
||||
@@ -255,6 +257,31 @@ async function requestPluginProfile<T>(
|
||||
)
|
||||
}
|
||||
|
||||
/** Re-read Electron's current registry before retrying an exact-owner wake.
|
||||
* A route that was removed or replaced while the first hydration wait ran is
|
||||
* no longer authority to touch that backend, even when its labels still look
|
||||
* identical. */
|
||||
async function pluginRouteStillRegistered(route: PluginProfileRoute): Promise<boolean> {
|
||||
const getProfileRoutes = window.hermesDesktop?.getProfileRoutes
|
||||
|
||||
if (!getProfileRoutes) {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const routes = await getProfileRoutes($profiles.get().map(profile => profile.name))
|
||||
|
||||
return routes.some(
|
||||
candidate =>
|
||||
candidate.connectionId === route.connectionId &&
|
||||
candidate.profile === route.profile &&
|
||||
candidate.targetProfile === route.targetProfile
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
const refresh = () => $viewport.set(readViewport())
|
||||
window.addEventListener('resize', refresh)
|
||||
@@ -307,17 +334,17 @@ export interface PluginNewChatOptions {
|
||||
}
|
||||
|
||||
function waitForFocusedSessionHydration({
|
||||
connectionId,
|
||||
expectHistory,
|
||||
generation,
|
||||
isCurrent,
|
||||
profile,
|
||||
requireActiveProfile,
|
||||
storedSessionId,
|
||||
timeoutMs
|
||||
}: {
|
||||
connectionId?: string
|
||||
expectHistory: boolean
|
||||
generation: number
|
||||
isCurrent?: () => boolean
|
||||
profile: string
|
||||
requireActiveProfile: boolean
|
||||
storedSessionId: string
|
||||
@@ -351,17 +378,27 @@ function waitForFocusedSessionHydration({
|
||||
}
|
||||
|
||||
const check = () => {
|
||||
if (generation !== openSessionGeneration) {
|
||||
if (generation !== openSessionGeneration || (isCurrent && !isCurrent())) {
|
||||
finish(new Error('Session open was superseded by a newer selection.'))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const profileMatches = !requireActiveProfile || normalizeProfileKey($activeGatewayProfile.get()) === profile
|
||||
const connectionMatches = !connectionId || $activeConnectionId.get() === connectionId
|
||||
const sessionMatches = $selectedStoredSessionId.get() === storedSessionId
|
||||
const runtimeReady = Boolean($activeSessionId.get())
|
||||
const historyPainted = Boolean($messages.get().length)
|
||||
const mainMatches = $selectedStoredSessionId.get() === storedSessionId
|
||||
const tileMatches = $focusedStoredSessionId.get() === storedSessionId
|
||||
|
||||
const runtimeReady = mainMatches
|
||||
? Boolean($activeSessionId.get())
|
||||
: tileMatches
|
||||
? Boolean($focusedRuntimeId.get())
|
||||
: false
|
||||
|
||||
const historyPainted = mainMatches
|
||||
? Boolean($messages.get().length)
|
||||
: tileMatches
|
||||
? Boolean($focusedSessionState.get()?.messages.length)
|
||||
: false
|
||||
|
||||
// Paint-first hydration: for a history-bearing chat, the wake is DONE
|
||||
// the moment the persisted transcript is painted on the right session —
|
||||
@@ -377,7 +414,7 @@ function waitForFocusedSessionHydration({
|
||||
// surface is real rather than a stuck loader.
|
||||
const hydrated = expectHistory ? historyPainted : runtimeReady
|
||||
|
||||
if (profileMatches && connectionMatches && sessionMatches && hydrated) {
|
||||
if (profileMatches && (mainMatches || tileMatches) && hydrated) {
|
||||
finish()
|
||||
}
|
||||
}
|
||||
@@ -387,6 +424,11 @@ function waitForFocusedSessionHydration({
|
||||
unbinds.push($selectedStoredSessionId.listen(check))
|
||||
unbinds.push($activeSessionId.listen(check))
|
||||
unbinds.push($messages.listen(check))
|
||||
unbinds.push($focusedStoredSessionId.listen(check))
|
||||
unbinds.push($focusedRuntimeId.listen(check))
|
||||
unbinds.push($focusedSessionState.listen(check))
|
||||
unbinds.push($workspaceMode.listen(check))
|
||||
unbinds.push($workspaceOwnerKey.listen(check))
|
||||
|
||||
timer = window.setTimeout(() => {
|
||||
finish(new Error(`Timed out loading ${profile}'s session history.`))
|
||||
@@ -671,6 +713,19 @@ export const host = {
|
||||
const targetProfile = normalizeProfileKey(profile || $activeGatewayProfile.get())
|
||||
const expectHistory = options.expectHistory ?? false
|
||||
|
||||
if (options.workspaceMode === 'bots') {
|
||||
publishWorkspaceScope(
|
||||
'bots',
|
||||
options.workspaceOwnerKey ?? null,
|
||||
ownerRoute ? { kind: 'route', route: ownerRoute } : null
|
||||
)
|
||||
}
|
||||
|
||||
const openingStillCurrent = () =>
|
||||
generation === openSessionGeneration &&
|
||||
(options.workspaceMode !== 'bots' ||
|
||||
($workspaceMode.get() === 'bots' && $workspaceOwnerKey.get() === (options.workspaceOwnerKey ?? null)))
|
||||
|
||||
const plan = planPluginOpenSession({
|
||||
activeProfile: $activeGatewayProfile.get(),
|
||||
keepAllProfilesScope: options.keepAllProfilesScope,
|
||||
@@ -720,6 +775,10 @@ export const host = {
|
||||
profileActiveAt = Date.now()
|
||||
}
|
||||
|
||||
if (!openingStillCurrent()) {
|
||||
throw new Error('Session open was superseded by a newer selection.')
|
||||
}
|
||||
|
||||
if (ownerRoute) {
|
||||
setShowAllProfiles(true)
|
||||
} else if (plan.showAllProfiles !== null) {
|
||||
@@ -728,7 +787,7 @@ export const host = {
|
||||
|
||||
wakePhase = 'hydration'
|
||||
|
||||
if (generation !== openSessionGeneration) {
|
||||
if (!openingStillCurrent()) {
|
||||
throw new Error('Session open was superseded by a newer selection.')
|
||||
}
|
||||
|
||||
@@ -756,11 +815,6 @@ export const host = {
|
||||
const intent = options.intent ?? 'in-place'
|
||||
|
||||
if (options.workspaceMode === 'bots') {
|
||||
publishWorkspaceScope(
|
||||
'bots',
|
||||
options.workspaceOwnerKey ?? null,
|
||||
ownerRoute ? { kind: 'route', route: ownerRoute } : null
|
||||
)
|
||||
openSession(storedSessionId, navigate, intent, {
|
||||
workspaceMode: 'bots',
|
||||
workspaceOwnerKey: options.workspaceOwnerKey
|
||||
@@ -790,9 +844,9 @@ export const host = {
|
||||
|
||||
if (options.awaitHydration) {
|
||||
await waitForFocusedSessionHydration({
|
||||
connectionId: ownerRoute?.connectionId,
|
||||
expectHistory,
|
||||
generation,
|
||||
isCurrent: openingStillCurrent,
|
||||
profile: targetProfile,
|
||||
// A background dial never moves $activeGatewayProfile, so gating
|
||||
// hydration on it would wait for something that is not coming.
|
||||
@@ -815,6 +869,10 @@ export const host = {
|
||||
throw error
|
||||
}
|
||||
|
||||
if (ownerRoute && !(await pluginRouteStillRegistered(ownerRoute))) {
|
||||
throw new Error(`The ${targetProfile} gateway is no longer available.`)
|
||||
}
|
||||
|
||||
// Logged per attempt so a support bundle shows the retry happened at
|
||||
// all; the terminal failure is reported once by the catch below.
|
||||
console.warn('[bot-wake] hydration timed out, retrying', {
|
||||
@@ -828,7 +886,7 @@ export const host = {
|
||||
} catch (error) {
|
||||
if (
|
||||
options.awaitHydration &&
|
||||
generation === openSessionGeneration &&
|
||||
openingStillCurrent() &&
|
||||
error instanceof Error &&
|
||||
error.message.startsWith('Timed out loading ')
|
||||
) {
|
||||
|
||||
@@ -123,6 +123,7 @@ const {
|
||||
} = await import('@/store/profile')
|
||||
|
||||
const { $focusedRuntimeId, $focusedSessionState, $focusedStoredSessionId } = await import('@/store/session-states')
|
||||
const { setWorkspaceScope } = await import('@/components/pane-shell/workspace-scope')
|
||||
|
||||
const {
|
||||
$activeSessionId,
|
||||
@@ -156,6 +157,7 @@ afterEach(() => {
|
||||
setMockAtom($selectedStoredSessionId, null)
|
||||
setMockAtom($messages, [])
|
||||
$profiles.set([profile('cached-only')])
|
||||
setWorkspaceScope('sessions')
|
||||
delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
|
||||
})
|
||||
|
||||
@@ -433,7 +435,98 @@ describe('profile-aware plugin session opens', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('waits until the target Bot Chat runtime and history are on main before resolving', async () => {
|
||||
it('finishes hydration on the focused Bot tile without moving the Sessions gateway', async () => {
|
||||
const route = {
|
||||
connectionId: 'source-a',
|
||||
mode: 'remote' as const,
|
||||
profile: 'default',
|
||||
targetProfile: 'backend-default'
|
||||
}
|
||||
|
||||
const opening = host.openSession('bot-chat', {
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1_000,
|
||||
intent: 'tab',
|
||||
route,
|
||||
workspaceMode: 'bots',
|
||||
workspaceOwnerKey: 'bot:source-a::default'
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
setMockAtom($focusedStoredSessionId, 'bot-chat')
|
||||
setMockAtom($focusedRuntimeId, 'runtime-bot-chat')
|
||||
setMockAtom($focusedSessionState, {
|
||||
messages: [{ id: 'bot-history', parts: [], role: 'assistant' }],
|
||||
storedSessionId: 'bot-chat'
|
||||
} as never)
|
||||
|
||||
await opening
|
||||
expect($activeGatewayProfile.get()).toBe('remote-worker')
|
||||
expect($selectedStoredSessionId.get()).toBeNull()
|
||||
})
|
||||
|
||||
it('strands a late Bot wake when the user returns to Sessions', async () => {
|
||||
let releaseDial: (() => void) | undefined
|
||||
|
||||
vi.mocked(openGatewayForAgent).mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<void>(resolve => {
|
||||
releaseDial = resolve
|
||||
})
|
||||
)
|
||||
|
||||
const opening = host.openSession('late-bot-chat', {
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1_000,
|
||||
intent: 'tab',
|
||||
route: {
|
||||
connectionId: 'source-a',
|
||||
mode: 'remote',
|
||||
profile: 'writer',
|
||||
targetProfile: 'writer'
|
||||
},
|
||||
workspaceMode: 'bots',
|
||||
workspaceOwnerKey: 'bot:source-a::writer'
|
||||
})
|
||||
|
||||
setWorkspaceScope('sessions')
|
||||
releaseDial?.()
|
||||
|
||||
await expect(opening).rejects.toThrow(/superseded/i)
|
||||
expect(openSessionCore).not.toHaveBeenCalled()
|
||||
expect(setResumeExhaustedSessionId).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('revalidates an exact route before the one allowed hydration retry', async () => {
|
||||
;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {
|
||||
getProfileRoutes: vi.fn(async () => [])
|
||||
}
|
||||
|
||||
await expect(
|
||||
host.openSession('removed-owner-chat', {
|
||||
awaitHydration: true,
|
||||
expectHistory: true,
|
||||
hydrationTimeoutMs: 1,
|
||||
intent: 'tab',
|
||||
retryHydrationTimeoutOnce: true,
|
||||
route: {
|
||||
connectionId: 'removed-source',
|
||||
mode: 'remote',
|
||||
profile: 'writer',
|
||||
targetProfile: 'writer'
|
||||
},
|
||||
workspaceMode: 'bots',
|
||||
workspaceOwnerKey: 'bot:removed-source::writer'
|
||||
})
|
||||
).rejects.toThrow(/no longer available/i)
|
||||
|
||||
expect(openSessionCore).toHaveBeenCalledTimes(1)
|
||||
expect(setResumeExhaustedSessionId).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('waits until the target Bot Chat runtime and history are on the focused surface', async () => {
|
||||
vi.mocked(openGatewayForProfile).mockImplementationOnce(async () => undefined)
|
||||
|
||||
let resolved = false
|
||||
@@ -467,18 +560,6 @@ describe('profile-aware plugin session opens', () => {
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user