You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by as...@apache.org on 2026/09/11 08:52:46 UTC

(maka) 03/03: fix(desktop): give the WorkHub transcript the pixel band

This is an automated email from the ASF dual-hosted git repository.

Astro-Han pushed a commit to branch refactor/transcript-renderer-window
in repository https://gitbox.apache.org/repos/asf/maka.git

commit b239a9b39b381f00a880300a45d6abfb01731892
Author: AstroHan <le...@outlook.com>
AuthorDate: Fri Sep 11 16:52:36 2026 +0800

    fix(desktop): give the WorkHub transcript the pixel band
    
    WorkHub mounts the same ChatView as the chat surface but was wired
    without the band: no automatic fill, no trim, an explicit "older"
    button instead. Two consequences of the Renderer-owned window followed.
    Every page the button loaded was retained forever, where Main used to
    bound every consumer's window. And a window behind the tail never
    followed it — Main used to splice tail growth into whatever window it
    held — so a queued follow-up's own row never arrived, the observation
    check never satisfied, and the next follow-up was refused as a retry.
    
    The WorkHub transcript port now carries `prefetchHistory` and `retain`,
    delegated to the same range controller the chat surface uses, and the
    ChatView gets the band's callbacks. The "older" button goes with it.
    Queuing a follow-up returns the window to the tail before admission, on
    every admission outcome, so the queued row lands and the guard clears.
    A trim publishes the trimmed snapshot: it is the one window change with
    no batch behind it.
    
    Generated-by: Claude Code
---
 apps/desktop/e2e/workhub-layout.spec.ts            |  6 +-
 ...workhub-coordination-transcript-preload.test.ts | 75 ++++++++++++++++++++++
 .../main/__tests__/workhub-send-visibility.test.ts | 37 ++++++++++-
 .../workhub/controller/use-workhub-controller.ts   | 15 +++--
 .../features/workhub/locales/workhub-live-copy.ts  |  3 -
 .../desktop/src/renderer/features/workhub/ports.ts |  5 +-
 .../renderer/features/workhub/ui/workhub-root.tsx  | 14 ++--
 .../platform/desktop/create-workhub-services.ts    | 14 +++-
 apps/desktop/stories/workhub.stories.tsx           |  2 +-
 9 files changed, 149 insertions(+), 22 deletions(-)

diff --git a/apps/desktop/e2e/workhub-layout.spec.ts b/apps/desktop/e2e/workhub-layout.spec.ts
index 48e45c0adb..ff9364d83f 100644
--- a/apps/desktop/e2e/workhub-layout.spec.ts
+++ b/apps/desktop/e2e/workhub-layout.spec.ts
@@ -368,7 +368,11 @@ test('WorkHub keeps the submitted prompt visible while its agent is still runnin
   await workhub.locator(COMPOSER_INPUT).fill('立即调整方向,保持当前任务');
   await workhub.locator(COMPOSER_INPUT).press('Shift+Enter');
   await expect(workhub.locator('.maka-bubble-streaming')).toContainText('Acknowledged steering: 立即调整方向,保持当前任务');
-  await expect(workhub.locator('.maka-user-message').filter({ hasText: '立即调整方向,保持当前任务' })).toHaveCount(1);
+  const steered = workhub.locator('.maka-user-message').filter({ hasText: '立即调整方向,保持当前任务' });
+  await expect(steered).toHaveCount(1);
+  // A queued message is only ever durable at the tail, so sending one has to
+  // take the window and the reader there.
+  await expect(steered).toBeInViewport();
   await expect(followups).toHaveText(queuedTexts);
   await expect(stop).toBeVisible();
   await stop.click();
diff --git a/apps/desktop/src/main/__tests__/workhub-coordination-transcript-preload.test.ts b/apps/desktop/src/main/__tests__/workhub-coordination-transcript-preload.test.ts
index 87a41449bd..1e72a6e5cd 100644
--- a/apps/desktop/src/main/__tests__/workhub-coordination-transcript-preload.test.ts
+++ b/apps/desktop/src/main/__tests__/workhub-coordination-transcript-preload.test.ts
@@ -29,6 +29,7 @@ import type { StoredMessage } from '@maka/core/session';
 import type { MakaBridge } from '../../preload/bridge-contract.js';
 import type { DesktopTranscriptBatch, DesktopTranscriptRangeRequest } from '../../preload/transcript-contract.js';
 import { createDesktopWorkHubServices } from '../../renderer/platform/desktop/create-workhub-services.js';
+import type { WorkHubTranscriptSnapshot } from '../../renderer/features/workhub/index.js';
 import { desktopSessionKey } from '../../shared/runtime-host-identity.js';
 import { encodeDesktopTranscriptPage, encodeDesktopTranscriptSnapshot } from '../desktop-transcript-ipc.js';
 import type { AttachmentRef } from '@maka/core/events';
@@ -524,3 +525,77 @@ for (const initial of ['failure-before-ready', 'failure-after-ready', 'cached']
     }
   });
 }
+
+test('WorkHub fills and trims its transcript window through the reader band', async (t) => {
+  const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
+  Object.defineProperty(globalThis, 'window', { configurable: true, value: { location: { search: '?surface=workhub' } } });
+  t.after(() => {
+    if (originalWindow) Object.defineProperty(globalThis, 'window', originalWindow);
+    else Reflect.deleteProperty(globalThis, 'window');
+  });
+  const sessionId = desktopSessionKey({ hostId: 'owner-host', sessionId: 'coordination' });
+  const identity = { sessionId: 'coordination', generation: 'generation-1', hostEpoch: 'epoch-1' };
+  const row = (sequence: number, turnId: string): { sequence: number; message: StoredMessage } => ({
+    sequence, message: { type: 'user', id: `message-${sequence}`, turnId, ts: sequence, text: `Record ${sequence}` },
+  });
+  let deliverySequence = 0;
+  let newerReads = 0;
+  let olderReads = 0;
+  let snapshots: WorkHubTranscriptSnapshot[] = [];
+  const services = createDesktopWorkHubServices({
+    attachments: {},
+    transcripts: {
+      async open(_sessionId: string, onBatch: (batch: DesktopTranscriptBatch) => void) {
+        for (const batch of encodeDesktopTranscriptSnapshot({
+          ...identity, durableThrough: 4, overlay: [], hasOlder: true, hasNewer: true,
+          durable: [row(2, 'turn-a'), row(3, 'turn-b')],
+        })) onBatch({ ...batch, deliverySequence: ++deliverySequence });
+        return {
+          ...identity, durableThrough: 4, hasOlder: true, hasNewer: true, readThroughMessageId: 'message-3',
+          acknowledgeTail: async () => {},
+          loadBefore: async () => { olderReads += 1; },
+          loadAround: async () => {},
+          loadLatest: async () => {},
+          async loadAfter(anchor: number | null, _maxBytes: number | undefined, navigation: { navigation: number }) {
+            newerReads += 1;
+            assert.equal(anchor, 3);
+            for (const batch of encodeDesktopTranscriptPage(
+              { ...identity, navigation: navigation.navigation },
+              { durableThrough: 4, hasNewer: false, durable: [row(4, 'turn-c')] },
+              { direction: 'newer', anchor },
+            )) onBatch({ ...batch, deliverySequence: ++deliverySequence });
+          },
+          close: async () => undefined,
+        };
+      },
+    } satisfies Pick<MakaBridge['transcripts'], 'open'>,
+  } as unknown as Parameters<typeof createDesktopWorkHubServices>[0]);
+  const handle = await services.openTranscript(
+    sessionId,
+    (snapshot) => { snapshots.push(snapshot); },
+    new AbortController().signal,
+    (error) => { throw error; },
+  );
+  const latest = () => snapshots.at(-1)!;
+  try {
+    await waitFor(() => latest()?.ready === true, { timeoutMs: 5_000 });
+    assert.deepEqual(latest().messages.map(({ turnId }) => turnId), ['turn-a', 'turn-b']);
+    assert.equal(await handle.prefetchHistory('newer'), true);
+    assert.deepEqual(latest().messages.map(({ turnId }) => turnId), ['turn-a', 'turn-b', 'turn-c']);
+    assert.equal(latest().hasNewer, false);
+    assert.equal(await handle.prefetchHistory('newer'), false, 'a window at the tail has no newer edge to read');
+    assert.equal(newerReads, 1);
+    assert.equal(await handle.prefetchHistory('older'), true);
+    assert.equal(await handle.prefetchHistory('older'), false, 'the same window answers an older read the same way');
+    assert.equal(olderReads, 1);
+    snapshots = [];
+    handle.retain({ firstTurnId: 'turn-b', lastTurnId: 'turn-c' });
+    assert.deepEqual(latest().messages.map(({ turnId }) => turnId), ['turn-b', 'turn-c']);
+    assert.equal(latest().hasOlder, true, 'a trimmed edge becomes history again');
+    // A trim moves the window, so the edge it re-opened is worth asking again.
+    assert.equal(await handle.prefetchHistory('older'), true);
+    assert.equal(olderReads, 2);
+  } finally {
+    await handle.close();
+  }
+});
diff --git a/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts b/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts
index 67edc84ba1..8d3e4c705a 100644
--- a/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts
+++ b/apps/desktop/src/main/__tests__/workhub-send-visibility.test.ts
@@ -44,6 +44,8 @@ async function mountController(failFirstRead = false) {
   let publish!: (snapshot: WorkHubTranscriptSnapshot) => void;
   let observe!: Parameters<WorkHubServices['observe']>[1];
   let loadLatestCount = 0;
+  const prefetched: Array<'older' | 'newer'> = [];
+  const retained: Array<{ firstTurnId: string; lastTurnId: string }> = [];
   let admission = deferred<{ turnId: string }>();
   const latestRead = deferred<void>();
   const requests: Array<Parameters<WorkHubServices['answer']>[1]> = [];
@@ -94,7 +96,13 @@ async function mountController(failFirstRead = false) {
       if (failFirstRead && openCount === 1) throw new Error('transient initial read failure');
       publish = handler;
       handler({ messages: [], ready: true, hasOlder: false, hasNewer: false });
-      return { observationChanged: () => {}, loadOlder: async () => {}, loadLatest: () => { loadLatestCount += 1; return latestRead.promise; }, close: async () => {} };
+      return {
+        observationChanged: () => {},
+        prefetchHistory: async (edge: 'older' | 'newer') => { prefetched.push(edge); return true; },
+        retain: (window: { firstTurnId: string; lastTurnId: string }) => { retained.push(window); },
+        loadLatest: () => { loadLatestCount += 1; return latestRead.promise; },
+        close: async () => {},
+      };
     },
     retractQueueEntry: async (...input: Parameters<WorkHubServices['retractQueueEntry']>) => { queueMutations.push(['retract', ...input]); },
     promoteQueueEntry: async (...input: Parameters<WorkHubServices['promoteQueueEntry']>) => { queueMutations.push(['promote', ...input]); },
@@ -125,6 +133,7 @@ async function mountController(failFirstRead = false) {
     resetAdmission() { admission = deferred<{ turnId: string }>(); },
     admit(turnId: string) { rootTurn = { turnId, runId: `run:${turnId}`, status: 'running' }; },
     get loadLatestCount() { return loadLatestCount; },
+    prefetched, retained,
     emit(event: Parameters<typeof observe>[0]) { observe(event); },
     publish(messages: StoredMessage[]) { publish({ messages, ready: true, hasOlder: false, hasNewer: false }); },
   };
@@ -521,6 +530,32 @@ test('WorkHub defaults to follow-up and moves each message into its admitted suc
   h.latestRead.resolve();
 });
 
+test('a queued follow-up returns the window to the tail so its own retry guard can clear', async () => {
+  const h = await mountController();
+  await act(() => h.emit({ type: 'text_delta', id: 'live', turnId: 'active-turn', messageId: 'answer', ts: 1, text: 'Working' }));
+  h.setSteerResult('unknown');
+  await act(async () => { assert.equal(await h.controller.send('queued while parked in history', []), false); });
+  const messageId = h.steers[0]![1];
+  assert.equal(h.loadLatestCount, 1, 'an uncertain enqueue still has to reach the tail to be observed');
+  await act(async () => { assert.equal(await h.controller.send('a different follow-up', []), false); });
+  assert.equal(h.steers.length, 1, 'an unobserved attempt refuses the next follow-up');
+  await act(() => h.publish([{ type: 'user', id: messageId, turnId: 'successor', text: 'queued while parked in history', ts: 2 }]));
+  h.setSteerResult('admitted');
+  await act(async () => { assert.equal(await h.controller.send('a different follow-up', []), true); });
+  assert.equal(h.steers.length, 2, 'the observed row releases the guard');
+  h.latestRead.resolve();
+});
+
+test('the transcript band reaches WorkHub’s window', async () => {
+  const h = await mountController();
+  assert.equal(await h.controller.prefetchHistory('older'), true);
+  assert.equal(await h.controller.prefetchHistory('newer'), true);
+  assert.deepEqual(h.prefetched, ['older', 'newer']);
+  h.controller.retainWindow({ firstTurnId: 'turn-b', lastTurnId: 'turn-c' });
+  assert.deepEqual(h.retained, [{ firstTurnId: 'turn-b', lastTurnId: 'turn-c' }]);
+  h.latestRead.resolve();
+});
+
 test('follow-up admission before an uncertain response keeps its successor placement', async () => {
   const h = await mountController();
   await act(() => h.emit({ type: 'text_delta', id: 'live', turnId: 'active-turn', messageId: 'answer', ts: 1, text: 'Working' }));
diff --git a/apps/desktop/src/renderer/features/workhub/controller/use-workhub-controller.ts b/apps/desktop/src/renderer/features/workhub/controller/use-workhub-controller.ts
index 78ca778d5c..6f405f05d8 100644
--- a/apps/desktop/src/renderer/features/workhub/controller/use-workhub-controller.ts
+++ b/apps/desktop/src/renderer/features/workhub/controller/use-workhub-controller.ts
@@ -387,6 +387,13 @@ export function useWorkHubController() {
           id: attempt.messageId, hostTurnId: queuedTurnId, text, attachments: [...attachments],
           ts: Date.now(), transientPlacement: attempt.placement, pendingSteering: attempt.placement === 'current_turn',
         }]);
+        viewportNavigation.followLatest(target);
+        // A queued message becomes visible only where the tail is, and its own
+        // retry guard waits on seeing it. Issue the read before admission so an
+        // uncertain enqueue — the case that arms the guard — is covered too.
+        void range.current?.loadLatest().catch((reason: unknown) => {
+          if (currentSessionId.current === target) report(reason);
+        });
         const result = await services.enqueueMessage(target, attempt.messageId, text, attachments, attempt.placement);
         if (result === 'rejected' && pendingQueued.current === attempt) {
           pendingQueued.current = undefined;
@@ -394,9 +401,6 @@ export function useWorkHubController() {
         }
         if (result !== 'admitted' && !attempt.observed) throw new Error(workHubLiveCopy[localeRef.current][result === 'unknown' ? 'sendUnknown' : 'sendNotAdmitted']);
         if (pendingQueued.current === attempt) pendingQueued.current = undefined;
-        if (currentSessionId.current === target) {
-          viewportNavigation.followLatest(target);
-        }
         return true;
       }
       const previous = pendingSend.current;
@@ -523,7 +527,10 @@ export function useWorkHubController() {
         void send(attempt.input.text, attempt.input.attachments ?? []);
       } else retryResolution.current();
     },
-    loadOlder: () => range.current?.loadOlder(),
+    prefetchHistory: (edge: 'older' | 'newer') =>
+      range.current?.prefetchHistory(edge) ?? Promise.resolve(false),
+    retainWindow: (window: { firstTurnId: string; lastTurnId: string }) =>
+      range.current?.retain(window),
     loadLatest: () => range.current?.loadLatest(),
     report,
     streamingSettled(messageId?: string) {
diff --git a/apps/desktop/src/renderer/features/workhub/locales/workhub-live-copy.ts b/apps/desktop/src/renderer/features/workhub/locales/workhub-live-copy.ts
index 04ed11d84f..55a7723ef1 100644
--- a/apps/desktop/src/renderer/features/workhub/locales/workhub-live-copy.ts
+++ b/apps/desktop/src/renderer/features/workhub/locales/workhub-live-copy.ts
@@ -37,7 +37,6 @@ export const workHubLiveCopy = {
     expandConversation: 'Expand conversation',
     retry: 'Retry',
     reloadRequired: 'WorkHub needs to reload',
-    older: 'Load earlier messages',
     welcome: 'What can I help with?',
     hint: 'Ask a question, manage your tasks, or ask me to work in Maka.',
     floating: 'WorkHub is in a floating window',
@@ -64,7 +63,6 @@ export const workHubLiveCopy = {
     expandConversation: '展开对话',
     retry: '重试',
     reloadRequired: '工作台需要重新加载',
-    older: '加载更早的消息',
     welcome: '有什么可以帮你?',
     hint: '问个问题、管理任务,或让我帮你操作 Maka。',
     floating: '工作台已在浮窗中打开',
@@ -91,7 +89,6 @@ export const workHubLiveCopy = {
     expandConversation: '展開對話',
     retry: '重試',
     reloadRequired: '工作台需要重新載入',
-    older: '載入更早的訊息',
     welcome: '有什麼可以幫你?',
     hint: '問個問題、管理任務,或讓我幫你操作 Maka。',
     floating: '工作台已在浮動視窗中開啟',
diff --git a/apps/desktop/src/renderer/features/workhub/ports.ts b/apps/desktop/src/renderer/features/workhub/ports.ts
index da55cde5e9..5ba6d3f61e 100644
--- a/apps/desktop/src/renderer/features/workhub/ports.ts
+++ b/apps/desktop/src/renderer/features/workhub/ports.ts
@@ -41,7 +41,10 @@ export interface WorkHubTranscriptSnapshot {
 }
 export interface WorkHubTranscript {
   observationChanged(phase: 'pending' | 'ready'): void;
-  loadOlder(): Promise<void>;
+  /** Fills the window at an edge the reader approaches; resolves to whether a read was issued. */
+  prefetchHistory(edge: 'older' | 'newer'): Promise<boolean>;
+  /** Trims the window to the Turns the reader's band still covers. */
+  retain(window: { firstTurnId: string; lastTurnId: string }): void;
   loadLatest(): Promise<void>;
   close(): Promise<void>;
 }
diff --git a/apps/desktop/src/renderer/features/workhub/ui/workhub-root.tsx b/apps/desktop/src/renderer/features/workhub/ui/workhub-root.tsx
index 72bfd887c4..72593460fe 100644
--- a/apps/desktop/src/renderer/features/workhub/ui/workhub-root.tsx
+++ b/apps/desktop/src/renderer/features/workhub/ui/workhub-root.tsx
@@ -310,16 +310,6 @@ export function WorkHubRoot() {
         }
       >
         <div ref={history} className="workHubHistory" aria-hidden={!showConversation} inert={!showConversation}>
-        {transcript.hasOlder && (
-          <Button
-            label={t.older}
-            variant="ghost"
-            onClick={() => {
-              const task = controller.loadOlder();
-              if (task) call(task);
-            }}
-          />
-        )}
         <div className="workhub-body">
         <WorkHubNavigationRail locale={locale} sessions={tasks} delegatedSessionIds={delegatedSessionIds} copy={getWorkHubRailCopy(locale)} onOpenSession={(id) => call(services.presentation.openSession(id))} />
         <div className="workhub-conversation-shell">
@@ -330,6 +320,10 @@ export function WorkHubRoot() {
           scrollBehavior="auto"
           onNew={() => composer.current?.focus()}
           messages={[...transcript.messages]}
+          hasOlderHistory={transcript.hasOlder}
+          hasNewerHistory={transcript.hasNewer}
+          onPrefetchHistory={controller.prefetchHistory}
+          onRetainWindow={controller.retainWindow}
           transientMessages={controller.transientMessages}
           viewportNavigation={controller.viewportNavigation}
           liveTurn={controller.liveTurn}
diff --git a/apps/desktop/src/renderer/platform/desktop/create-workhub-services.ts b/apps/desktop/src/renderer/platform/desktop/create-workhub-services.ts
index 21a6b6fbc4..095a4d1ede 100644
--- a/apps/desktop/src/renderer/platform/desktop/create-workhub-services.ts
+++ b/apps/desktop/src/renderer/platform/desktop/create-workhub-services.ts
@@ -265,7 +265,19 @@ export function createDesktopWorkHubServices(
       if (cancellation.aborted) cancel();
       return {
         observationChanged: controller.observationChanged,
-        loadOlder: async () => { await controller.loadBefore(); },
+        prefetchHistory: (edge) =>
+          edge === 'older' ? controller.loadBefore() : controller.loadAfter(),
+        retain: ({ firstTurnId, lastTurnId }) => {
+          // A Turn the band named but the window no longer holds yields null,
+          // which leaves that side of the window unbounded rather than empty.
+          const trimmed = controller.store.retain(
+            controller.store.sequenceForTurn(firstTurnId, 'first'),
+            controller.store.sequenceForTurn(lastTurnId, 'last'),
+          );
+          // A trim is the one window change nothing delivers, and the rows it
+          // drops stay mounted until the surface hears about it.
+          if (trimmed && !cancellation.aborted) handler(store.snapshot());
+        },
         loadLatest: () => controller.loadLatest(),
         close: () => { cancellation.removeEventListener('abort', cancel); return controller.close(); },
       };
diff --git a/apps/desktop/stories/workhub.stories.tsx b/apps/desktop/stories/workhub.stories.tsx
index 48eabd2cc2..5d194ca5c5 100644
--- a/apps/desktop/stories/workhub.stories.tsx
+++ b/apps/desktop/stories/workhub.stories.tsx
@@ -78,7 +78,7 @@ function makeServices(failFirst: boolean, withHistory: boolean): WorkHubServices
       return { kind: 'committed', session: { ...session, workspace: { target: { kind: 'host_path', path: '/projects/maka' }, hostCwd: '/projects/maka' }, createdAt: 0, activityAt: 0, labelsTruncated: false, llmConnectionId: 'connection-test', collaborationMode: 'agent', orchestrationMode: 'default' } };
     },
     observe: () => () => {},
-    openTranscript: async (_id, handler) => { updateTranscript = handler; publish(); return { observationChanged: () => {}, loadOlder: async () => {}, loadLatest: async () => {}, close: async () => { updateTranscript = undefined; } }; },
+    openTranscript: async (_id, handler) => { updateTranscript = handler; publish(); return { observationChanged: () => {}, prefetchHistory: async () => false, retain: () => {}, loadLatest: async () => {}, close: async () => { updateTranscript = undefined; } }; },
     stop: async () => [],
   };
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org