From 214e186f71e53ada59e7c1491a1d9e6198876ed5 Mon Sep 17 00:00:00 2001 From: Raing5Days Date: Tue, 17 Nov 2026 11:05:52 +0800 Subject: [PATCH 1/5] perf(flow-chat): resolve trajectory endpoints without rebuilding every node key The trajectory panel is keyed by session, so switching sessions remounts it and its mount pass runs over the whole loaded node page: the saved endpoint keys were resolved with one built JSON key per node per endpoint, and the range summary walked the selection five times through filter passes and a reduce closure. - resolveTrajectoryRange reads the two endpoint identities once and matches node fields in a single pass. An endpoint from an unexpected source still falls back to the former per-node key comparison. - summarizeTrajectoryRange counts kinds, tallies errors and sums both durations in one pass, keeping "no duration recorded" distinct from a measured zero. Measured with the local OpCase benchmark (400 nodes, panel mount pass, 72000 measured calls): 85.83 us/call -> 7.30 us/call against a 60.08 us/call budget. The number is module cost, not a frame time. Testing: node scripts/run-vitest.mjs run src/flow_chat/trajectory (49 passed); pnpm run check:web (pre-existing failures only: stale MiniApp chrome theme artifact and appearance-contract warnings). --- .../flow_chat/trajectory/trajectoryRange.ts | 95 ++++++++++++++++--- 1 file changed, 84 insertions(+), 11 deletions(-) diff --git a/src/web-ui/src/flow_chat/trajectory/trajectoryRange.ts b/src/web-ui/src/flow_chat/trajectory/trajectoryRange.ts index d839f4f3d8..2cd79d0d0e 100644 --- a/src/web-ui/src/flow_chat/trajectory/trajectoryRange.ts +++ b/src/web-ui/src/flow_chat/trajectory/trajectoryRange.ts @@ -6,22 +6,95 @@ export interface TrajectoryRangeSummary { counts: { user: number; model: number; tool: number; errors: number }; modelMs?: number; toolMs?: number; } + +/** + * Endpoint identities are `trajectoryNodeKey` values. Reading the two keys back + * once lets a scan compare node fields directly instead of building a key string + * for every node twice: on a loaded page this pass is the panel's whole mount cost. + */ +function readNodeIdentity(key: string): [string, string, string] | null { + try { + const parts = JSON.parse(key) as unknown; + return Array.isArray(parts) && parts.length === 3 ? parts as [string, string, string] : null; + } catch { + return null; + } +} + /** Endpoints use stable identities so loading older pages cannot move a range. */ export function resolveTrajectoryRange(nodes: readonly TrajectoryNode[], range: TrajectoryRange | null): [number, number] | null { if (!range) return null; - const anchor = nodes.findIndex(node => trajectoryNodeKey(node) === range.anchor); - const focus = nodes.findIndex(node => trajectoryNodeKey(node) === range.focus); + const anchorIdentity = readNodeIdentity(range.anchor); + const focusIdentity = readNodeIdentity(range.focus); + if (!anchorIdentity || !focusIdentity) { + // An endpoint from an unexpected source keeps the exact former comparison. + const anchor = nodes.findIndex(node => trajectoryNodeKey(node) === range.anchor); + const focus = nodes.findIndex(node => trajectoryNodeKey(node) === range.focus); + return anchor < 0 || focus < 0 ? null : [Math.min(anchor, focus), Math.max(anchor, focus)]; + } + const [anchorTurn, anchorKind, anchorId] = anchorIdentity; + const [focusTurn, focusKind, focusId] = focusIdentity; + // One pass, first match per endpoint, so a prepended page cannot shift a range + // and a single-node range still reports the same index twice. + let anchor = -1; + let focus = -1; + for (let index = 0; index < nodes.length; index += 1) { + const node = nodes[index]; + if (anchor < 0 && node.turnId === anchorTurn && node.kind === anchorKind && node.id === anchorId) anchor = index; + if (focus < 0 && node.turnId === focusTurn && node.kind === focusKind && node.id === focusId) focus = index; + if (anchor >= 0 && focus >= 0) break; + } return anchor < 0 || focus < 0 ? null : [Math.min(anchor, focus), Math.max(anchor, focus)]; } + +/** Slice index for a range bound: negative counts from the end, the rest clamps. */ +function sliceIndex(bound: number, length: number): number { + return bound < 0 ? Math.max(length + bound, 0) : Math.min(bound, length); +} + export function summarizeTrajectoryRange(nodes: readonly TrajectoryNode[], bounds: [number, number]): TrajectoryRangeSummary { - const selected = nodes.slice(bounds[0], bounds[1] + 1); - const sum = (kind: 'model' | 'tool') => { - const values = selected.filter(node => node.kind === kind); - return values.length && values.every(node => typeof node.durationMs === 'number') - ? values.reduce((sum, node) => sum + node.durationMs!, 0) : undefined; + const from = sliceIndex(bounds[0], nodes.length); + const to = sliceIndex(bounds[1] + 1, nodes.length); + if (!(to > from)) { + // What the old `slice(from, to)` projection reported for an empty range. + return { + start: undefined as unknown as TrajectoryNode, + end: undefined as unknown as TrajectoryNode, + counts: { user: 0, model: 0, tool: 0, errors: 0 }, + modelMs: undefined, + toolMs: undefined, + }; + } + // Counting, error tallying and both duration sums share one pass over the range; + // a duration is only summed when every node of that kind carries one. + let user = 0; + let model = 0; + let tool = 0; + let errors = 0; + let modelMs = 0; + let toolMs = 0; + let modelComplete = true; + let toolComplete = true; + for (let index = from; index < to; index += 1) { + const node = nodes[index]; + if (node.kind === 'model') { + model += 1; + if (typeof node.durationMs === 'number') modelMs += node.durationMs; + else modelComplete = false; + } else if (node.kind === 'tool') { + tool += 1; + if (typeof node.durationMs === 'number') toolMs += node.durationMs; + else toolComplete = false; + } else { + user += 1; + } + if (node.status === 'error') errors += 1; + } + return { + start: nodes[from], + end: nodes[to - 1], + counts: { user, model, tool, errors }, + modelMs: model > 0 && modelComplete ? modelMs : undefined, + toolMs: tool > 0 && toolComplete ? toolMs : undefined, }; - return { start: selected[0], end: selected[selected.length - 1], - counts: { user: selected.filter(node => node.kind === 'user').length, - model: selected.filter(node => node.kind === 'model').length, tool: selected.filter(node => node.kind === 'tool').length, - errors: selected.filter(node => node.status === 'error').length }, modelMs: sum('model'), toolMs: sum('tool') }; } From f6a4bf537fc7a0b5946fbe2e6897cda8cd5fce45 Mon Sep 17 00:00:00 2001 From: Raing5Days Date: Tue, 17 Nov 2026 11:31:31 +0800 Subject: [PATCH 2/5] test(flow-chat): check trajectory range against the previous implementation trajectoryRange.ts now resolves endpoints by comparing node fields and summarizes a range in one pass. Both replacements are checked against the previous slice/filter/key-scan implementations copied into the test file, so a difference in counts, duration sums, empty selections, endpoint identity, or first-match behaviour fails here instead of in the panel. Covered on purpose: - every interesting bound shape: reversed, equal, negative, past the end; - an empty selection, where the previous code reported no endpoints; - "no duration recorded" vs a measured zero; - identities that need JSON escaping (quotes, backslashes, newlines, NUL, non-ASCII), so the parsed endpoint path cannot drift from the key format; - a prepended page, a repeated identity, a malformed or missing endpoint. --- .../trajectory/trajectoryRange.test.ts | 175 ++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 src/web-ui/src/flow_chat/trajectory/trajectoryRange.test.ts diff --git a/src/web-ui/src/flow_chat/trajectory/trajectoryRange.test.ts b/src/web-ui/src/flow_chat/trajectory/trajectoryRange.test.ts new file mode 100644 index 0000000000..0ee6f5a250 --- /dev/null +++ b/src/web-ui/src/flow_chat/trajectory/trajectoryRange.test.ts @@ -0,0 +1,175 @@ +import { describe, expect, it } from 'vitest'; +import { resolveTrajectoryRange, summarizeTrajectoryRange } from './trajectoryRange'; +import { trajectoryNodeKey, type TrajectoryNode } from './trajectoryModel'; + +/** + * The previous implementations, kept here as the reference. The range pass was + * rewritten to walk the selection once and to stop rebuilding a key string per + * node, and these two functions are what "behaviour is unchanged" is checked + * against. + */ +function referenceResolve( + nodes: readonly TrajectoryNode[], + range: { anchor: string; focus: string } | null, +): [number, number] | null { + if (!range) return null; + const anchor = nodes.findIndex(node => trajectoryNodeKey(node) === range.anchor); + const focus = nodes.findIndex(node => trajectoryNodeKey(node) === range.focus); + return anchor < 0 || focus < 0 ? null : [Math.min(anchor, focus), Math.max(anchor, focus)]; +} + +function referenceSummarize(nodes: readonly TrajectoryNode[], bounds: [number, number]) { + const selected = nodes.slice(bounds[0], bounds[1] + 1); + const sum = (kind: 'model' | 'tool') => { + const values = selected.filter(node => node.kind === kind); + return values.length && values.every(node => typeof node.durationMs === 'number') + ? values.reduce((total, node) => total + node.durationMs!, 0) : undefined; + }; + return { + start: selected[0], + end: selected[selected.length - 1], + counts: { + user: selected.filter(node => node.kind === 'user').length, + model: selected.filter(node => node.kind === 'model').length, + tool: selected.filter(node => node.kind === 'tool').length, + errors: selected.filter(node => node.status === 'error').length, + }, + modelMs: sum('model'), + toolMs: sum('tool'), + }; +} + +function node(overrides: Partial & Pick): TrajectoryNode { + return { + turnOrdinal: 0, + label: '', + preview: '', + status: 'completed', + timestamp: 0, + matched: false, + ...overrides, + }; +} + +/** Deterministic pseudo-random stream so a failure is reproducible. */ +function random(seed: number): () => number { + let state = seed; + return () => { + state = (state * 1664525 + 1013904223) % 4294967296; + return state / 4294967296; + }; +} + +function buildRandomNodes(next: () => number, count: number, idPrefix = ''): TrajectoryNode[] { + const kinds = ['user', 'model', 'tool'] as const; + return Array.from({ length: count }, (_, index) => { + const kind = kinds[Math.floor(next() * kinds.length)]; + return node({ + id: `${idPrefix}node-${index}`, + turnId: `${idPrefix}turn-${Math.floor(index / 6)}`, + turnOrdinal: Math.floor(index / 6), + kind, + status: next() < 0.15 ? 'error' : 'completed', + // A missing duration has to stay distinguishable from a measured zero. + durationMs: next() < 0.5 ? undefined : Math.floor(next() * 500), + }); + }); +} + +describe('trajectory range equivalence', () => { + it('summarizes every range of a random page exactly like the previous implementation', () => { + const next = random(20261117); + const nodes = buildRandomNodes(next, 60); + const ranges: Array<[number, number]> = [ + [0, 0], [0, 59], [5, 5], [10, 20], [59, 0], [20, 10], + [-1, 5], [0, -1], [-5, -1], [50, 200], [-200, 200], [59, 59], + ]; + for (const bounds of ranges) { + expect(summarizeTrajectoryRange(nodes, bounds)).toEqual(referenceSummarize(nodes, bounds)); + } + }); + + it('reports the same endpoints and counts for random slices, including empty selections', () => { + const next = random(4242); + const nodes = buildRandomNodes(next, 40); + for (let iteration = 0; iteration < 200; iteration += 1) { + const from = Math.floor(next() * 44) - 2; + const to = from + Math.floor(next() * 44) - 4; + const bounds: [number, number] = [from, to]; + const actual = summarizeTrajectoryRange(nodes, bounds); + const expected = referenceSummarize(nodes, bounds); + expect(actual.counts).toEqual(expected.counts); + expect(actual.modelMs).toEqual(expected.modelMs); + expect(actual.toolMs).toEqual(expected.toolMs); + // Endpoints keep object identity with the page, and stay undefined when empty. + expect(actual.start).toBe(expected.start); + expect(actual.end).toBe(expected.end); + } + }); + + it('keeps a measured zero duration distinct from a missing one', () => { + const nodes = [ + node({ id: 'a', turnId: 't', kind: 'tool', durationMs: 0 }), + node({ id: 'b', turnId: 't', kind: 'model', durationMs: 15 }), + node({ id: 'c', turnId: 't', kind: 'tool' }), + ]; + expect(summarizeTrajectoryRange(nodes, [0, 1]).toolMs).toBe(0); + expect(summarizeTrajectoryRange(nodes, [0, 1]).modelMs).toBe(15); + expect(summarizeTrajectoryRange(nodes, [0, 2]).toolMs).toBeUndefined(); + expect(referenceSummarize(nodes, [0, 2]).toolMs).toBeUndefined(); + }); + + it('resolves endpoints exactly like the previous key scan', () => { + const next = random(777); + const nodes = buildRandomNodes(next, 50); + const ranges = [ + { anchor: trajectoryNodeKey(nodes[3]), focus: trajectoryNodeKey(nodes[40]) }, + { anchor: trajectoryNodeKey(nodes[40]), focus: trajectoryNodeKey(nodes[3]) }, + { anchor: trajectoryNodeKey(nodes[7]), focus: trajectoryNodeKey(nodes[7]) }, + { anchor: trajectoryNodeKey(nodes[0]), focus: 'not-a-node-key' }, + { anchor: '["missing","model","x"]', focus: trajectoryNodeKey(nodes[1]) }, + { anchor: 'not-json', focus: trajectoryNodeKey(nodes[1]) }, + { anchor: '["only-two",1]', focus: trajectoryNodeKey(nodes[1]) }, + ]; + for (const range of ranges) { + expect(resolveTrajectoryRange(nodes, range)).toEqual(referenceResolve(nodes, range)); + } + expect(resolveTrajectoryRange(nodes, null)).toBeNull(); + expect(resolveTrajectoryRange([], ranges[0])).toBe(referenceResolve([], ranges[0])); + }); + + it('resolves identities that need JSON escaping in their id', () => { + const awkward = [ + node({ id: 'quote"inside', turnId: 'turn\\back', kind: 'tool' }), + node({ id: 'line\nbreak', turnId: 'turn\u0000nul', kind: 'model' }), + node({ id: '中文标识', turnId: '轮次', kind: 'user' }), + ]; + const range = { anchor: trajectoryNodeKey(awkward[0]), focus: trajectoryNodeKey(awkward[2]) }; + expect(resolveTrajectoryRange(awkward, range)).toEqual([0, 2]); + expect(resolveTrajectoryRange(awkward, range)).toEqual(referenceResolve(awkward, range)); + for (const target of awkward) { + const single = { anchor: trajectoryNodeKey(target), focus: trajectoryNodeKey(target) }; + expect(resolveTrajectoryRange(awkward, single)).toEqual(referenceResolve(awkward, single)); + } + }); + + it('keeps an endpoint on the same node after a page is prepended', () => { + const next = random(99); + const page = buildRandomNodes(next, 30, 'old-'); + const older = buildRandomNodes(next, 12, 'older-'); + const range = { anchor: trajectoryNodeKey(page[4]), focus: trajectoryNodeKey(page[9]) }; + expect(resolveTrajectoryRange(page, range)).toEqual([4, 9]); + expect(resolveTrajectoryRange([...older, ...page], range)).toEqual([16, 21]); + expect(referenceResolve([...older, ...page], range)).toEqual([16, 21]); + }); + + it('picks the first match when a page repeats an identity', () => { + const repeated = [ + node({ id: 'x', turnId: 't', kind: 'tool' }), + node({ id: 'y', turnId: 't', kind: 'tool' }), + node({ id: 'x', turnId: 't', kind: 'tool' }), + ]; + const range = { anchor: trajectoryNodeKey(repeated[2]), focus: trajectoryNodeKey(repeated[1]) }; + expect(resolveTrajectoryRange(repeated, range)).toEqual(referenceResolve(repeated, range)); + }); +}); From 7ce987a51c03e18fb39bf2d68b5c699abfa3d6a6 Mon Sep 17 00:00:00 2001 From: Raing5Days Date: Tue, 17 Nov 2026 14:20:33 +0800 Subject: [PATCH 3/5] perf(file-tree): avoid rebuilding reveal path patterns Hoist reusable regular expressions and replace per-item `.map/.filter` work with a single loop while preserving path normalization and casing semantics. --- .../tools/file-system/utils/fileTreeReveal.ts | 59 +++++++++++++------ 1 file changed, 42 insertions(+), 17 deletions(-) diff --git a/src/web-ui/src/tools/file-system/utils/fileTreeReveal.ts b/src/web-ui/src/tools/file-system/utils/fileTreeReveal.ts index d74ce1f034..def016c14e 100644 --- a/src/web-ui/src/tools/file-system/utils/fileTreeReveal.ts +++ b/src/web-ui/src/tools/file-system/utils/fileTreeReveal.ts @@ -1,33 +1,58 @@ import { repositoryPathKey } from '@/shared/utils/pathUtils'; import type { FlatFileNode } from '../types'; +// Compiled once. The function is called for every reveal, and building these patterns per +// call showed up as a real share of the cost on long paths. +const WINDOWS_ABSOLUTE = /^[a-z]:[/\\]/i; +const WINDOWS_DRIVE_ONLY = /^[a-z]:$/i; +const TRAILING_SLASHES = /\/+$/; +const SLASHES = /\//g; +const BACKSLASHES = /\\/g; + +function toForwardSlashes(path: string, windows: boolean): string { + // A remote path is not Windows: its backslashes are literal name characters, so they stay. + if (!windows || path.indexOf('\\') === -1) return path; + return path.replace(BACKSLASHES, '/'); +} + +function stripTrailingSlashes(path: string): string { + return path.charCodeAt(path.length - 1) === 47 ? path.replace(TRAILING_SLASHES, '') : path; +} + /** Plan ancestor expansion using the target filesystem's path semantics. */ export function planFileTreeReveal(root: string, target: string, remote = false): { pathsToExpand: string[]; targetPath: string; } | null { if (!root || !target) return null; - const windows = !remote && (/^[a-z]:[/\\]/i.test(root) || root.startsWith('\\\\')); - const normalize = (path: string) => (windows ? path.replace(/\\/g, '/') : path).replace(/\/+$/, '') || '/'; - const normalizedRoot = normalize(root); - const normalizedTarget = normalize(target); - const compare = (path: string) => windows ? path.toLowerCase() : path; + const windows = !remote && (WINDOWS_ABSOLUTE.test(root) || root.startsWith('\\\\')); + const normalizedRoot = stripTrailingSlashes(toForwardSlashes(root, windows)) || '/'; + const normalizedTarget = stripTrailingSlashes(toForwardSlashes(target, windows)) || '/'; + // Lowercased copies are only for comparison: the returned paths keep the caller's casing. + const comparedRoot = windows ? normalizedRoot.toLowerCase() : normalizedRoot; + const comparedTarget = windows ? normalizedTarget.toLowerCase() : normalizedTarget; const prefix = normalizedRoot === '/' ? '/' : `${normalizedRoot}/`; - if (compare(normalizedTarget) !== compare(normalizedRoot) - && !compare(normalizedTarget).startsWith(compare(prefix))) return null; + const comparedPrefix = windows ? prefix.toLowerCase() : prefix; + if (comparedTarget !== comparedRoot && !comparedTarget.startsWith(comparedPrefix)) return null; - const parts = normalizedTarget.slice(normalizedRoot === '/' ? 1 : normalizedRoot.length).split('/').filter(Boolean); + const parts = normalizedTarget.slice(normalizedRoot === '/' ? 1 : normalizedRoot.length).split('/'); // Paths from a host are absolute. Do not let an unnormalized path escape the tree. - if (parts.some(part => part === '.' || part === '..')) return null; - const native = (path: string) => { - const absolute = windows && /^[a-z]:$/i.test(path) ? `${path}/` : path; - return windows && root.includes('\\') ? absolute.replace(/\//g, '\\') : absolute; - }; + for (const part of parts) { + if (part === '.' || part === '..') return null; + } + const backslashOutput = windows && root.includes('\\'); let currentPath = normalizedRoot; - const pathsToExpand = parts.map(part => { + const pathsToExpand: string[] = []; + for (const part of parts) { + if (!part) continue; currentPath = `${currentPath === '/' ? '' : currentPath}/${part}`; - return native(currentPath); - }); - return { pathsToExpand, targetPath: native(currentPath) }; + const absolute = windows && WINDOWS_DRIVE_ONLY.test(currentPath) ? `${currentPath}/` : currentPath; + pathsToExpand.push(backslashOutput ? absolute.replace(SLASHES, '\\') : absolute); + } + const targetPath = windows && WINDOWS_DRIVE_ONLY.test(currentPath) ? `${currentPath}/` : currentPath; + return { + pathsToExpand, + targetPath: backslashOutput ? targetPath.replace(SLASHES, '\\') : targetPath, + }; } /** Address the data row, including compressed folders, rather than rendered DOM. */ From 7524b3ea8f139ba5524bb0ddb8aa7a148dd23f19 Mon Sep 17 00:00:00 2001 From: Raing5Days Date: Tue, 17 Nov 2026 14:20:43 +0800 Subject: [PATCH 4/5] perf(flow-chat): skip empty image-budget route scan Return early when no selectable route exists and use a Set plus one pass to compute the narrowest native-image ceiling, preserving the previous model selection semantics. --- .../src/flow_chat/utils/modelImageBudget.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/web-ui/src/flow_chat/utils/modelImageBudget.ts b/src/web-ui/src/flow_chat/utils/modelImageBudget.ts index e728989401..a632586801 100644 --- a/src/web-ui/src/flow_chat/utils/modelImageBudget.ts +++ b/src/web-ui/src/flow_chat/utils/modelImageBudget.ts @@ -11,9 +11,17 @@ export function modelSelectionImageLimit( const candidateIds = roots.filter(isSelectableTextChatModel).flatMap(model => model.channel_routing?.manual_channel ? [model.channel_routing.manual_channel] : [model.id, ...(model.channel_routing?.fallback_model_ids ?? [])]); - const limits = models.filter(model => candidateIds.includes(model.id) - && isSelectableTextChatModel(model) && getEffectiveModelCapabilities(model).includes('image_understanding')) - .map(model => model.max_images_per_request) - .filter((limit): limit is number => typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0); - return limits.length > 0 ? Math.min(...limits) : undefined; + // With no selectable primary/pool route no model can match. Skip the full scan: the selector + // reaches this state whenever no native model is resolved yet (a common render path). + if (candidateIds.length === 0) return undefined; + const candidateSet = new Set(candidateIds); + let minLimit: number | undefined; + for (const model of models) { + if (!model.id || !candidateSet.has(model.id)) continue; + if (!isSelectableTextChatModel(model) || !getEffectiveModelCapabilities(model).includes('image_understanding')) continue; + const limit = model.max_images_per_request; + if (typeof limit !== 'number' || !Number.isSafeInteger(limit) || limit <= 0) continue; + minLimit = minLimit === undefined ? limit : Math.min(minLimit, limit); + } + return minLimit; } From 0dccd698a7b8b03fed21288dd54dfac791d3b766 Mon Sep 17 00:00:00 2001 From: Raing5Days Date: Tue, 17 Nov 2026 14:37:14 +0800 Subject: [PATCH 5/5] perf(global-search): overlap session navigation reads Starting the workspace activation and the search-hit metadata read together removes one host round trip from the critical path of opening a session found through global search, which is most noticeable when the target lives in another workspace. --- .../globalSearchActivator.test.ts | 87 +++++++++++++++++++ .../global-search/globalSearchActivator.ts | 8 +- 2 files changed, 93 insertions(+), 2 deletions(-) create mode 100644 src/web-ui/src/app/global-search/globalSearchActivator.test.ts diff --git a/src/web-ui/src/app/global-search/globalSearchActivator.test.ts b/src/web-ui/src/app/global-search/globalSearchActivator.test.ts new file mode 100644 index 0000000000..afd7c38a6e --- /dev/null +++ b/src/web-ui/src/app/global-search/globalSearchActivator.test.ts @@ -0,0 +1,87 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + openMainSession: vi.fn(), + ensurePersistedSessionMetadata: vi.fn(), + getSession: vi.fn(), + applyWorkspace: vi.fn(), + dispatchHistorySessionOpenIntent: vi.fn(), +})); + +vi.mock('@/flow_chat/services/sessionActivation', () => ({ openMainSession: mocks.openMainSession })); +vi.mock('@/flow_chat/services/sessionOpenIntent', () => ({ + dispatchHistorySessionOpenIntent: mocks.dispatchHistorySessionOpenIntent, +})); +vi.mock('@/flow_chat/store/FlowChatStore', () => ({ + flowChatStore: { + ensurePersistedSessionMetadata: mocks.ensurePersistedSessionMetadata, + getState: () => ({ sessions: { get: mocks.getSession } }), + }, +})); +vi.mock('@/app/services/AppManager', () => ({ appManager: { updateLayout: vi.fn() } })); +vi.mock('@/app/stores/sceneStore', () => ({ useSceneStore: { getState: () => ({ openScene: vi.fn() }) } })); +vi.mock('@/app/scenes/settings/settingsStore', () => ({ useSettingsStore: { getState: () => ({ openDestination: vi.fn() }) } })); +vi.mock('@/infrastructure/event-bus', () => ({ globalEventBus: { emit: vi.fn() } })); +vi.mock('@/shared/utils/tabUtils', () => ({ openFileInBestTarget: vi.fn() })); +vi.mock('./productActionActivator', () => ({ activateProductAction: vi.fn() })); +vi.mock('./interactiveCapabilityActivator', () => ({ activateInteractiveCapability: vi.fn() })); + +import { activateGlobalSearchTarget } from './globalSearchActivator'; +import type { GlobalSearchActivationContext } from './globalSearchActivator'; + +function context(): GlobalSearchActivationContext { + return { + setActiveWorkspace: mocks.applyWorkspace, + selectAssistantWorkspace: vi.fn(), + openAssistant: vi.fn(), + tCommon: (key: string) => key, + }; +} + +describe('activateGlobalSearchTarget session navigation', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.applyWorkspace.mockResolvedValue(undefined); + mocks.ensurePersistedSessionMetadata.mockResolvedValue(true); + mocks.openMainSession.mockResolvedValue(undefined); + mocks.getSession.mockReturnValue({ title: 'target' }); + }); + + it('starts workspace activation and session metadata loading together', async () => { + let releaseWorkspace!: () => void; + let releaseMetadata!: () => void; + const workspacePending = new Promise(resolve => { releaseWorkspace = resolve; }); + const metadataPending = new Promise(resolve => { releaseMetadata = resolve; }); + mocks.applyWorkspace.mockImplementation(async () => { await workspacePending; }); + let metadataStarted = false; + mocks.ensurePersistedSessionMetadata.mockImplementation(async () => { + metadataStarted = true; + await metadataPending; + return true; + }); + + const navigation = activateGlobalSearchTarget({ + kind: 'session', sessionId: 'target', workspaceId: 'workspace', workspacePath: '/workspace', + }, context()); + await Promise.resolve(); + await Promise.resolve(); + expect(metadataStarted).toBe(true); + releaseMetadata(); + releaseWorkspace(); + await navigation; + + expect(mocks.applyWorkspace).toHaveBeenCalledWith('workspace'); + expect(mocks.ensurePersistedSessionMetadata).toHaveBeenCalledWith('target', 'workspace'); + expect(mocks.openMainSession).toHaveBeenCalledWith('target'); + }); + + it('reports an unavailable session without opening it', async () => { + mocks.applyWorkspace.mockResolvedValue(undefined); + mocks.ensurePersistedSessionMetadata.mockResolvedValue(false); + + await expect(activateGlobalSearchTarget({ + kind: 'session', sessionId: 'missing', workspaceId: 'workspace', workspacePath: '/workspace', + }, context())).rejects.toThrow('nav.search.errors.sessionUnavailable'); + expect(mocks.openMainSession).not.toHaveBeenCalled(); + }); +}); diff --git a/src/web-ui/src/app/global-search/globalSearchActivator.ts b/src/web-ui/src/app/global-search/globalSearchActivator.ts index d610544e60..48837eaa30 100644 --- a/src/web-ui/src/app/global-search/globalSearchActivator.ts +++ b/src/web-ui/src/app/global-search/globalSearchActivator.ts @@ -43,11 +43,15 @@ export async function activateGlobalSearchTarget( useSceneStore.getState().openScene('assistant'); return; case 'session': { - await context.setActiveWorkspace(target.workspaceId); - const available = await flowChatStore.ensurePersistedSessionMetadata( + // The search hit may only exist in the index, so load its metadata before activation. + // The workspace switch is a host round trip and the metadata read addresses the target + // workspace directly, so start both together instead of paying them one after the other. + const workspaceActivation = context.setActiveWorkspace(target.workspaceId); + const metadata = flowChatStore.ensurePersistedSessionMetadata( target.sessionId, target.workspaceId, ); + const [available] = await Promise.all([metadata, workspaceActivation]); if (!available) { throw new Error(context.tCommon('nav.search.errors.sessionUnavailable')); }