You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/22 21:54:30 UTC
(maka) branch feat/runtime-host-rust updated (9292ffe722 -> 40e9efcc91)
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a change to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
from 9292ffe722 fix(ui): unify turn status and inline process disclosure
new 073223740d fix(desktop): publish live history before offline fallback
new 40e9efcc91 fix(desktop): retain native menus until their popups close
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../desktop-transcript-range-store.test.ts | 3 +
.../desktop/src/main/__tests__/native-menu.test.ts | 12 +-
.../runtime-host-session-observer.test.ts | 56 +++++-
.../transcript-open-cached-preview.test.ts | 208 +++++++++++++++++++++
.../transcript-reading-position-controller.test.ts | 59 ++++++
apps/desktop/src/main/native-menu.ts | 14 +-
.../runtime-host-session-observation-registry.ts | 60 +++---
apps/desktop/src/preload/preload.ts | 59 +++---
.../controller/transcript-reading-position.ts | 4 +-
.../desktop/desktop-transcript-range-store.ts | 4 +-
apps/desktop/src/renderer/styles/chat-message.css | 11 ++
packages/ui/src/chat-view.tsx | 2 +-
12 files changed, 428 insertions(+), 64 deletions(-)
create mode 100644 apps/desktop/src/main/__tests__/transcript-open-cached-preview.test.ts
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 02/02: fix(desktop): retain native menus until their popups close
Posted by wy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 40e9efcc9147ffcfc7fe74e9f968bc4ad7ef13fa
Author: Wang <m4...@gmail.com>
AuthorDate: Wed Sep 23 05:54:24 2026 +0800
fix(desktop): retain native menus until their popups close
Generated-by: Codex
---
apps/desktop/src/main/__tests__/native-menu.test.ts | 12 +++++++++++-
apps/desktop/src/main/native-menu.ts | 14 ++++++++++++--
2 files changed, 23 insertions(+), 3 deletions(-)
diff --git a/apps/desktop/src/main/__tests__/native-menu.test.ts b/apps/desktop/src/main/__tests__/native-menu.test.ts
index 31c618115e..78e329e8a1 100644
--- a/apps/desktop/src/main/__tests__/native-menu.test.ts
+++ b/apps/desktop/src/main/__tests__/native-menu.test.ts
@@ -24,10 +24,14 @@ import test from 'node:test';
test('native menu returns only the selected action, cancels cleanly, and anchors at renderer zoom', async () => {
let items: Electron.MenuItemConstructorOptions[] = [];
let options: Electron.PopupOptions | undefined;
+ let popupFailure: Error | undefined;
const globals = globalThis as typeof globalThis & { nativeMenuTest?: unknown };
globals.nativeMenuTest = { buildFromTemplate(template: Electron.MenuItemConstructorOptions[]) {
items = template;
- return { popup(input: Electron.PopupOptions) { options = input; } };
+ return { popup(input: Electron.PopupOptions) {
+ if (popupFailure) throw popupFailure;
+ options = input;
+ } };
} };
const hooks = registerHooks({ resolve(specifier, context, next) {
return specifier === 'electron'
@@ -53,6 +57,12 @@ test('native menu returns only the selected action, cancels cleanly, and anchors
const cancelled = popupNativeMenu(window, request);
options!.callback!();
assert.equal(await cancelled, null);
+ popupFailure = new Error('native popup failed');
+ await assert.rejects(popupNativeMenu(window, request), (error) => error === popupFailure);
+ popupFailure = undefined;
+ const recovered = popupNativeMenu(window, request);
+ options!.callback!();
+ assert.equal(await recovered, null);
assert.throws(() => popupNativeMenu(window, { ...request, x: Infinity }), /Invalid native menu/);
assert.throws(() => popupNativeMenu(window, { ...request, items: [{ role: 'quit' }] }), /Invalid native menu/);
} finally { hooks.deregister(); delete globals.nativeMenuTest; }
diff --git a/apps/desktop/src/main/native-menu.ts b/apps/desktop/src/main/native-menu.ts
index 95104405b6..a31c59a9e3 100644
--- a/apps/desktop/src/main/native-menu.ts
+++ b/apps/desktop/src/main/native-menu.ts
@@ -20,6 +20,10 @@
import { Menu, type BrowserWindow } from 'electron';
import type { NativeMenuRequest } from '../shared/native-menu.js';
+// A Menu collected while its popup is still open crashes the native close
+// path, so each popup owns a reference until its callback reports it closed.
+const openMenus = new Set<Menu>();
+
export function popupNativeMenu(window: BrowserWindow, input: unknown): Promise<string | null> {
const request = input as NativeMenuRequest | undefined;
if (!request || !Number.isFinite(request.x) || !Number.isFinite(request.y) ||
@@ -38,7 +42,13 @@ export function popupNativeMenu(window: BrowserWindow, input: unknown): Promise<
})));
// Menu coordinates are relative to window content, in DIP rather than CSS pixels.
const zoom = window.webContents.getZoomFactor();
- menu.popup({ window, x: Math.round(request.x * zoom), y: Math.round(request.y * zoom),
- callback: () => resolve(selected) });
+ openMenus.add(menu);
+ try {
+ menu.popup({ window, x: Math.round(request.x * zoom), y: Math.round(request.y * zoom),
+ callback: () => { openMenus.delete(menu); resolve(selected); } });
+ } catch (error) {
+ openMenus.delete(menu);
+ throw error;
+ }
});
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 01/02: fix(desktop): publish live history before offline fallback
Posted by wy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 073223740d5b1730d5561ff464be5706b203caf9
Author: Wang <m4...@gmail.com>
AuthorDate: Wed Sep 23 05:54:24 2026 +0800
fix(desktop): publish live history before offline fallback
Release unavailable first reads without delaying cache fallback or Host recovery; reject stale delivery and preserve cancellation.
Generated-by: Codex
---
.../desktop-transcript-range-store.test.ts | 3 +
.../runtime-host-session-observer.test.ts | 56 +++++-
.../transcript-open-cached-preview.test.ts | 208 +++++++++++++++++++++
.../transcript-reading-position-controller.test.ts | 59 ++++++
.../runtime-host-session-observation-registry.ts | 60 +++---
apps/desktop/src/preload/preload.ts | 59 +++---
.../controller/transcript-reading-position.ts | 4 +-
.../desktop/desktop-transcript-range-store.ts | 4 +-
apps/desktop/src/renderer/styles/chat-message.css | 11 ++
packages/ui/src/chat-view.tsx | 2 +-
10 files changed, 405 insertions(+), 61 deletions(-)
diff --git a/apps/desktop/src/main/__tests__/desktop-transcript-range-store.test.ts b/apps/desktop/src/main/__tests__/desktop-transcript-range-store.test.ts
index 4d1875d6b4..c47d2949b5 100644
--- a/apps/desktop/src/main/__tests__/desktop-transcript-range-store.test.ts
+++ b/apps/desktop/src/main/__tests__/desktop-transcript-range-store.test.ts
@@ -1361,6 +1361,8 @@ test('cached fallback remains readable and retries once per observation generati
await settle();
assert.equal(opens, 1);
assert.equal(store.range().generation, 'cached:generation');
+ assert.equal(store.range().hasOlder, false, 'a cached transcript offers no earlier history to load');
+ assert.equal(store.snapshot().hasOlder, false);
await controller.loadEarlier();
assert.equal(earlierReads, 0, 'a cached transcript has no Host to read earlier history from');
controller.observationChanged('ready');
@@ -1375,6 +1377,7 @@ test('cached fallback remains readable and retries once per observation generati
await settle();
assert.equal(opens, 3);
assert.equal(store.range().generation, 'live-generation');
+ assert.equal(store.range().hasOlder, true);
assert.deepEqual(errors, []);
await controller.close();
});
diff --git a/apps/desktop/src/main/__tests__/runtime-host-session-observer.test.ts b/apps/desktop/src/main/__tests__/runtime-host-session-observer.test.ts
index ca87756bed..2d25419664 100644
--- a/apps/desktop/src/main/__tests__/runtime-host-session-observer.test.ts
+++ b/apps/desktop/src/main/__tests__/runtime-host-session-observer.test.ts
@@ -503,15 +503,10 @@ test('restores transcript consumers across Host replacement', async () => {
await observations.attach(second, bind('second'));
observations.detach(second);
await observations.closeTranscript('consumer-1');
- const pending = observations.openTranscript('session-1', 'consumer-2', target);
- let pendingSettled = false;
- void pending.finally(() => {
- pendingSettled = true;
- });
- await Promise.resolve();
- assert.equal(pendingSettled, false);
+ await assert.rejects(observations.openTranscript('session-1', 'consumer-2', target), /source is unavailable/);
+ assert.deepEqual(observations.trackedSessionIds(), []);
await observations.attach(source('third'), bind('third'));
- assert.equal((await pending).generation, 'third');
+ assert.equal((await observations.openTranscript('session-1', 'consumer-2', target)).generation, 'third');
assert.deepEqual(opens, [
'first:session-1:consumer-1:history',
@@ -526,6 +521,51 @@ test('restores transcript consumers across Host replacement', async () => {
await observations.close();
});
+test('detaching a pending first read releases its caller before source cleanup and drops late frames', { timeout: 5_000 }, async () => {
+ const observations = new RuntimeHostSessionObservationRegistry();
+ const started = deferred<RuntimeHostTranscriptTarget>();
+ const completion = deferred<DesktopTranscriptOpenResult>();
+ const destroyed = new Set<() => void>();
+ const batches: DesktopTranscriptBatch[] = [];
+ let closes = 0;
+ const source = {
+ async observe() {},
+ async unobserve() {},
+ async openTranscript(_sessionId: string, _consumerId: string, target: RuntimeHostTranscriptTarget) {
+ started.resolve(target);
+ return completion.promise;
+ },
+ async loadEarlierTranscript() {},
+ async readTranscriptTurn() { return []; },
+ acknowledgeTranscriptTail() {},
+ async closeTranscript() { closes += 1; },
+ };
+ await observations.attach(source);
+ const opening = observations.openTranscript('session-1', 'consumer-1', {
+ id: 18,
+ send(_channel, batch) { batches.push(batch); },
+ once(_event, listener) { destroyed.add(listener); },
+ off(_event, listener) { destroyed.delete(listener); },
+ });
+ const unavailable = assert.rejects(opening, /source is unavailable/);
+ const target = await started.promise;
+ try {
+ observations.detach(source);
+ await unavailable;
+ assert.deepEqual(observations.trackedSessionIds(), []);
+ assert.equal(destroyed.size, 0);
+ target.send('sessions:transcript:consumer-1', {
+ sessionId: 'session-1', generation: 'old', hostEpoch: 'old-host', deliverySequence: 1,
+ durableThrough: null, fragments: [], reset: true, ready: true,
+ });
+ assert.deepEqual(batches, []);
+ } finally {
+ completion.resolve({ sessionId: 'session-1', generation: 'old', hostEpoch: 'old-host', readThroughMessageId: null });
+ await observations.close();
+ }
+ await waitFor(() => closes === 1);
+});
+
test('does not hold Host observation recovery on transcript replay', async () => {
const observations = new RuntimeHostSessionObservationRegistry();
const target = eventTarget(18);
diff --git a/apps/desktop/src/main/__tests__/transcript-open-cached-preview.test.ts b/apps/desktop/src/main/__tests__/transcript-open-cached-preview.test.ts
new file mode 100644
index 0000000000..5435705159
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/transcript-open-cached-preview.test.ts
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+import { runInNewContext } from 'node:vm';
+import test from 'node:test';
+import { build } from 'esbuild';
+import type { StoredMessage } from '@maka/core/session';
+import type { MakaBridge } from '../../preload/bridge-contract.js';
+import type { DesktopTranscriptBatch } from '../../preload/transcript-contract.js';
+import { encodeDesktopTranscriptSnapshot } from '../desktop-transcript-ipc.js';
+import { DesktopTranscriptRangeStore } from '../../renderer/platform/desktop/desktop-transcript-range-store.js';
+import { desktopSessionKey } from '../../shared/runtime-host-identity.js';
+import { deferred, waitFor } from '@maka/core/test-only/async-primitives';
+
+const OWNER = {
+ hostId: 'host-1', targetEpoch: 'epoch-1', profileId: 'local',
+ profileName: 'Local', profileKind: 'local', profileAccess: 'owner', readiness: 'ready',
+};
+const SESSION_ID = desktopSessionKey({ hostId: OWNER.hostId, sessionId: 'session-1' });
+
+const message = (id: string, turnId: string): StoredMessage => ({
+ type: 'user', id, turnId, ts: 1, text: id,
+});
+const CACHED_TAIL = [
+ { sequence: 19, message: message('m19', 't19') },
+ { sequence: 20, message: message('m20', 't20') },
+];
+const FULL = Array.from({ length: 20 }, (_, index) => ({
+ sequence: index + 1, message: message(`m${index + 1}`, `t${index + 1}`),
+}));
+
+interface Harness {
+ readonly bridge: MakaBridge;
+ readonly state: { cacheReads: number };
+ liveListeners(): number;
+}
+
+async function preloadHarness(options: {
+ liveOpenFails?: boolean;
+ partialLive?: boolean;
+ beforeCacheRead?(): Promise<void>;
+}): Promise<Harness> {
+ let bridge: MakaBridge | undefined;
+ let consumerId = '';
+ let deliverySequence = 0;
+ const state = { cacheReads: 0 };
+ const listeners = new Map<string, (...args: unknown[]) => void>();
+ const deliver = (batch: Omit<DesktopTranscriptBatch, 'deliverySequence'>) => {
+ listeners.get(`sessions:transcript:${consumerId}`)?.({}, OWNER, {
+ ...batch, deliverySequence: ++deliverySequence,
+ });
+ };
+ const ipcRenderer = {
+ on(channel: string, listener: (...args: unknown[]) => void) { listeners.set(channel, listener); },
+ off(channel: string) { listeners.delete(channel); },
+ send() {},
+ async invoke(channel: string, ...args: unknown[]): Promise<unknown> {
+ if (channel === 'app:bootstrapReady') return;
+ if (channel === 'runtime-host:activeIdentity') return OWNER;
+ if (channel === 'runtime-host:identities') return [OWNER];
+ if (channel === 'session-local:transcript') {
+ state.cacheReads += 1;
+ await options.beforeCacheRead?.();
+ return {
+ cachedAt: 1,
+ batches: [...encodeDesktopTranscriptSnapshot({
+ beginsAtTurnBoundary: true,
+ sessionId: 'session-1', generation: 'cached:g1', hostEpoch: 'epoch-1',
+ durableThrough: 20, durable: CACHED_TAIL, hasOlder: true,
+ })],
+ };
+ }
+ if (channel === 'sessions:transcript:open') {
+ consumerId = args[2] as string;
+ if (options.partialLive) {
+ const batch = [...encodeDesktopTranscriptSnapshot({
+ beginsAtTurnBoundary: true,
+ sessionId: 'session-1', generation: 'live-1', hostEpoch: 'epoch-1',
+ durableThrough: 20, durable: CACHED_TAIL, hasOlder: true,
+ })][0]!;
+ deliver({ ...batch, ready: false });
+ }
+ if (options.liveOpenFails) throw new Error('live transcript unavailable');
+ setImmediate(() => {
+ for (const batch of encodeDesktopTranscriptSnapshot({
+ beginsAtTurnBoundary: true,
+ sessionId: 'session-1', generation: 'live-1', hostEpoch: 'epoch-1',
+ durableThrough: 20, durable: FULL, hasOlder: false,
+ })) deliver(batch);
+ });
+ return { kind: 'ready', value: {
+ sessionId: 'session-1', generation: 'live-1', hostEpoch: 'epoch-1',
+ readThroughMessageId: null,
+ } };
+ }
+ if (
+ channel === 'sessions:transcript:ack' ||
+ channel === 'sessions:transcript:acknowledge-tail' ||
+ channel === 'sessions:transcript:close'
+ ) return;
+ throw new Error(`Unexpected channel: ${channel}`);
+ },
+ };
+ const bundle = await build({
+ entryPoints: [fileURLToPath(new URL('../../../src/preload/preload.ts', import.meta.url))],
+ bundle: true, write: false, platform: 'node', format: 'cjs', external: ['electron'],
+ });
+ const require = createRequire(import.meta.url);
+ runInNewContext(bundle.outputFiles[0]!.text, {
+ require: (id: string) => id === 'electron' ? {
+ ipcRenderer,
+ contextBridge: { exposeInMainWorld(name: string, value: MakaBridge) {
+ if (name === 'maka') bridge = value;
+ } },
+ } : require(id),
+ process: { env: {} }, Buffer, console, setTimeout, clearTimeout, TextEncoder, TextDecoder,
+ Uint8Array, crypto: globalThis.crypto,
+ });
+ assert.ok(bridge);
+ return { bridge, state, liveListeners: () => [...listeners.keys()].filter((key) => key.startsWith('sessions:transcript:')).length };
+}
+
+function publications(store: DesktopTranscriptRangeStore) {
+ const seen: Array<{ ids: string[]; hasOlder: boolean }> = [];
+ store.subscribe(() => {
+ const snapshot = store.snapshot();
+ if (snapshot.ready) {
+ seen.push({ ids: snapshot.messages.map((entry) => entry.id), hasOlder: snapshot.hasOlder });
+ }
+ });
+ return seen;
+}
+
+// A healthy open publishes the live answer as the first history; the cached
+// tail is not a preview the reader ever sees.
+test('a healthy transcript open publishes only the live answer and never reads the cache', async () => {
+ const { bridge, state } = await preloadHarness({ liveOpenFails: false });
+ const store = new DesktopTranscriptRangeStore(SESSION_ID);
+ const seen = publications(store);
+ const handle = await bridge.transcripts.open(SESSION_ID, (batch) => store.accept(batch), () => {}, 'history');
+ await waitFor(() => seen.length === 1, { timeoutMs: 5_000 });
+ await handle.close();
+ assert.deepEqual(seen, [{ ids: FULL.map((entry) => entry.message.id), hasOlder: false }]);
+ assert.equal(state.cacheReads, 0);
+});
+
+// The cache stands in only when the live read never answered; even then it
+// advertises no earlier history because nothing can serve the read.
+test('a failed live open falls back to the cached transcript without earlier history', async () => {
+ const { bridge, state } = await preloadHarness({ liveOpenFails: true });
+ const store = new DesktopTranscriptRangeStore(SESSION_ID);
+ const seen = publications(store);
+ const handle = await bridge.transcripts.open(SESSION_ID, (batch) => store.accept(batch), () => {}, 'history');
+ await waitFor(() => seen.length === 1, { timeoutMs: 5_000 });
+ assert.deepEqual(seen, [{ ids: ['m19', 'm20'], hasOlder: false }]);
+ assert.equal(state.cacheReads, 1);
+ assert.equal(handle.generation, 'cached:g1');
+ await assert.rejects(handle.loadEarlier(), /Reconnect the Host/);
+ await handle.close();
+});
+
+test('cancellation during cache fallback cannot publish or retain the abandoned consumer', async () => {
+ const started = deferred<void>();
+ const release = deferred<void>();
+ const { bridge, liveListeners } = await preloadHarness({
+ liveOpenFails: true,
+ beforeCacheRead: () => { started.resolve(); return release.promise; },
+ });
+ const delivered: DesktopTranscriptBatch[] = [];
+ let cancel = () => {};
+ const opened = bridge.transcripts.open(SESSION_ID, (batch) => delivered.push(batch), (close) => { cancel = close; });
+ const rejected = assert.rejects(opened, /cancelled/);
+ await started.promise;
+ cancel();
+ release.resolve();
+ await rejected;
+ assert.deepEqual(delivered, []);
+ assert.equal(liveListeners(), 0);
+});
+
+test('a partially delivered live generation never falls back to older cached history', async () => {
+ const { bridge, state, liveListeners } = await preloadHarness({ liveOpenFails: true, partialLive: true });
+ const delivered: DesktopTranscriptBatch[] = [];
+ await assert.rejects(bridge.transcripts.open(SESSION_ID, (batch) => delivered.push(batch)), /live transcript unavailable/);
+ assert.equal(delivered.length, 1);
+ assert.equal(delivered[0]!.generation, 'live-1');
+ assert.equal(state.cacheReads, 0);
+ assert.equal(liveListeners(), 0);
+});
diff --git a/apps/desktop/src/main/__tests__/transcript-reading-position-controller.test.ts b/apps/desktop/src/main/__tests__/transcript-reading-position-controller.test.ts
index 07bd13194d..1064164562 100644
--- a/apps/desktop/src/main/__tests__/transcript-reading-position-controller.test.ts
+++ b/apps/desktop/src/main/__tests__/transcript-reading-position-controller.test.ts
@@ -119,6 +119,65 @@ test('a bookmark the Turn index does not know, or cannot be asked about, is unav
}
});
+test('a cached transcript keeps a stored bookmark pending until the live answer replaces it', async () => {
+ const store = new DesktopTranscriptRangeStore(SESSION_ID);
+ for (const batch of encodeDesktopTranscriptSnapshot({
+ beginsAtTurnBoundary: true,
+ ...IDENTITY, generation: 'cached:generation', durableThrough: 30,
+ durable: [{ sequence: 30, message: answer('c') }], hasOlder: true,
+ })) store.accept(batch);
+ const reads: (number | undefined)[] = [];
+ const lookups: string[] = [];
+ const controller = createDesktopTranscriptRangeController(store, async () => handle({
+ async loadEarlier(throughSequence) {
+ reads.push(throughSequence);
+ for (const batch of encodeDesktopTranscriptBatches(IDENTITY, {
+ durableThrough: 30,
+ durable: [{ sequence: 10, message: answer('a') }, { sequence: 20, message: answer('b') }],
+ hasOlder: false, earlierThan: 30, reset: false, ready: true,
+ })) store.accept(batch);
+ },
+ }), { onError: (error) => assert.fail(String(error)) });
+ let anchor: { turnId: string } | undefined = { turnId: 'a' };
+ const unavailable: string[] = [];
+ const lifecycle = createTranscriptRestoreLifecycle();
+ const restore = () => restoreSessionTranscriptRange({
+ lifecycle, sessionId: SESSION_ID, controller, readingAnchor: { turnId: 'a' },
+ isCurrent: () => true,
+ lookupTurn: async (_sessionId, turnId) => { lookups.push(turnId); return 10; },
+ setReadingAnchor: (_sessionId, next) => { anchor = next; },
+ onRestoreUnavailable: (_sessionId, turnId) => { unavailable.push(turnId); },
+ onError: (error) => assert.fail(String(error)),
+ });
+ try {
+ await controller.ready();
+ restore();
+ for (let tick = 0; tick < 4; tick += 1) await settle();
+ restore();
+ await settle();
+ assert.deepEqual(lookups, []);
+ assert.deepEqual(reads, []);
+ assert.deepEqual(anchor, { turnId: 'a' });
+ assert.deepEqual(unavailable, []);
+ for (const batch of encodeDesktopTranscriptSnapshot({
+ beginsAtTurnBoundary: true,
+ ...IDENTITY, durableThrough: 30,
+ durable: [{ sequence: 30, message: answer('c') }], hasOlder: true,
+ })) store.accept(batch);
+ restore();
+ for (let tick = 0; tick < 4; tick += 1) await settle();
+ restore();
+ await settle();
+ assert.deepEqual(lookups, ['a']);
+ assert.deepEqual(reads, [10]);
+ assert.deepEqual(store.snapshot().messages.map(({ turnId }) => turnId), ['a', 'b', 'c']);
+ assert.deepEqual(anchor, { turnId: 'a' });
+ assert.deepEqual(unavailable, []);
+ } finally {
+ await controller.close();
+ }
+});
+
test('sending before transcript open completes cancels the queued bookmark without delaying admission', { timeout: 5_000 }, async () => {
const store = new DesktopTranscriptRangeStore(SESSION_ID);
const opening = deferred<DesktopTranscriptHandle>();
diff --git a/apps/desktop/src/main/runtime-host-session-observation-registry.ts b/apps/desktop/src/main/runtime-host-session-observation-registry.ts
index bfd4c4f2f1..b98b8f12b6 100644
--- a/apps/desktop/src/main/runtime-host-session-observation-registry.ts
+++ b/apps/desktop/src/main/runtime-host-session-observation-registry.ts
@@ -270,8 +270,12 @@ export class RuntimeHostSessionObservationRegistry {
if (this.#source === source) {
this.#source = undefined;
this.#bindTarget = (target) => target;
- for (const registration of this.#transcripts.values()) {
- registration.restore?.resolve();
+ for (const [consumerId, registration] of this.#transcripts) {
+ if (registration.lifecycle === 'pending') {
+ this.#deleteTranscript(consumerId, registration, new Error('Runtime Host transcript source is unavailable'));
+ } else {
+ registration.restore?.resolve();
+ }
}
}
}
@@ -350,6 +354,8 @@ export class RuntimeHostSessionObservationRegistry {
* A reset replaces what the consumer holds, so it starts the count again.
*/
#trackDelivered(
+ consumerId: string,
+ source: SessionObservationSource,
registration: TranscriptRegistration,
target: RuntimeHostTranscriptTarget,
): RuntimeHostTranscriptTarget {
@@ -358,6 +364,7 @@ export class RuntimeHostSessionObservationRegistry {
return target.id;
},
send: (channel, payload) => {
+ if (this.#source !== source || this.#transcripts.get(consumerId) !== registration) return;
if (payload.reset) registration.deliveredFrom = null;
for (const { sequence } of payload.fragments) {
if (registration.deliveredFrom === null || sequence < registration.deliveredFrom) {
@@ -382,6 +389,7 @@ export class RuntimeHostSessionObservationRegistry {
if (this.#transcripts.has(consumerId)) {
throw new Error('Desktop transcript consumer identity was reused');
}
+ const source = requireTranscriptSource(this.#source);
const destroyedListener = () => {
void this.closeTranscript(consumerId).catch(this.#onError);
};
@@ -400,30 +408,30 @@ export class RuntimeHostSessionObservationRegistry {
};
this.#transcripts.set(consumerId, registration);
target.once('destroyed', destroyedListener);
- const source = this.#source;
- if (!source) return ready.promise;
- try {
- const transcriptSource = requireTranscriptSource(source);
- const result = await transcriptSource.openTranscript(
- sessionId,
- consumerId,
- this.#trackDelivered(registration, this.#bindTarget(target)),
- mode,
- resumeFrom,
- );
- if (this.#source === source && this.#transcripts.get(consumerId) === registration) {
- registration.lifecycle = 'active';
- registration.ready.resolve(result);
- } else {
- await transcriptSource.closeTranscript(consumerId);
- }
- } catch (error) {
- if (this.#source === source && this.#transcripts.get(consumerId) === registration) {
- this.#deleteTranscript(consumerId, registration);
- throw error;
+ // First-read availability is not a durable subscription: detach must
+ // release its caller even when the old source has not finished closing.
+ // An already opened consumer still restores across connections below.
+ void (async () => {
+ try {
+ const result = await source.openTranscript(
+ sessionId,
+ consumerId,
+ this.#trackDelivered(consumerId, source, registration, this.#bindTarget(target)),
+ mode,
+ resumeFrom,
+ );
+ if (this.#source === source && this.#transcripts.get(consumerId) === registration) {
+ registration.lifecycle = 'active';
+ registration.ready.resolve(result);
+ } else {
+ await source.closeTranscript(consumerId);
+ }
+ } catch (error) {
+ if (this.#source === source && this.#transcripts.get(consumerId) === registration) {
+ this.#deleteTranscript(consumerId, registration, error instanceof Error ? error : new Error(String(error)));
+ }
}
- return registration.ready.promise;
- }
+ })().catch(this.#onError);
return registration.ready.promise;
}
@@ -587,7 +595,7 @@ export class RuntimeHostSessionObservationRegistry {
const result = await transcriptSource.openTranscript(
registration.sessionId,
consumerId,
- this.#trackDelivered(registration, this.#bindTarget(registration.target)),
+ this.#trackDelivered(consumerId, source, registration, this.#bindTarget(registration.target)),
registration.mode,
registration.deliveredFrom ?? undefined,
);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 0b02370a6c..c74e969332 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2460,7 +2460,7 @@ const makaBridge = {
const consumerId = crypto.randomUUID();
const channel = `sessions:transcript:${consumerId}`;
let identity: DesktopTranscriptIdentity | undefined;
- let cachedIdentity: DesktopTranscriptIdentity | undefined;
+ let session: Awaited<ReturnType<typeof runtimeHostSessionRef>> | undefined;
const retiredGenerations = new Set<string>();
let closed = false;
let requestClose = () => {};
@@ -2504,22 +2504,15 @@ const makaBridge = {
}
};
ipcRenderer.on(channel, listener);
- const openDispatch = runtimeHostSessionRef(sessionId).then(async (session) => {
- consumerScope = session.scope;
- const cached = await invokeWhenReady(
- 'session-local:transcript', session.scope, session.sessionId,
- ).catch(() => null) as import('../shared/session-local-contract.js').DesktopCachedTranscript | null;
+ const openDispatch = runtimeHostSessionRef(sessionId).then((ref) => {
+ consumerScope = ref.scope;
+ session = ref;
if (closed) throw new Error('Desktop transcript open was cancelled');
- // Local frames do not participate in the live consumer identity or ACK window.
- for (const [index, batch] of (cached?.batches ?? []).entries()) {
- handler({ ...batch, deliverySequence: index + 1 });
- if (batch.ready) cachedIdentity = { generation: batch.generation, hostEpoch: batch.hostEpoch };
- }
return {
completion: invokeWhenReady(
'sessions:transcript:open',
- session.scope,
- session.sessionId,
+ ref.scope,
+ ref.sessionId,
consumerId,
mode,
resumeFrom ?? null,
@@ -2541,19 +2534,37 @@ const makaBridge = {
try {
openResult = await openDispatch.then(({ completion }) => completion);
} catch (error) {
- const cancelled = closed;
- closed = true;
ipcRenderer.off(channel, listener);
- if (!cancelled && cachedIdentity && !identity) {
- const unavailable = async () => { throw new Error('Reconnect the Host to load uncached history'); };
- return {
- ...cachedIdentity, sessionId, readThroughMessageId: null,
- acknowledgeTail: unavailable,
- loadEarlier: unavailable,
- close: async () => {},
- };
+ try {
+ // A healthy open publishes only live history. The cache is a read-only
+ // fallback, never a preview or a continuation of a partial live read.
+ if (!closed && !identity && session) {
+ const cached = await invokeWhenReady(
+ 'session-local:transcript', session.scope, session.sessionId,
+ ).catch(() => null) as import('../shared/session-local-contract.js').DesktopCachedTranscript | null;
+ let cachedIdentity: DesktopTranscriptIdentity | undefined;
+ // Cache delivery is outside the live ACK window. Cancellation must
+ // still win while the local read or its consumer is running.
+ for (const [index, batch] of (cached?.batches ?? []).entries()) {
+ if (closed) throw new Error('Desktop transcript open was cancelled');
+ handler({ ...batch, deliverySequence: index + 1 });
+ if (batch.ready) cachedIdentity = { generation: batch.generation, hostEpoch: batch.hostEpoch };
+ }
+ if (closed) throw new Error('Desktop transcript open was cancelled');
+ if (cachedIdentity) {
+ const unavailable = async () => { throw new Error('Reconnect the Host to load uncached history'); };
+ return {
+ ...cachedIdentity, sessionId, readThroughMessageId: null,
+ acknowledgeTail: unavailable,
+ loadEarlier: unavailable,
+ close: async () => {},
+ };
+ }
+ }
+ throw error;
+ } finally {
+ closed = true;
}
- throw error;
}
if (openResult.kind === 'cancelled') {
closed = true;
diff --git a/apps/desktop/src/renderer/features/conversation/controller/transcript-reading-position.ts b/apps/desktop/src/renderer/features/conversation/controller/transcript-reading-position.ts
index 9791c1e864..186899f3b2 100644
--- a/apps/desktop/src/renderer/features/conversation/controller/transcript-reading-position.ts
+++ b/apps/desktop/src/renderer/features/conversation/controller/transcript-reading-position.ts
@@ -168,7 +168,9 @@ export function restoreSessionTranscriptRange<Message>(options: {
const command = options.lifecycle.request(options);
if (!command || command.loading || !controller || !sessionId || !options.isCurrent(sessionId, controller)) return;
const range = currentTranscriptRange(controller, sessionId);
- if (!range?.ready) return;
+ // A cached range is replaced wholesale by the live answer; only that answer
+ // can say whether the target Turn is reachable.
+ if (!range?.ready || range.generation?.startsWith('cached:')) return;
const { turnId } = command.target;
if (controller.store.snapshot().messages.some((message) =>
message !== null && typeof message === 'object' && 'turnId' in message && message.turnId === turnId,
diff --git a/apps/desktop/src/renderer/platform/desktop/desktop-transcript-range-store.ts b/apps/desktop/src/renderer/platform/desktop/desktop-transcript-range-store.ts
index 5af8f4190e..146015e927 100644
--- a/apps/desktop/src/renderer/platform/desktop/desktop-transcript-range-store.ts
+++ b/apps/desktop/src/renderer/platform/desktop/desktop-transcript-range-store.ts
@@ -492,7 +492,9 @@ export class DesktopTranscriptRangeStore {
hostEpoch: this.#hostEpoch,
durableThrough: this.#value.through,
oldestSequence: this.#value.order[0] ?? null,
- hasOlder: this.#value.hasOlder,
+ // A cached snapshot cannot serve earlier reads; the live answer replaces
+ // it rather than continuing it.
+ hasOlder: this.#value.hasOlder && !this.#generation.startsWith('cached:'),
beginsAtTurnBoundary: this.#value.beginsAtTurnBoundary,
ready: this.#ready,
};
diff --git a/apps/desktop/src/renderer/styles/chat-message.css b/apps/desktop/src/renderer/styles/chat-message.css
index 764675c217..9f497aa8dc 100644
--- a/apps/desktop/src/renderer/styles/chat-message.css
+++ b/apps/desktop/src/renderer/styles/chat-message.css
@@ -31,6 +31,17 @@
and bubble chrome; the remaining selectors are product content and actions.
============================================================================ */
+/* Reveal the newly ready Session once, without an intermediate cached tail. */
+.maka-chat-session-swap {
+ animation: maka-stream-fade-in var(--duration-emphasized) var(--ease-out-strong);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .maka-chat-session-swap {
+ animation: none;
+ }
+}
+
/* Native anchoring handles ordinary content growth. The scroll authority
disables it during following and atomic range replacement, when it owns
the position write itself. */
diff --git a/packages/ui/src/chat-view.tsx b/packages/ui/src/chat-view.tsx
index 9aa4c30167..872e85596d 100644
--- a/packages/ui/src/chat-view.tsx
+++ b/packages/ui/src/chat-view.tsx
@@ -791,7 +791,7 @@ export function ChatView(props: {
? emptyContent
: null}
{loadEarlierHistoryControl}
- <div key={props.activeSession.id} ref={listRef}>
+ <div key={props.activeSession.id} ref={listRef} className="maka-chat-session-swap">
<Virtualizer
key={measurement.generation}
ref={virtualizerRef}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org