Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions src/web-ui/src/app/global-search/globalSearchActivator.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>(resolve => { releaseWorkspace = resolve; });
const metadataPending = new Promise<boolean>(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();
});
});
8 changes: 6 additions & 2 deletions src/web-ui/src/app/global-search/globalSearchActivator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
}
Expand Down
175 changes: 175 additions & 0 deletions src/web-ui/src/flow_chat/trajectory/trajectoryRange.test.ts
Original file line number Diff line number Diff line change
@@ -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<TrajectoryNode> & Pick<TrajectoryNode, 'id' | 'turnId' | 'kind'>): 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));
});
});
95 changes: 84 additions & 11 deletions src/web-ui/src/flow_chat/trajectory/trajectoryRange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') };
}
Loading
Loading