Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
fix(search): complete direct paged result navigation
YToolbox8e0e2ecdd324
diff --git a/src/main/features/chats.ts b/src/main/features/chats.tsindex 26774f54..597504c8 100644--- a/src/main/features/chats.ts+++ b/src/main/features/chats.ts@@ -2022,21 +2022,38 @@ export async function getMessagesPage(return { history, nextCursor };}-/** Load the fixed-size history page containing one search-result record. */+/** Load from the fixed-size page containing a search hit through the newest+ * record. The search index gives us the absolute record index, so this is one+ * direct forward read rather than a renderer-driven chain of older-page IPC+ * requests. `nextCursor` still points immediately before the target page so+ * normal upward pagination remains available. */export async function getMessagesPageAtIndex(userId: string,cid: string,messageIndex: number,limit = 10,projectIdHint?: string | null,-): Promise<{ history: MessageRecord[]; nextCursor: number | null; pageStart: number }> {+): Promise<{+ history: MessageRecord[];+ historyIndexes: number[];+ nextCursor: number | null;+ pageStart: number;+}> {const file = conversationMessageReadFile(userId, cid, projectIdHint);const wanted = Math.max(1, Math.floor(Number(limit) || 1));const index = Math.max(0, Math.floor(Number(messageIndex) || 0));const pageStart = Math.floor(index / wanted) * wanted;- const page = await readJsonlWindow<MessageRecord>(file, pageStart, wanted);+ const page = await readJsonlWindow<MessageRecord>(file, pageStart, Number.MAX_SAFE_INTEGER);+ const visible = page.records+ .map((message, offset) => ({ message, index: pageStart + offset }))+ .filter(({ message }) => !message.deleted_at);return {- history: page.records.filter((message) => !message.deleted_at),+ history: visible.map(({ message }) => message),+ // Keep the source JSONL indexes aligned with `history`. The renderer uses+ // this as the final navigation identity for old records that predate+ // stable message ids/timestamps; filtering a tombstone must not shift the+ // remaining page-relative offsets.+ historyIndexes: visible.map(({ index: recordIndex }) => recordIndex),nextCursor: page.previousCursor,pageStart,};diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 0c0c60f3..7681cbcd 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -806,7 +806,10 @@ const invokeHandlers: Record<string, InvokeHandler> = {conversation: { ...conv, ...runtime, agent_enabled },history: page.history,next_cursor: page.nextCursor,- ...(hasAroundIndex && 'pageStart' in page ? { page_start: page.pageStart } : {}),+ ...(hasAroundIndex && 'pageStart' in page && 'historyIndexes' in page ? {+ page_start: page.pageStart,+ history_indexes: page.historyIndexes,+ } : {}),};},diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.jsindex c552d643..df4e57ed 100644--- a/src/renderer/modules/conversation.js+++ b/src/renderer/modules/conversation.js@@ -2454,6 +2454,7 @@ function _groupMsgToLegacy(gm) {...(gm.failure_kind ? { failure_kind: gm.failure_kind } : {}),...(gm.failure_code ? { failure_code: gm.failure_code } : {}),...(_groupMessageSystemKind(gm) ? { _system_kind: _groupMessageSystemKind(gm) } : {}),+ ...(Number.isSafeInteger(gm._history_index) ? { _history_index: gm._history_index } : {}),};return out;}@@ -4742,6 +4743,11 @@ function _findConversationHistorySearchTarget(container, target = {}) {const byId = messages.find((message) => String(message.dataset?.msgId || '') === msgId);if (byId) return byId;}+ const msgIndex = Number(target.msgIndex);+ if (Number.isSafeInteger(msgIndex) && msgIndex >= 0) {+ const byIndex = messages.find((message) => Number(message.dataset?.msgIndex) === msgIndex);+ if (byIndex) return byIndex;+ }const targetTs = _msTs(target.time);if (!targetTs) return null;const role = target.role === 'user' || target.role === 'assistant' ? target.role : '';@@ -4753,7 +4759,28 @@ function _findConversationHistorySearchTarget(container, target = {}) {function _flashConversationHistorySearchTarget(target) {if (!target) return;- target.scrollIntoView({ block: 'center' });+ const container = target.closest?.('.chat-history') || target.parentElement;+ if (container) {+ // `.chat-history` has CSS smooth scrolling for ordinary navigation. A+ // search hit is an exact address, so assign scrollTop directly and mark+ // the resulting event as programmatic. Besides making the jump instant,+ // this prevents the top-of-page auto-loader from interpreting the jump as+ // user intent and walking through earlier pages one by one.+ const previousBehavior = container.style?.scrollBehavior || '';+ if (container.style) container.style.scrollBehavior = 'auto';+ _markProgrammaticStickyScroll(container);+ const containerRect = container.getBoundingClientRect();+ const targetRect = target.getBoundingClientRect();+ const centeredTop = Number(container.scrollTop || 0)+ + targetRect.top - containerRect.top+ - (Number(container.clientHeight || 0) - targetRect.height) / 2;+ container.scrollTop = Math.max(0, centeredTop);+ container._stickyEnabled = false;+ container._stickyUserPaused = true;+ requestAnimationFrame(() => {+ if (container.style) container.style.scrollBehavior = previousBehavior;+ });+ }target.classList.add('search-flash');setTimeout(() => target.classList.remove('search-flash'), 1600);}@@ -4857,8 +4884,24 @@ async function loadConversationHistory(cid, opts = {}) {// agent's visibility slice still carries dispatches so the agent has the// dispatch text in its own context.const renderStartedAt = performance.now();+ const rawHistory = Array.isArray(data.history) ? data.history : [];+ const responseIndexes = Array.isArray(data.history_indexes) ? data.history_indexes : [];+ const responsePageStart = Number(data.page_start);+ const indexedHistory = rawHistory.map((gm, offset) => {+ if (!gm || typeof gm !== 'object') return gm;+ const explicitIndex = Number(responseIndexes[offset]);+ const fallbackIndex = Number.isSafeInteger(responsePageStart) && responsePageStart >= 0+ ? responsePageStart + offset+ : Number.NaN;+ const sourceIndex = Number.isSafeInteger(explicitIndex) && explicitIndex >= 0+ ? explicitIndex+ : fallbackIndex;+ return Number.isSafeInteger(sourceIndex) && sourceIndex >= 0+ ? { ...gm, _history_index: sourceIndex }+ : gm;+ });const visibleGroupHistory = _collapseSupersededInterruptionRecords(- (data.history || []).filter(_isVisibleGroupHistoryRecord),+ indexedHistory.filter(_isVisibleGroupHistoryRecord),);const history = visibleGroupHistory.map(_groupMsgToLegacy)@@ -4876,9 +4919,12 @@ async function loadConversationHistory(cid, opts = {}) {// tree scans. Live messages and recovery paths still use the guarded// incremental insertion path below.const historyFragment = document.createDocumentFragment();- history.forEach((msg, idx) => appendChatMessage(msg, false, {+ history.forEach((msg) => appendChatMessage(msg, false, {cid,- msgIndex: idx,+ // Only stamp authoritative source indexes returned by an anchored+ // history read. A normal latest-page row has no global index; using+ // its local 0..9 offset would let a later search falsely match it.+ msgIndex: Number.isSafeInteger(msg?._history_index) ? msg._history_index : undefined,container: historyFragment,historyHydration: true,}));diff --git a/test/main/features/chats.test.ts b/test/main/features/chats.test.tsindex 3e7a083c..7b89a5c1 100644--- a/test/main/features/chats.test.ts+++ b/test/main/features/chats.test.ts@@ -131,7 +131,7 @@ describe('chats › message history tombstones', () => {expect(earlier.nextCursor).toBeNull();});- it('loads the fixed history page containing a search message index', async () => {+ it('loads from the search target page through the newest message', async () => {const chats = await loadChats();const conv = await chats.createConversation(TEST_UID, { title: 'search target' });const file = path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`);@@ -149,10 +149,36 @@ describe('chats › message history tombstones', () => {expect(page.pageStart).toBe(20);expect(page.history.map((row) => row.id)).toEqual(['m20', 'm21', 'm22', 'm23', 'm24', 'm25', 'm26', 'm27', 'm28', 'm29',+ 'm30', 'm31', 'm32', 'm33', 'm34',+ ]);+ expect(page.historyIndexes).toEqual([+ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,]);expect(page.nextCursor).not.toBeNull();});+ it('keeps source indexes aligned when an anchored page contains tombstones or legacy rows', async () => {+ const chats = await loadChats();+ const conv = await chats.createConversation(TEST_UID, { title: 'legacy search target' });+ const file = path.join(tmpDir, TEST_UID, 'cloud', 'chats', `${conv.conversation_id}.jsonl`);+ const rows = Array.from({ length: 35 }, (_, i) => {+ if (i === 21) {+ return { id: 'm21', from: 'user', text: 'deleted', deleted_at: '2026-07-10T11:00:00' };+ }+ if (i === 23) return { from: 'commander', text: 'legacy target without identity' };+ return { id: `m${i}`, from: i % 2 ? 'commander' : 'user', text: `message ${i}` };+ });+ fs.writeFileSync(file, rows.map((row) => JSON.stringify(row)).join('\n') + '\n');++ const page = await chats.getMessagesPageAtIndex(TEST_UID, conv.conversation_id, 23, 10);++ expect(page.pageStart).toBe(20);+ expect(page.history.map((row) => row.text)).toContain('legacy target without identity');+ expect(page.historyIndexes).toEqual([+ 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,+ ]);+ });+it('keeps an explicit global history read out of a duplicate project root', async () => {const chats = await loadChats();const projects = await import('../../../src/main/features/projects');diff --git a/test/renderer/global-search-navigation.test.ts b/test/renderer/global-search-navigation.test.tsindex d42a0062..76915c6c 100644--- a/test/renderer/global-search-navigation.test.ts+++ b/test/renderer/global-search-navigation.test.ts@@ -8,6 +8,7 @@ const searchSource = fs.readFileSync(path.join(root, 'src/renderer/modules/searcconst bootSource = fs.readFileSync(path.join(root, 'src/renderer/modules/boot.js'), 'utf8');const conversationSource = fs.readFileSync(path.join(root, 'src/renderer/modules/conversation.js'), 'utf8');const ipcSource = fs.readFileSync(path.join(root, 'src/main/ipc/index.ts'), 'utf8');+const chatsSource = fs.readFileSync(path.join(root, 'src/main/features/chats.ts'), 'utf8');function extractFunction(source: string, name: string): string {const asyncMarker = `async function ${name}`;@@ -39,8 +40,14 @@ describe('global search conversation navigation', () => {expect(bootSource).toContain('{ searchTarget: opts.historyTarget }');expect(bootSource).toContain('_revealConversationHistorySearchTarget(cid, opts.historyTarget)');expect(ipcSource).toContain('chats.getMessagesPageAtIndex(');+ expect(ipcSource).toContain('history_indexes: page.historyIndexes');+ expect(chatsSource).toContain(+ 'readJsonlWindow<MessageRecord>(file, pageStart, Number.MAX_SAFE_INTEGER)',+ );const loadStart = conversationSource.indexOf('async function loadConversationHistory');const loadBody = conversationSource.slice(loadStart, conversationSource.indexOf('\nfunction _messageRecordHasMountedSidecars', loadStart));+ expect(loadBody).toContain('Array.isArray(data.history_indexes)');+ expect(loadBody).toContain('_history_index: sourceIndex');expect(loadBody.indexOf('_revealConversationHistorySearchTarget(cid, opts.searchTarget)')).toBeLessThan(loadBody.indexOf('await _evaluateAutoRecipient(cid)'),);@@ -69,28 +76,42 @@ describe('global search conversation navigation', () => {expect(conversationSource).not.toContain('HISTORY_SEARCH_PAGE_SIZE');});- it('highlights the target immediately without smooth scrolling or catch-up loads', () => {+ it('positions an identity-less legacy target by its global index without catch-up loads', () => {const added: string[] = [];- let scrolled = false;+ let olderLoads = 0;+ const container: any = {+ scrollTop: 0,+ clientHeight: 400,+ style: { scrollBehavior: '' },+ getBoundingClientRect: () => ({ top: 0, height: 400 }),+ querySelectorAll: () => [matched],+ querySelector: () => ({ dataset: { state: 'idle', cursor: '100', cid: 'c1' } }),+ };const matched = {- dataset: { msgId: 'target-message', ts: '10' },+ dataset: { msgIndex: '23' },classList: {contains: () => true,add: (name: string) => added.push(name),remove: (name: string) => added.push(`removed:${name}`),},- scrollIntoView: () => { scrolled = true; },- };- const container = {- querySelectorAll: () => [matched],+ closest: () => container,+ getBoundingClientRect: () => ({ top: 100, height: 50 }),};const context: any = {Array,+ Math,Number,String,+ HISTORY_AUTO_LOAD_THRESHOLD: 48,currentCid: 'c1',document: { getElementById: () => container },_msTs: () => 0,+ _markProgrammaticStickyScroll: (el: any) => { el._programmatic = true; },+ _isProgrammaticStickyScroll: (el: any) => el._programmatic === true,+ _loadOlderConversationHistory: () => { olderLoads += 1; },+ _historyNextCursor: (value: unknown) => Number(value),+ _setEarlierHistoryLoaderState: () => {},+ requestAnimationFrame: (fn: () => void) => { fn(); return 1; },setTimeout: (fn: () => void) => { fn(); return 1; },};vm.createContext(context);@@ -98,15 +119,19 @@ describe('global search conversation navigation', () => {extractFunction(conversationSource, '_findConversationHistorySearchTarget'),extractFunction(conversationSource, '_flashConversationHistorySearchTarget'),extractFunction(conversationSource, '_revealConversationHistorySearchTarget'),+ extractFunction(conversationSource, '_maybeAutoLoadEarlierHistory'),].join('\n'), context);const found = context._revealConversationHistorySearchTarget('c1', {- msgId: 'target-message',+ msgIndex: 23,});+ context._maybeAutoLoadEarlierHistory(container);expect(found).toBe(true);- expect(scrolled).toBe(true);+ expect(container.scrollTop).toBe(0);+ expect(container._stickyEnabled).toBe(false);+ expect(olderLoads).toBe(0);expect(added).toEqual(['search-flash', 'removed:search-flash']);- expect(conversationSource).not.toContain("behavior: 'smooth', block: 'center'");+ expect(conversationSource).not.toContain("target.scrollIntoView({ block: 'center' })");});});