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/08/23 06:46:29 UTC
(maka) branch main updated: fix(desktop): reconcile goal arm across reconnects (#3363)
This is an automated email from the ASF dual-hosted git repository.
Astro-Han pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/main by this push:
new c9fa58a53 fix(desktop): reconcile goal arm across reconnects (#3363)
c9fa58a53 is described below
commit c9fa58a5373ca876f9a46ebbe5d551ab837f085a
Author: ooopSok <81...@users.noreply.github.com>
AuthorDate: Sun Aug 23 14:46:23 2026 +0800
fix(desktop): reconcile goal arm across reconnects (#3363)
Add a reusable Desktop reconciled-control path that dispatches a mutation once and reconciles only through replacement-candidate reads.
Apply it to goal.arm, comparing canonical Goal state after a dispatched connection loss without replaying the mutation.
Keep uncertain Goal outcomes visible and locked in the dialog, with Chinese and English guidance.
Preserve the Goal pause/resume behavior already merged through feat(goal): let the user arm a Goal from the composer #3199.
Fixes #3234
Generated-by: Codex
---
.../src/main/__tests__/goal-arm-outcome.test.ts | 100 +++++
.../desktop/src/main/__tests__/goal-dialog.test.ts | 270 +++++++++++++
.../src/main/__tests__/goal-preload-bridge.test.ts | 89 +++++
.../runtime-host-reconnecting-ipc-main.test.ts | 268 ++++++++++++-
.../runtime-host-session-domains-ipc-main.test.ts | 435 ++++++++++++++++++++-
apps/desktop/src/main/ipc-reconnect-policy.ts | 51 +++
.../src/main/runtime-host-desktop-candidate.ts | 45 ++-
.../src/main/runtime-host-reconnecting-ipc-main.ts | 203 +++++++++-
.../main/runtime-host-session-domains-ipc-main.ts | 104 ++++-
apps/desktop/src/preload/bridge-contract.d.ts | 2 +-
apps/desktop/src/preload/preload.ts | 49 +--
.../src/preload/projected-session-runtime-host.ts | 76 ++++
apps/desktop/src/renderer/goal-arm-outcome.ts | 50 +++
apps/desktop/src/renderer/goal-dialog.tsx | 62 ++-
apps/desktop/src/renderer/locales/shell-copy.ts | 43 ++
apps/desktop/src/shared/goal-arm.ts | 11 +
16 files changed, 1782 insertions(+), 76 deletions(-)
diff --git a/apps/desktop/src/main/__tests__/goal-arm-outcome.test.ts b/apps/desktop/src/main/__tests__/goal-arm-outcome.test.ts
new file mode 100644
index 000000000..9f6e955e6
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/goal-arm-outcome.test.ts
@@ -0,0 +1,100 @@
+/*
+ * 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 test from 'node:test';
+import type { GoalArmOutcome } from '../../shared/goal-arm.js';
+import { interpretGoalArmOutcome } from '../../renderer/goal-arm-outcome.js';
+import { getShellCopy } from '../../renderer/locales/shell-copy.js';
+
+test('successful Goal arming closes while every reconciliation result locks the form', () => {
+ const goal = {
+ id: 'goal-1',
+ revision: 1,
+ sessionId: 'session-1',
+ condition: 'All tests pass',
+ status: 'active' as const,
+ setAt: 1,
+ iterations: 0,
+ maxIterations: 50,
+ consecutiveNoProgress: 0,
+ blockCap: 8,
+ tokensAtStart: 0,
+ tokensNow: 0,
+ tokensBaselinePending: false,
+ };
+ const cases: Array<{
+ outcome: GoalArmOutcome;
+ expected: ReturnType<typeof interpretGoalArmOutcome>;
+ }> = [
+ {
+ outcome: { kind: 'armed', goal },
+ expected: { action: 'close' },
+ },
+ {
+ outcome: {
+ kind: 'reconciled',
+ currentGoal: goal,
+ matchesRequestedState: true,
+ },
+ expected: { action: 'lock', notice: { kind: 'matching_goal', goal } },
+ },
+ {
+ outcome: {
+ kind: 'reconciled',
+ currentGoal: goal,
+ matchesRequestedState: false,
+ },
+ expected: { action: 'lock', notice: { kind: 'different_goal', goal } },
+ },
+ {
+ outcome: {
+ kind: 'reconciled',
+ currentGoal: null,
+ matchesRequestedState: false,
+ },
+ expected: { action: 'lock', notice: { kind: 'no_goal' } },
+ },
+ {
+ outcome: { kind: 'reconciliation_unavailable' },
+ expected: { action: 'lock', notice: { kind: 'unavailable' } },
+ },
+ ];
+
+ for (const { outcome, expected } of cases) {
+ assert.deepEqual(interpretGoalArmOutcome(outcome), expected);
+ }
+});
+
+test('Goal reconciliation copy explains authoritative state in Chinese and English', () => {
+ const zh = getShellCopy('zh').goalDialog;
+ assert.match(
+ zh.reconciledMatching('所有测试通过', zh.statusLabels.active),
+ /所有测试通过.*进行中.*无法确认.*提交/,
+ );
+ assert.match(zh.reconciledNoGoal, /未读到 Goal/);
+ assert.match(zh.reconciliationUnavailable, /不会重复提交/);
+
+ const en = getShellCopy('en').goalDialog;
+ assert.match(
+ en.reconciledDifferent('All tests pass', en.statusLabels.paused),
+ /All tests pass.*Paused.*differs/,
+ );
+ assert.match(en.reconciliationUnavailable, /will not submit twice/);
+});
diff --git a/apps/desktop/src/main/__tests__/goal-dialog.test.ts b/apps/desktop/src/main/__tests__/goal-dialog.test.ts
new file mode 100644
index 000000000..353ba9d3f
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/goal-dialog.test.ts
@@ -0,0 +1,270 @@
+/*
+ * 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 { afterEach, test } from 'node:test';
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { parseHTML } from 'linkedom';
+import { AstryxLocaleProvider, LocaleProvider } from '@maka/ui';
+import type { GoalArmOutcome } from '../../shared/goal-arm.js';
+import { GoalDialog } from '../../renderer/goal-dialog.js';
+
+const originalGlobals = {
+ document: globalThis.document,
+ window: globalThis.window,
+ HTMLElement: globalThis.HTMLElement,
+ HTMLIFrameElement: globalThis.HTMLIFrameElement,
+ Event: globalThis.Event,
+ Node: globalThis.Node,
+ CSS: globalThis.CSS,
+ matchMedia: globalThis.matchMedia,
+ requestAnimationFrame: globalThis.requestAnimationFrame,
+ cancelAnimationFrame: globalThis.cancelAnimationFrame,
+ IS_REACT_ACT_ENVIRONMENT: (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
+ .IS_REACT_ACT_ENVIRONMENT,
+};
+
+let mountedRoot: Root | undefined;
+
+afterEach(async () => {
+ if (mountedRoot) await act(() => mountedRoot?.unmount());
+ mountedRoot = undefined;
+ Object.assign(globalThis, originalGlobals);
+});
+
+test('ignores a stale Goal arm result after switching Sessions', async () => {
+ const first = deferred<GoalArmOutcome>();
+ const calls: string[] = [];
+ const harness = installGoalDialog(async (sessionId) => {
+ calls.push(sessionId);
+ return first.promise;
+ });
+ await harness.render('session-1');
+ await setInputValue(harness.document, 'textarea', 'Finish session one');
+ await clickButton(harness.document, 'Start');
+ assert.deepEqual(calls, ['session-1']);
+
+ await harness.render('session-2');
+ first.resolve({ kind: 'reconciliation_unavailable' });
+ await act(async () => {
+ await first.promise;
+ await Promise.resolve();
+ });
+
+ assert.doesNotMatch(harness.document.body.textContent, /cannot be confirmed/);
+ assert.equal(harness.closed, 0);
+});
+
+test('ignores a stale Goal arm rejection after closing and reopening', async () => {
+ const first = deferred<GoalArmOutcome>();
+ const harness = installGoalDialog(async () => first.promise);
+ await harness.render('session-1');
+ await setInputValue(harness.document, 'textarea', 'Finish session one');
+ await clickButton(harness.document, 'Start');
+
+ await harness.render(undefined);
+ await harness.render('session-1');
+ first.reject(new Error('old rejection'));
+ await act(async () => {
+ await first.promise.catch(() => undefined);
+ await Promise.resolve();
+ });
+
+ assert.doesNotMatch(harness.document.body.textContent, /goal could not be set/i);
+ assert.equal(harness.document.querySelector('textarea')?.hasAttribute('disabled'), false);
+ assert.equal(harness.closed, 0);
+});
+
+test('closes only for armed and locks reconciled state until reopen', async () => {
+ const goal = goalState();
+ let outcome: GoalArmOutcome = {
+ kind: 'reconciled',
+ currentGoal: null,
+ matchesRequestedState: false,
+ };
+ const harness = installGoalDialog(async () => outcome);
+ await harness.render('session-1');
+ await setInputValue(harness.document, 'textarea', 'Finish session one');
+ await clickButton(harness.document, 'Start');
+
+ assert.equal(harness.closed, 0);
+ assert.match(harness.document.body.textContent, /no Goal was found/);
+ assert.equal(harness.document.querySelector('textarea')?.hasAttribute('disabled'), true);
+ assert.equal(findButton(harness.document, 'Start').hasAttribute('disabled'), true);
+
+ await harness.render(undefined);
+ await harness.render('session-1');
+ assert.doesNotMatch(harness.document.body.textContent, /no Goal was found/);
+ assert.equal(harness.document.querySelector('textarea')?.hasAttribute('disabled'), false);
+
+ outcome = { kind: 'armed', goal };
+ await setInputValue(harness.document, 'textarea', 'Finish session one');
+ await clickButton(harness.document, 'Start');
+ assert.equal(harness.closed, 1);
+});
+
+test('keeps the Goal form editable after a deterministic rejection', async () => {
+ const harness = installGoalDialog(async () => {
+ throw new Error('Goal already exists');
+ });
+ await harness.render('session-1');
+ await setInputValue(harness.document, 'textarea', 'Finish session one');
+ await clickButton(harness.document, 'Start');
+
+ assert.equal(harness.closed, 0);
+ assert.match(harness.document.body.textContent, /goal could not be set/i);
+ assert.equal(harness.document.querySelector('textarea')?.hasAttribute('disabled'), false);
+ assert.equal(findButton(harness.document, 'Start').hasAttribute('disabled'), false);
+});
+
+function installGoalDialog(
+ arm: (sessionId: string) => Promise<GoalArmOutcome>,
+) {
+ const parsed = parseHTML('<html><body><div id="root"></div></body></html>');
+ const { document, window } = parsed;
+ const matchMedia = (media: string) => ({
+ matches: false,
+ media,
+ onchange: null,
+ addListener() {},
+ removeListener() {},
+ addEventListener() {},
+ removeEventListener() {},
+ dispatchEvent: () => false,
+ });
+ Object.assign(window, { matchMedia, scrollTo() {} });
+ Object.assign(window.HTMLElement.prototype, {
+ showModal(this: HTMLElement) {
+ this.setAttribute('open', '');
+ },
+ close(this: HTMLElement) {
+ this.removeAttribute('open');
+ },
+ });
+ Object.assign(globalThis, {
+ document,
+ window,
+ matchMedia,
+ HTMLElement: window.HTMLElement,
+ HTMLIFrameElement: window.HTMLIFrameElement ?? class HTMLIFrameElement {},
+ Event: window.Event,
+ Node: window.Node,
+ CSS: { escape: (value: string) => value },
+ requestAnimationFrame: (callback: FrameRequestCallback) => setTimeout(callback, 0),
+ cancelAnimationFrame: (handle: number) => clearTimeout(handle),
+ IS_REACT_ACT_ENVIRONMENT: true,
+ });
+ (window as unknown as { maka: unknown }).maka = {
+ goal: { arm },
+ };
+ const container = document.querySelector('#root');
+ assert.ok(container);
+ const root = createRoot(container);
+ mountedRoot = root;
+ let closed = 0;
+ return {
+ document,
+ get closed() {
+ return closed;
+ },
+ async render(sessionId: string | undefined) {
+ await act(async () => {
+ root.render(
+ createElement(LocaleProvider, {
+ locale: 'en',
+ children: createElement(AstryxLocaleProvider, {
+ children: createElement(GoalDialog, {
+ sessionId,
+ onClose: () => {
+ closed += 1;
+ },
+ }),
+ }),
+ }),
+ );
+ await Promise.resolve();
+ });
+ },
+ };
+}
+
+async function setInputValue(
+ document: Document,
+ selector: string,
+ value: string,
+): Promise<void> {
+ const input = document.querySelector(selector) as HTMLInputElement | null;
+ assert.ok(input, `missing input: ${selector}`);
+ await act(async () => {
+ input.value = value;
+ const propsKey = Object.keys(input).find((key) => key.startsWith('__reactProps$'));
+ assert.ok(propsKey, 'missing React props on input');
+ const props = (input as unknown as Record<string, unknown>)[propsKey] as {
+ onChange?: (event: { target: HTMLInputElement; defaultPrevented: boolean }) => void;
+ };
+ assert.ok(props.onChange, 'missing React change handler');
+ props.onChange({ target: input, defaultPrevented: false });
+ await Promise.resolve();
+ });
+}
+
+async function clickButton(document: Document, label: string): Promise<void> {
+ const button = findButton(document, label);
+ await act(async () => {
+ button.click();
+ await Promise.resolve();
+ });
+}
+
+function findButton(document: Document, label: string): HTMLButtonElement {
+ const button = [...document.querySelectorAll('button')].find(
+ (candidate) => candidate.textContent === label,
+ ) as HTMLButtonElement | undefined;
+ assert.ok(button, `missing button: ${label}`);
+ return button;
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((accept, decline) => {
+ resolve = accept;
+ reject = decline;
+ });
+ return { promise, resolve, reject };
+}
+
+function goalState() {
+ return {
+ id: 'goal-1',
+ revision: 1,
+ sessionId: 'session-1',
+ condition: 'Finish session one',
+ status: 'active' as const,
+ setAt: 1,
+ iterations: 0,
+ maxIterations: 50,
+ consecutiveNoProgress: 0,
+ blockCap: 8,
+ tokensAtStart: 0,
+ tokensNow: 0,
+ tokensBaselinePending: false,
+ };
+}
diff --git a/apps/desktop/src/main/__tests__/goal-preload-bridge.test.ts b/apps/desktop/src/main/__tests__/goal-preload-bridge.test.ts
new file mode 100644
index 000000000..3577daa2d
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/goal-preload-bridge.test.ts
@@ -0,0 +1,89 @@
+/*
+ * 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 test from 'node:test';
+import {
+ invokeProjectedSessionRuntimeHost,
+} from '../../preload/projected-session-runtime-host.js';
+import { desktopSessionKey } from '../../shared/runtime-host-identity.js';
+
+test('Goal arm preload routing preserves target scope and projects every outcome', async () => {
+ const scope = { hostId: 'host-1', targetEpoch: 'epoch-2' };
+ const desktopSessionId = desktopSessionKey({
+ hostId: scope.hostId,
+ sessionId: 'session-1',
+ });
+ const request = { condition: 'Finish', maxIterations: 20, tokenBudget: 1_000 };
+ const scenarios = [
+ {
+ wire: {
+ kind: 'armed',
+ goal: { id: 'goal-1', sessionId: 'session-1' },
+ },
+ projected: {
+ kind: 'armed',
+ goal: { id: 'goal-1', sessionId: desktopSessionId },
+ },
+ },
+ {
+ wire: {
+ kind: 'reconciled',
+ currentGoal: { id: 'goal-2', sessionId: 'session-1' },
+ matchesRequestedState: true,
+ },
+ projected: {
+ kind: 'reconciled',
+ currentGoal: { id: 'goal-2', sessionId: desktopSessionId },
+ matchesRequestedState: true,
+ },
+ },
+ {
+ wire: { kind: 'reconciliation_unavailable' },
+ projected: { kind: 'reconciliation_unavailable' },
+ },
+ ] as const;
+
+ for (const scenario of scenarios) {
+ const invocations: unknown[] = [];
+ const result = await invokeProjectedSessionRuntimeHost(
+ async (sessionId) => {
+ assert.equal(sessionId, desktopSessionId);
+ return { scope, sessionId: 'session-1' };
+ },
+ async (channel, targetScope, rawSessionId, ...args) => {
+ invocations.push({ channel, targetScope, rawSessionId, args });
+ return scenario.wire;
+ },
+ 'goal:arm',
+ desktopSessionId,
+ request,
+ );
+
+ assert.deepEqual(invocations, [
+ {
+ channel: 'goal:arm',
+ targetScope: scope,
+ rawSessionId: 'session-1',
+ args: [request],
+ },
+ ]);
+ assert.deepEqual(result, scenario.projected);
+ }
+});
diff --git a/apps/desktop/src/main/__tests__/runtime-host-reconnecting-ipc-main.test.ts b/apps/desktop/src/main/__tests__/runtime-host-reconnecting-ipc-main.test.ts
index 9964fc13c..75181fca2 100644
--- a/apps/desktop/src/main/__tests__/runtime-host-reconnecting-ipc-main.test.ts
+++ b/apps/desktop/src/main/__tests__/runtime-host-reconnecting-ipc-main.test.ts
@@ -28,7 +28,257 @@ import {
readWithFallback,
tryReconnectableReadResult,
} from "../ipc-reconnect-policy.js";
-import { RuntimeHostReconnectingIpcMain } from "../runtime-host-reconnecting-ipc-main.js";
+import * as ipcReconnectPolicy from "../ipc-reconnect-policy.js";
+import {
+ RuntimeHostReconnectingIpcMain,
+ RuntimeHostTargetChangedError,
+} from "../runtime-host-reconnecting-ipc-main.js";
+
+test("classifies only dispatched control connection loss for reconciliation", () => {
+ const predicate = (
+ ipcReconnectPolicy as typeof ipcReconnectPolicy & {
+ isDispatchedControlConnectionLoss?: (error: unknown) => boolean;
+ }
+ ).isDispatchedControlConnectionLoss;
+ assert.equal(typeof predicate, "function");
+ assert.equal(
+ predicate?.(
+ new RuntimeHostRequestInterruptedError(
+ "goal.arm",
+ "control",
+ "dispatched",
+ "connection_lost",
+ ),
+ ),
+ true,
+ );
+ for (const error of [
+ new RuntimeHostRequestInterruptedError(
+ "goal.arm",
+ "control",
+ "not_dispatched",
+ "connection_lost",
+ ),
+ new RuntimeHostRequestInterruptedError(
+ "goal.arm",
+ "control",
+ "dispatched",
+ "timeout",
+ ),
+ new RuntimeHostRequestInterruptedError(
+ "goal.query",
+ "query",
+ "dispatched",
+ "connection_lost",
+ ),
+ new RuntimeHostRequestInterruptedError(
+ "web-search.execute",
+ "command",
+ "dispatched",
+ "connection_lost",
+ ),
+ new Error("ordinary failure"),
+ ]) {
+ assert.equal(predicate?.(error), false);
+ }
+});
+
+test("reconciles a dispatched control on a replacement without replaying it", async () => {
+ const ipc = ipcHarness();
+ const router = new RuntimeHostReconnectingIpcMain(ipc);
+ const firstTarget = router.createTarget("target-a") as ReconciledControlTarget;
+ assert.equal(typeof firstTarget.handleReconciledControl, "function");
+ let dispatches = 0;
+ firstTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => {
+ dispatches += 1;
+ return {
+ kind: "reconcile",
+ context: { condition: "All tests pass" },
+ };
+ },
+ reconcile: async () => assert.fail("The closed candidate must not reconcile"),
+ });
+ router.activate("target-a");
+
+ const arming = ipc.invoke("goal:arm", scope("target-a"));
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ firstTarget.removeHandler("goal:arm");
+ const replacementTarget = router.createTarget("target-a") as ReconciledControlTarget;
+ let reconciliations = 0;
+ replacementTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => assert.fail("The mutation must not be replayed"),
+ reconcile: async (context) => {
+ reconciliations += 1;
+ assert.deepEqual(context, { condition: "All tests pass" });
+ return { kind: "reconciled", currentGoal: "goal-1" };
+ },
+ });
+
+ assert.deepEqual(await arming, {
+ kind: "reconciled",
+ currentGoal: "goal-1",
+ });
+ assert.equal(dispatches, 1);
+ assert.equal(reconciliations, 1);
+ router.close();
+});
+
+test("bounds reconciliation when no replacement candidate becomes available", async () => {
+ const ipc = ipcHarness();
+ const router = new RuntimeHostReconnectingIpcMain(ipc, {
+ reconciliationWaitTimeoutMs: 5,
+ });
+ const firstTarget = router.createTarget("target-a") as ReconciledControlTarget;
+ let dispatches = 0;
+ firstTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => {
+ dispatches += 1;
+ return { kind: "reconcile", context: { sessionId: "session-1" } };
+ },
+ reconcile: async () => assert.fail("The unavailable candidate must not reconcile"),
+ reconciliationUnavailable: async () => ({ kind: "reconciliation_unavailable" }),
+ });
+ router.activate("target-a");
+
+ const arming = ipc.invoke("goal:arm", scope("target-a"));
+ const settled = arming.then(
+ (value) => ({ ok: true as const, value }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ firstTarget.removeHandler("goal:arm");
+
+ try {
+ assert.deepEqual(
+ await Promise.race([
+ settled,
+ new Promise<{ readonly timedOut: true }>((resolve) =>
+ setTimeout(() => resolve({ timedOut: true }), 25),
+ ),
+ ]),
+ {
+ ok: true,
+ value: { kind: "reconciliation_unavailable" },
+ },
+ );
+ assert.equal(dispatches, 1);
+ } finally {
+ router.close();
+ await settled;
+ }
+});
+
+test("retries only reconciliation when its replacement connection is lost", async () => {
+ const ipc = ipcHarness();
+ const router = new RuntimeHostReconnectingIpcMain(ipc);
+ const firstTarget = router.createTarget("target-a") as ReconciledControlTarget;
+ let dispatches = 0;
+ firstTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => {
+ dispatches += 1;
+ return { kind: "reconcile", context: { sessionId: "session-1" } };
+ },
+ reconcile: async () => assert.fail("The closed candidate must not reconcile"),
+ });
+ router.activate("target-a");
+
+ const arming = ipc.invoke("goal:arm", scope("target-a"));
+ const settled = arming.then(
+ (value) => ({ ok: true as const, value }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ firstTarget.removeHandler("goal:arm");
+ const failedTarget = router.createTarget("target-a") as ReconciledControlTarget;
+ const reconciliationEntered = deferred();
+ const failReconciliation = deferred();
+ failedTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => assert.fail("The mutation must not be replayed"),
+ reconcile: async () => {
+ reconciliationEntered.resolve();
+ await failReconciliation.promise;
+ throw new RuntimeHostRequestInterruptedError(
+ "goal.query",
+ "query",
+ "dispatched",
+ "connection_lost",
+ );
+ },
+ });
+ await reconciliationEntered.promise;
+ failReconciliation.resolve();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ failedTarget.removeHandler("goal:arm");
+ const recoveredTarget = router.createTarget("target-a") as ReconciledControlTarget;
+ let reconciliations = 0;
+ recoveredTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => assert.fail("The mutation must not be replayed"),
+ reconcile: async (context) => {
+ reconciliations += 1;
+ assert.deepEqual(context, { sessionId: "session-1" });
+ return { kind: "reconciled", currentGoal: "goal-1" };
+ },
+ });
+
+ assert.deepEqual(await settled, {
+ ok: true,
+ value: { kind: "reconciled", currentGoal: "goal-1" },
+ });
+ assert.equal(dispatches, 1);
+ assert.equal(reconciliations, 1);
+ router.close();
+});
+
+test("never reconciles a control through a different target epoch", async () => {
+ const ipc = ipcHarness();
+ const router = new RuntimeHostReconnectingIpcMain(ipc);
+ const firstTarget = router.createTarget("target-a") as ReconciledControlTarget;
+ let dispatches = 0;
+ firstTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => {
+ dispatches += 1;
+ return { kind: "reconcile", context: { sessionId: "session-1" } };
+ },
+ reconcile: async () => assert.fail("The closed candidate must not reconcile"),
+ });
+ router.activate("target-a");
+
+ const arming = ipc.invoke("goal:arm", scope("target-a"));
+ const settled = arming.then(
+ () => ({ settled: true }),
+ (error: unknown) => ({ settled: true, error }),
+ );
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ firstTarget.removeHandler("goal:arm");
+ const otherTarget = router.createTarget("target-b") as ReconciledControlTarget;
+ let otherReconciliations = 0;
+ otherTarget.handleReconciledControl("goal:arm", {
+ dispatch: async () => assert.fail("The mutation must not be replayed"),
+ reconcile: async () => {
+ otherReconciliations += 1;
+ return { kind: "reconciled" };
+ },
+ });
+ router.activate("target-b");
+ const pending = Promise.race([
+ settled,
+ new Promise<{ settled: false }>((resolve) =>
+ setImmediate(() => resolve({ settled: false })),
+ ),
+ ]);
+ assert.deepEqual(await pending, { settled: false });
+
+ router.deactivate("target-a");
+ const result = await settled;
+ assert.equal(result.settled, true);
+ assert.ok(
+ "error" in result && result.error instanceof RuntimeHostTargetChangedError,
+ );
+ assert.equal(dispatches, 1);
+ assert.equal(otherReconciliations, 0);
+ router.close();
+});
test("holds an invocation across a Runtime Host candidate replacement", async () => {
const ipc = ipcHarness();
@@ -276,6 +526,22 @@ test("read adapters project ordinary failures without hiding reconnectable failu
type IpcHandler = Parameters<IpcMain["handle"]>[1];
+type ReconciledControlTarget = ReturnType<
+ RuntimeHostReconnectingIpcMain["createTarget"]
+> & {
+ handleReconciledControl(
+ channel: string,
+ handlers: {
+ dispatch: IpcHandler;
+ reconcile: (context: unknown, ...args: Parameters<IpcHandler>) => Promise<unknown>;
+ reconciliationUnavailable?: (
+ context: unknown,
+ ...args: Parameters<IpcHandler>
+ ) => Promise<unknown>;
+ },
+ ): void;
+};
+
function ipcHarness() {
const handlers = new Map<string, IpcHandler>();
return {
diff --git a/apps/desktop/src/main/__tests__/runtime-host-session-domains-ipc-main.test.ts b/apps/desktop/src/main/__tests__/runtime-host-session-domains-ipc-main.test.ts
index 8b645a777..ee817a502 100644
--- a/apps/desktop/src/main/__tests__/runtime-host-session-domains-ipc-main.test.ts
+++ b/apps/desktop/src/main/__tests__/runtime-host-session-domains-ipc-main.test.ts
@@ -24,7 +24,18 @@ import { projectDeepResearchClientProgress } from '@maka/core/deep-research-clie
import { type DeepResearchRun } from '@maka/core/deep-research-run';
import { type PlanSessionState } from '@maka/core/plan';
import { type ShellRunUpdate } from '@maka/core/events';
-import { encodeDeepResearchSnapshot } from '@maka/runtime-host/protocol';
+import {
+ encodeDeepResearchSnapshot,
+ type GoalProjection,
+} from '@maka/runtime-host/protocol';
+import {
+ RuntimeHostOperationError,
+ RuntimeHostRequestInterruptedError,
+} from '@maka/runtime-host/client';
+import type {
+ ReconciledControlHandlers,
+ ReconnectableReadIpcMain,
+} from '../ipc-reconnect-policy.js';
import {
projectEmbeddedDeepResearch,
projectHostedDeepResearch,
@@ -36,9 +47,345 @@ import {
type DomainClient = RuntimeHostSessionDomainsIpcDeps['client'];
+test('goal:arm reconciles a lost dispatched response without dispatching again', async () => {
+ const previous = goalProjection({ goalId: 'goal-old', condition: 'Old goal' });
+ const requested = {
+ condition: ' Finish the adapter ',
+ maxIterations: 20,
+ tokenBudget: 1_000,
+ };
+ let armCalls = 0;
+ const firstIpc = reconciledIpcHarness();
+ registerDomainsIpc(
+ {
+ client: domainClient({
+ queryGoal: async () => ({ sessionId: 'session-1', goal: previous }),
+ armGoal: async () => {
+ armCalls += 1;
+ throw new RuntimeHostRequestInterruptedError(
+ 'goal.arm',
+ 'control',
+ 'dispatched',
+ 'connection_lost',
+ );
+ },
+ }),
+ emitModeChanged() {},
+ },
+ firstIpc,
+ );
+
+ const step = await firstIpc.dispatch('goal:arm', 'session-1', requested);
+ assert.equal((step as { kind: string }).kind, 'reconcile');
+
+ const replacementIpc = reconciledIpcHarness();
+ registerDomainsIpc(
+ {
+ client: domainClient({
+ queryGoal: async () => ({
+ sessionId: 'session-1',
+ goal: goalProjection({ condition: 'Finish the adapter' }),
+ }),
+ armGoal: async () => assert.fail('replacement must never re-arm the Goal'),
+ }),
+ emitModeChanged() {},
+ },
+ replacementIpc,
+ );
+
+ assert.deepEqual(
+ await replacementIpc.reconcile(
+ 'goal:arm',
+ (step as { context: unknown }).context,
+ 'session-1',
+ requested,
+ ),
+ {
+ kind: 'reconciled',
+ currentGoal: {
+ id: 'goal-1',
+ revision: 3,
+ sessionId: 'session-1',
+ condition: 'Finish the adapter',
+ status: 'active',
+ setAt: 1,
+ iterations: 2,
+ maxIterations: 20,
+ consecutiveNoProgress: 0,
+ blockCap: 8,
+ tokenBudget: 1_000,
+ tokensAtStart: 0,
+ tokensNow: 120,
+ tokensBaselinePending: false,
+ },
+ matchesRequestedState: true,
+ },
+ );
+ assert.equal(armCalls, 1);
+});
+
+test('goal:arm reconciliation compares every canonical requested field', async () => {
+ const firstIpc = reconciledIpcHarness();
+ registerDomainsIpc(
+ {
+ client: domainClient({
+ queryGoal: async () => ({
+ sessionId: 'session-1',
+ goal: goalProjection({ goalId: 'goal-old', condition: 'Old goal' }),
+ }),
+ armGoal: async () => {
+ throw new RuntimeHostRequestInterruptedError(
+ 'goal.arm',
+ 'control',
+ 'dispatched',
+ 'connection_lost',
+ );
+ },
+ }),
+ emitModeChanged() {},
+ },
+ firstIpc,
+ );
+ const requested = { condition: ' Default budget goal ' };
+ const step = await firstIpc.dispatch('goal:arm', 'session-1', requested);
+ const context = (step as { context: unknown }).context;
+ const cases: ReadonlyArray<{
+ readonly name: string;
+ readonly goal: GoalProjection;
+ readonly expected: boolean;
+ }> = [
+ {
+ name: 'a new Goal matches the trimmed condition and default iteration budget',
+ goal: goalProjection({
+ goalId: 'goal-new',
+ condition: 'Default budget goal',
+ maxIterations: 50,
+ tokenBudget: null,
+ }),
+ expected: true,
+ },
+ {
+ name: 'the previous Goal identity does not match',
+ goal: goalProjection({
+ goalId: 'goal-old',
+ condition: 'Default budget goal',
+ maxIterations: 50,
+ tokenBudget: null,
+ }),
+ expected: false,
+ },
+ {
+ name: 'a different Session does not match',
+ goal: goalProjection({
+ goalId: 'goal-new',
+ sessionId: 'session-2',
+ condition: 'Default budget goal',
+ maxIterations: 50,
+ tokenBudget: null,
+ }),
+ expected: false,
+ },
+ {
+ name: 'a different condition does not match',
+ goal: goalProjection({
+ goalId: 'goal-new',
+ condition: 'Different goal',
+ maxIterations: 50,
+ tokenBudget: null,
+ }),
+ expected: false,
+ },
+ {
+ name: 'a different iteration budget does not match',
+ goal: goalProjection({
+ goalId: 'goal-new',
+ condition: 'Default budget goal',
+ maxIterations: 49,
+ tokenBudget: null,
+ }),
+ expected: false,
+ },
+ {
+ name: 'a different token budget does not match',
+ goal: goalProjection({
+ goalId: 'goal-new',
+ condition: 'Default budget goal',
+ maxIterations: 50,
+ tokenBudget: 1,
+ }),
+ expected: false,
+ },
+ ];
+
+ for (const scenario of cases) {
+ const ipc = reconciledIpcHarness();
+ registerDomainsIpc(
+ {
+ client: domainClient({
+ queryGoal: async () => ({ sessionId: 'session-1', goal: scenario.goal }),
+ }),
+ emitModeChanged() {},
+ },
+ ipc,
+ );
+ const outcome = await ipc.reconcile('goal:arm', context, 'session-1', requested) as {
+ readonly matchesRequestedState: boolean;
+ };
+ assert.equal(outcome.matchesRequestedState, scenario.expected, scenario.name);
+ }
+});
+
+test('goal:arm reconciliation reports different, missing, and unavailable authority', async () => {
+ const firstIpc = reconciledIpcHarness();
+ registerDomainsIpc(
+ {
+ client: domainClient({
+ queryGoal: async () => ({
+ sessionId: 'session-1',
+ goal: goalProjection({ goalId: 'goal-old', condition: 'Old goal' }),
+ }),
+ armGoal: async () => {
+ throw new RuntimeHostRequestInterruptedError(
+ 'goal.arm',
+ 'control',
+ 'dispatched',
+ 'connection_lost',
+ );
+ },
+ }),
+ emitModeChanged() {},
+ },
+ firstIpc,
+ );
+ const step = await firstIpc.dispatch('goal:arm', 'session-1', {
+ condition: 'Default budget goal',
+ });
+ const context = (step as { context: unknown }).context;
+ assert.deepEqual(
+ await firstIpc.reconciliationUnavailable(
+ 'goal:arm',
+ context,
+ 'session-1',
+ { condition: 'Default budget goal' },
+ ),
+ { kind: 'reconciliation_unavailable' },
+ );
+
+ const reconcileWith = async (
+ queryGoal: DomainClient['queryGoal'],
+ ): Promise<unknown> => {
+ const ipc = reconciledIpcHarness();
+ registerDomainsIpc(
+ {
+ client: domainClient({ queryGoal }),
+ emitModeChanged() {},
+ },
+ ipc,
+ );
+ return ipc.reconcile('goal:arm', context, 'session-1', {
+ condition: 'Default budget goal',
+ });
+ };
+
+ const oldGoal = goalProjection({
+ goalId: 'goal-old',
+ condition: 'Default budget goal',
+ maxIterations: 50,
+ tokenBudget: null,
+ });
+ assert.deepEqual(
+ await reconcileWith(async () => ({ sessionId: 'session-1', goal: oldGoal })),
+ {
+ kind: 'reconciled',
+ currentGoal: {
+ id: 'goal-old',
+ revision: 3,
+ sessionId: 'session-1',
+ condition: 'Default budget goal',
+ status: 'active',
+ setAt: 1,
+ iterations: 2,
+ maxIterations: 50,
+ consecutiveNoProgress: 0,
+ blockCap: 8,
+ tokensAtStart: 0,
+ tokensNow: 120,
+ tokensBaselinePending: false,
+ },
+ matchesRequestedState: false,
+ },
+ );
+ assert.deepEqual(
+ await reconcileWith(async () => ({ sessionId: 'session-1', goal: null })),
+ { kind: 'reconciled', currentGoal: null, matchesRequestedState: false },
+ );
+ assert.deepEqual(
+ await reconcileWith(async () => {
+ throw new Error('query unavailable');
+ }),
+ { kind: 'reconciliation_unavailable' },
+ );
+ await assert.rejects(
+ reconcileWith(async () => {
+ throw new RuntimeHostRequestInterruptedError(
+ 'goal.query',
+ 'query',
+ 'dispatched',
+ 'connection_lost',
+ );
+ }),
+ RuntimeHostRequestInterruptedError,
+ );
+});
+
+test('goal:arm preserves deterministic and non-dispatched rejection semantics', async () => {
+ const errors = [
+ new RuntimeHostRequestInterruptedError(
+ 'goal.arm',
+ 'control',
+ 'not_dispatched',
+ 'connection_lost',
+ ),
+ new RuntimeHostRequestInterruptedError(
+ 'goal.arm',
+ 'control',
+ 'dispatched',
+ 'timeout',
+ ),
+ new RuntimeHostOperationError(
+ 'goal.arm',
+ 'host_draining',
+ 'Runtime Host is draining',
+ ),
+ ];
+ for (const expected of errors) {
+ const ipc = ipcHarness();
+ let armCalls = 0;
+ registerDomainsIpc(
+ {
+ client: domainClient({
+ queryGoal: async () => ({ sessionId: 'session-1', goal: null }),
+ armGoal: async () => {
+ armCalls += 1;
+ throw expected;
+ },
+ }),
+ emitModeChanged() {},
+ },
+ ipc,
+ );
+ await assert.rejects(
+ ipc.invoke('goal:arm', 'session-1', { condition: 'Finish' }),
+ (actual) => actual === expected,
+ );
+ assert.equal(armCalls, 1);
+ }
+});
+
test('goal:arm takes the Session from the scoped channel and refuses any other key', async () => {
const armed: unknown[] = [];
const client = domainClient({
+ queryGoal: async (sessionId) => ({ sessionId, goal: null }),
armGoal: async (input) => {
armed.push(input);
return { sessionId: input.sessionId, goal: goalProjection() };
@@ -47,7 +394,7 @@ test('goal:arm takes the Session from the scoped channel and refuses any other k
const ipc = ipcHarness();
registerDomainsIpc({ client, emitModeChanged() {} }, ipc);
- const goal = await ipc.invoke('goal:arm', 'session-1', {
+ const outcome = await ipc.invoke('goal:arm', 'session-1', {
condition: 'Finish the adapter',
maxIterations: 20,
tokenBudget: 1_000,
@@ -60,7 +407,14 @@ test('goal:arm takes the Session from the scoped channel and refuses any other k
tokenBudget: 1_000,
},
]);
- assert.equal((goal as { id: string }).id, 'goal-1');
+ assert.equal(
+ (outcome as { kind: string; goal: { id: string } }).kind,
+ 'armed',
+ );
+ assert.equal(
+ (outcome as { kind: string; goal: { id: string } }).goal.id,
+ 'goal-1',
+ );
// Omitted budgets are "not chosen", which the Host reads as its defaults.
await ipc.invoke('goal:arm', 'session-1', { condition: 'Finish the adapter' });
@@ -107,6 +461,9 @@ test('adapts Host Goal, Task, Deep Research, and Resource projections', async ()
clearGoal: async (sessionId) => {
controls.push(sessionId);
},
+ controlGoalWithRetry: async (sessionId, action) => {
+ controls.push({ sessionId, action });
+ },
queryDeepResearch: async () => hostedResearch(),
});
const ipc = ipcHarness();
@@ -135,7 +492,13 @@ test('adapts Host Goal, Task, Deep Research, and Resource projections', async ()
tokensBaselinePending: false,
});
await ipc.invoke('goal:clear', 'session-1');
- assert.deepEqual(controls, ['session-1']);
+ await ipc.invoke('goal:pause', 'session-1');
+ await ipc.invoke('goal:resume', 'session-1');
+ assert.deepEqual(controls, [
+ 'session-1',
+ { sessionId: 'session-1', action: 'pause' },
+ { sessionId: 'session-1', action: 'resume' },
+ ]);
assert.deepEqual(await ipc.invoke('deepResearch:get', 'session-1'), {
sessionId: 'session-1',
objective: 'Inspect the adapter',
@@ -809,6 +1172,7 @@ function domainClient(overrides: Partial<DomainClient>): DomainClient {
return {
armGoal: unavailable,
clearGoal: unavailable,
+ controlGoalWithRetry: unavailable,
acquireRuntimeResourceController: unavailable,
controlPlan: unavailable,
controlRuntimeResource: unavailable,
@@ -830,7 +1194,13 @@ function domainClient(overrides: Partial<DomainClient>): DomainClient {
} as DomainClient;
}
-function goalProjection() {
+function goalProjection(
+ overrides: Partial<GoalProjection> = {},
+): GoalProjection {
+ return { ...baseGoalProjection(), ...overrides };
+}
+
+function baseGoalProjection() {
return {
goalId: 'goal-1',
revision: 3,
@@ -966,10 +1336,63 @@ function ipcHarness() {
};
}
+function reconciledIpcHarness() {
+ const ordinaryHandlers = new Map<string, IpcHandler>();
+ const controlHandlers = new Map<
+ string,
+ ReconciledControlHandlers<unknown, unknown>
+ >();
+ return {
+ handle(channel: string, handler: IpcHandler) {
+ ordinaryHandlers.set(channel, handler);
+ },
+ handleReconciledControl<Context, Result>(
+ channel: string,
+ handlers: ReconciledControlHandlers<Context, Result>,
+ ) {
+ controlHandlers.set(
+ channel,
+ handlers as unknown as ReconciledControlHandlers<unknown, unknown>,
+ );
+ },
+ async dispatch(channel: string, ...args: unknown[]): Promise<unknown> {
+ const handlers = controlHandlers.get(channel);
+ assert.ok(handlers, `missing reconciled control: ${channel}`);
+ return handlers.dispatch({} as never, ...args);
+ },
+ async reconcile(
+ channel: string,
+ context: unknown,
+ ...args: unknown[]
+ ): Promise<unknown> {
+ const handlers = controlHandlers.get(channel);
+ assert.ok(handlers, `missing reconciled control: ${channel}`);
+ return handlers.reconcile(context, {} as never, ...args);
+ },
+ async reconciliationUnavailable(
+ channel: string,
+ context: unknown,
+ ...args: unknown[]
+ ): Promise<unknown> {
+ const handlers = controlHandlers.get(channel);
+ assert.ok(handlers, `missing reconciled control: ${channel}`);
+ return handlers.reconciliationUnavailable(context, {} as never, ...args);
+ },
+ } satisfies ReconnectableReadIpcMain & {
+ dispatch(channel: string, ...args: unknown[]): Promise<unknown>;
+ reconcile(channel: string, context: unknown, ...args: unknown[]): Promise<unknown>;
+ reconciliationUnavailable(
+ channel: string,
+ context: unknown,
+ ...args: unknown[]
+ ): Promise<unknown>;
+ };
+}
+
function registerDomainsIpc(
deps: Omit<RuntimeHostSessionDomainsIpcDeps, 'sessionObserver'> &
Partial<Pick<RuntimeHostSessionDomainsIpcDeps, 'sessionObserver'>>,
- ipcMain: Pick<IpcMain, 'handle'>,
+ ipcMain: ReconnectableReadIpcMain,
) {
return registerRuntimeHostSessionDomainsIpc(
{
diff --git a/apps/desktop/src/main/ipc-reconnect-policy.ts b/apps/desktop/src/main/ipc-reconnect-policy.ts
index 147b44f4c..114db729a 100644
--- a/apps/desktop/src/main/ipc-reconnect-policy.ts
+++ b/apps/desktop/src/main/ipc-reconnect-policy.ts
@@ -27,8 +27,33 @@ import { HOST_OPERATION_SPECS } from "@maka/runtime-host/protocol";
export type IpcHandler = Parameters<IpcMain["handle"]>[1];
+export type ReconciledControlStep<Context, Result> =
+ | { readonly kind: "completed"; readonly value: Result }
+ | { readonly kind: "reconcile"; readonly context: Context };
+
+export interface ReconciledControlHandlers<Context, Result> {
+ dispatch(
+ event: Parameters<IpcHandler>[0],
+ ...args: unknown[]
+ ): Promise<ReconciledControlStep<Context, Result>>;
+ reconcile(
+ context: Context,
+ event: Parameters<IpcHandler>[0],
+ ...args: unknown[]
+ ): Promise<Result>;
+ reconciliationUnavailable(
+ context: Context,
+ event: Parameters<IpcHandler>[0],
+ ...args: unknown[]
+ ): Promise<Result>;
+}
+
export interface ReconnectableReadIpcMain extends Pick<IpcMain, "handle"> {
handleReconnectableRead?(channel: string, listener: IpcHandler): void;
+ handleReconciledControl?<Context, Result>(
+ channel: string,
+ handlers: ReconciledControlHandlers<Context, Result>,
+ ): void;
}
export function handleReconnectableRead(
@@ -43,6 +68,23 @@ export function handleReconnectableRead(
}
}
+export function handleReconciledControl<Context, Result>(
+ ipcMain: ReconnectableReadIpcMain,
+ channel: string,
+ handlers: ReconciledControlHandlers<Context, Result>,
+): void {
+ if (ipcMain.handleReconciledControl) {
+ ipcMain.handleReconciledControl(channel, handlers);
+ return;
+ }
+ ipcMain.handle(channel, async (event, ...args) => {
+ const step = await handlers.dispatch(event, ...args);
+ return step.kind === "completed"
+ ? step.value
+ : handlers.reconcile(step.context, event, ...args);
+ });
+}
+
export function isReconnectableReadFailure(error: unknown): boolean {
return (
(error instanceof RuntimeHostOperationError &&
@@ -54,6 +96,15 @@ export function isReconnectableReadFailure(error: unknown): boolean {
);
}
+export function isDispatchedControlConnectionLoss(error: unknown): boolean {
+ return (
+ error instanceof RuntimeHostRequestInterruptedError &&
+ error.mode === "control" &&
+ error.dispatch === "dispatched" &&
+ error.reason === "connection_lost"
+ );
+}
+
export function rethrowReconnectableReadFailure(error: unknown): void {
if (isReconnectableReadFailure(error)) throw error;
}
diff --git a/apps/desktop/src/main/runtime-host-desktop-candidate.ts b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
index bf945b7a0..c6e9164e2 100644
--- a/apps/desktop/src/main/runtime-host-desktop-candidate.ts
+++ b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
@@ -70,7 +70,11 @@ import {
} from "./runtime-host-session-execution-ipc-main.js";
import { RuntimeHostSessionObservationRegistry } from "./runtime-host-session-observation-registry.js";
import { RuntimeHostSessionObserver } from "./runtime-host-session-observer.js";
-import type { IpcHandler, ReconnectableReadIpcMain } from "./ipc-reconnect-policy.js";
+import type {
+ IpcHandler,
+ ReconciledControlHandlers,
+ ReconnectableReadIpcMain,
+} from "./ipc-reconnect-policy.js";
import type { RuntimeHostTargetIpcMain } from "./runtime-host-reconnecting-ipc-main.js";
import {
desktopSessionResourceKey,
@@ -751,6 +755,45 @@ class ScopedIpcMain implements ReconnectableReadIpcMain {
this.#handle(channel, listener, true);
}
+ handleReconciledControl<Context, Result>(
+ channel: string,
+ handlers: ReconciledControlHandlers<Context, Result>,
+ ): void {
+ if (this.#closed)
+ throw new Error("Desktop Runtime Host candidate IPC is closed");
+ if (this.#channels.has(channel)) {
+ throw new Error(
+ `Desktop Runtime Host candidate registered duplicate IPC: ${channel}`,
+ );
+ }
+ const scopedHandlers: ReconciledControlHandlers<Context, Result> = {
+ dispatch: (event, scope, ...args) => {
+ requireDesktopTargetScope(scope, this.scope);
+ return handlers.dispatch(event, ...args);
+ },
+ reconcile: (context, event, scope, ...args) => {
+ requireDesktopTargetScope(scope, this.scope);
+ return handlers.reconcile(context, event, ...args);
+ },
+ reconciliationUnavailable: (context, event, scope, ...args) => {
+ requireDesktopTargetScope(scope, this.scope);
+ return handlers.reconciliationUnavailable(context, event, ...args);
+ },
+ };
+ if (this.#ipcMain.handleReconciledControl) {
+ this.#ipcMain.handleReconciledControl(channel, scopedHandlers);
+ } else {
+ this.#ipcMain.handle(channel, async (event, scope, ...args) => {
+ requireDesktopTargetScope(scope, this.scope);
+ const step = await handlers.dispatch(event, ...args);
+ return step.kind === "completed"
+ ? step.value
+ : handlers.reconcile(step.context, event, ...args);
+ });
+ }
+ this.#channels.add(channel);
+ }
+
#handle(channel: string, listener: IpcHandler, reconnectableRead: boolean): void {
if (this.#closed)
throw new Error("Desktop Runtime Host candidate IPC is closed");
diff --git a/apps/desktop/src/main/runtime-host-reconnecting-ipc-main.ts b/apps/desktop/src/main/runtime-host-reconnecting-ipc-main.ts
index 305125e43..3875fb5f4 100644
--- a/apps/desktop/src/main/runtime-host-reconnecting-ipc-main.ts
+++ b/apps/desktop/src/main/runtime-host-reconnecting-ipc-main.ts
@@ -21,9 +21,31 @@ import type { IpcMain } from "electron";
import {
isReconnectableReadFailure,
type IpcHandler,
+ type ReconciledControlHandlers,
type ReconnectableReadIpcMain,
} from "./ipc-reconnect-policy.js";
+type ReconcileIpcHandler = (
+ context: unknown,
+ event: Parameters<IpcHandler>[0],
+ ...args: unknown[]
+) => Promise<unknown>;
+
+type ReconciliationUnavailableIpcHandler = ReconcileIpcHandler;
+
+const DEFAULT_RECONCILIATION_WAIT_TIMEOUT_MS = 15_000;
+
+export interface RuntimeHostReconnectingIpcMainOptions {
+ readonly reconciliationWaitTimeoutMs?: number;
+}
+
+class ReconciliationWaitExpiredError extends Error {
+ constructor() {
+ super("Runtime Host reconciliation replacement wait expired");
+ this.name = "ReconciliationWaitExpiredError";
+ }
+}
+
interface HandlerWaiter {
readonly epoch: string;
readonly resolve: (handler: BoundHandler) => void;
@@ -34,11 +56,14 @@ interface BoundHandler {
readonly epoch: string;
readonly owner: symbol;
readonly listener: IpcHandler;
+ readonly reconcile?: ReconcileIpcHandler;
+ readonly reconciliationUnavailable?: ReconciliationUnavailableIpcHandler;
}
interface HandlerSlot {
readonly waiters: Set<HandlerWaiter>;
readonly reconnectableRead: boolean;
+ readonly reconciledControl: boolean;
readonly handlers: Map<string, BoundHandler>;
}
@@ -65,10 +90,20 @@ export class RuntimeHostReconnectingIpcMain {
readonly #ipcMain: Pick<IpcMain, "handle" | "removeHandler">;
readonly #slots = new Map<string, HandlerSlot>();
readonly #activeEpochs = new Set<string>();
+ readonly #reconciliationWaitTimeoutMs: number;
#closed = false;
- constructor(ipcMain: Pick<IpcMain, "handle" | "removeHandler">) {
+ constructor(
+ ipcMain: Pick<IpcMain, "handle" | "removeHandler">,
+ options: RuntimeHostReconnectingIpcMainOptions = {},
+ ) {
this.#ipcMain = ipcMain;
+ const reconciliationWaitTimeoutMs =
+ options.reconciliationWaitTimeoutMs ?? DEFAULT_RECONCILIATION_WAIT_TIMEOUT_MS;
+ if (!Number.isSafeInteger(reconciliationWaitTimeoutMs) || reconciliationWaitTimeoutMs <= 0) {
+ throw new TypeError("Runtime Host reconciliation wait timeout must be positive");
+ }
+ this.#reconciliationWaitTimeoutMs = reconciliationWaitTimeoutMs;
}
createTarget(epoch: string): RuntimeHostTargetIpcMain {
@@ -79,9 +114,11 @@ export class RuntimeHostReconnectingIpcMain {
epoch,
isActive: () => this.#activeEpochs.has(epoch),
handle: (channel, listener) =>
- this.#handle(epoch, owner, channel, listener, false),
+ this.#handle(epoch, owner, channel, listener, false, false),
handleReconnectableRead: (channel, listener) =>
- this.#handle(epoch, owner, channel, listener, true),
+ this.#handle(epoch, owner, channel, listener, true, false),
+ handleReconciledControl: (channel, handlers) =>
+ this.#handleReconciledControl(epoch, owner, channel, handlers),
removeHandler: (channel) => this.#removeHandler(owner, channel),
};
}
@@ -120,6 +157,9 @@ export class RuntimeHostReconnectingIpcMain {
channel: string,
listener: IpcHandler,
reconnectableRead: boolean,
+ reconciledControl: boolean,
+ reconcile?: ReconcileIpcHandler,
+ reconciliationUnavailable?: ReconciliationUnavailableIpcHandler,
): void {
if (this.#closed) throw new Error("Desktop Runtime Host IPC router is closed");
let slot = this.#slots.get(channel);
@@ -128,6 +168,7 @@ export class RuntimeHostReconnectingIpcMain {
handlers: new Map(),
waiters: new Set(),
reconnectableRead,
+ reconciledControl,
};
this.#ipcMain.handle(channel, (event, ...args) =>
this.#dispatch(created, event, args),
@@ -135,13 +176,22 @@ export class RuntimeHostReconnectingIpcMain {
this.#slots.set(channel, created);
slot = created;
}
- if (slot.reconnectableRead !== reconnectableRead) {
+ if (
+ slot.reconnectableRead !== reconnectableRead ||
+ slot.reconciledControl !== reconciledControl
+ ) {
throw new Error(`Desktop Runtime Host IPC policy changed: ${channel}`);
}
if (slot.handlers.has(epoch)) {
throw new Error(`Desktop Runtime Host IPC handler already exists: ${channel}`);
}
- const handler = { epoch, owner, listener };
+ const handler = {
+ epoch,
+ owner,
+ listener,
+ ...(reconcile ? { reconcile } : {}),
+ ...(reconciliationUnavailable ? { reconciliationUnavailable } : {}),
+ };
slot.handlers.set(epoch, handler);
for (const waiter of [...slot.waiters]) {
if (waiter.epoch !== epoch) continue;
@@ -150,6 +200,24 @@ export class RuntimeHostReconnectingIpcMain {
}
}
+ #handleReconciledControl<Context, Result>(
+ epoch: string,
+ owner: symbol,
+ channel: string,
+ handlers: ReconciledControlHandlers<Context, Result>,
+ ): void {
+ this.#handle(
+ epoch,
+ owner,
+ channel,
+ handlers.dispatch as IpcHandler,
+ false,
+ true,
+ handlers.reconcile as unknown as ReconcileIpcHandler,
+ handlers.reconciliationUnavailable as unknown as ReconciliationUnavailableIpcHandler,
+ );
+ }
+
#removeHandler(owner: symbol, channel: string): void {
const slot = this.#slots.get(channel);
if (!slot) return;
@@ -164,27 +232,79 @@ export class RuntimeHostReconnectingIpcMain {
args: readonly unknown[],
): Promise<unknown> {
const epoch = this.#requireTargetEpoch(args[0]);
- let handler = slot.handlers.get(epoch);
- if (!handler) handler = await this.#waitForHandler(slot, epoch);
+ let handler: BoundHandler =
+ slot.handlers.get(epoch) ?? await this.#waitForHandler(slot, epoch);
+ let reconciliationContext: unknown;
+ let reconciling = false;
+ let reconciliationDeadline: number | undefined;
+ const waitForReplacement = async (
+ previous: BoundHandler,
+ ): Promise<BoundHandler | undefined> => {
+ if (!reconciling) return this.#waitForHandler(slot, epoch, previous);
+ const remainingMs = Math.max(
+ 0,
+ (reconciliationDeadline ?? Date.now()) - Date.now(),
+ );
+ try {
+ return await this.#waitForHandler(slot, epoch, previous, remainingMs);
+ } catch (error) {
+ if (error instanceof ReconciliationWaitExpiredError) return undefined;
+ throw error;
+ }
+ };
+ const unavailable = (): Promise<unknown> =>
+ requireReconciliationUnavailableHandler(handler)(
+ reconciliationContext,
+ event,
+ ...args,
+ );
while (true) {
try {
- const result = await handler.listener(event, ...args);
+ const result = reconciling
+ ? await requireReconcileHandler(handler)(reconciliationContext, event, ...args)
+ : await handler.listener(event, ...args);
this.#assertActive(epoch);
- if (slot.reconnectableRead && slot.handlers.get(epoch) !== handler) {
- handler = await this.#waitForHandler(slot, epoch, handler);
+ if (
+ (slot.reconnectableRead || reconciling) &&
+ slot.handlers.get(epoch) !== handler
+ ) {
+ const replacement = await waitForReplacement(handler);
+ if (!replacement) return unavailable();
+ handler = replacement;
+ continue;
+ }
+ if (slot.reconciledControl && !reconciling) {
+ const step = requireReconciledControlStep(result);
+ if (step.kind === "completed") return step.value;
+ reconciliationContext = step.context;
+ reconciling = true;
+ reconciliationDeadline = Date.now() + this.#reconciliationWaitTimeoutMs;
+ const replacement = await waitForReplacement(handler);
+ if (!replacement) return unavailable();
+ handler = replacement;
continue;
}
return result;
} catch (error) {
this.#assertActive(epoch);
- if (slot.reconnectableRead && slot.handlers.get(epoch) !== handler) {
- handler = await this.#waitForHandler(slot, epoch, handler);
+ if (
+ (slot.reconnectableRead || reconciling) &&
+ slot.handlers.get(epoch) !== handler
+ ) {
+ const replacement = await waitForReplacement(handler);
+ if (!replacement) return unavailable();
+ handler = replacement;
continue;
}
- if (!slot.reconnectableRead || !isReconnectableReadFailure(error)) {
+ if (
+ (!slot.reconnectableRead && !reconciling) ||
+ !isReconnectableReadFailure(error)
+ ) {
throw error;
}
- handler = await this.#waitForHandler(slot, epoch, handler);
+ const replacement = await waitForReplacement(handler);
+ if (!replacement) return unavailable();
+ handler = replacement;
}
}
}
@@ -193,6 +313,7 @@ export class RuntimeHostReconnectingIpcMain {
slot: HandlerSlot,
epoch: string,
previous?: BoundHandler,
+ timeoutMs?: number,
): Promise<BoundHandler> {
try {
this.#assertActive(epoch);
@@ -203,8 +324,29 @@ export class RuntimeHostReconnectingIpcMain {
if (current !== undefined && current !== previous) {
return Promise.resolve(current);
}
+ if (timeoutMs !== undefined && timeoutMs <= 0) {
+ return Promise.reject(new ReconciliationWaitExpiredError());
+ }
return new Promise((resolve, reject) => {
- slot.waiters.add({ epoch, resolve, reject });
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ const waiter: HandlerWaiter = {
+ epoch,
+ resolve: (handler) => {
+ if (timeout !== undefined) clearTimeout(timeout);
+ resolve(handler);
+ },
+ reject: (error) => {
+ if (timeout !== undefined) clearTimeout(timeout);
+ reject(error);
+ },
+ };
+ slot.waiters.add(waiter);
+ if (timeoutMs !== undefined) {
+ timeout = setTimeout(() => {
+ if (!slot.waiters.delete(waiter)) return;
+ waiter.reject(new ReconciliationWaitExpiredError());
+ }, timeoutMs);
+ }
});
}
@@ -238,3 +380,34 @@ export class RuntimeHostReconnectingIpcMain {
}
}
}
+
+function requireReconcileHandler(handler: BoundHandler): ReconcileIpcHandler {
+ if (!handler.reconcile) {
+ throw new Error("Desktop Runtime Host reconciled control handler is unavailable");
+ }
+ return handler.reconcile;
+}
+
+function requireReconciliationUnavailableHandler(
+ handler: BoundHandler,
+): ReconciliationUnavailableIpcHandler {
+ if (!handler.reconciliationUnavailable) {
+ throw new Error("Desktop Runtime Host reconciliation fallback is unavailable");
+ }
+ return handler.reconciliationUnavailable;
+}
+
+function requireReconciledControlStep(
+ value: unknown,
+): { readonly kind: "completed"; readonly value: unknown } | {
+ readonly kind: "reconcile";
+ readonly context: unknown;
+} {
+ if (!value || typeof value !== "object") {
+ throw new Error("Desktop Runtime Host reconciled control returned an invalid step");
+ }
+ const step = value as { kind?: unknown; value?: unknown; context?: unknown };
+ if (step.kind === "completed") return { kind: "completed", value: step.value };
+ if (step.kind === "reconcile") return { kind: "reconcile", context: step.context };
+ throw new Error("Desktop Runtime Host reconciled control returned an invalid step");
+}
diff --git a/apps/desktop/src/main/runtime-host-session-domains-ipc-main.ts b/apps/desktop/src/main/runtime-host-session-domains-ipc-main.ts
index 24b70c1d1..c0fd5aaa3 100644
--- a/apps/desktop/src/main/runtime-host-session-domains-ipc-main.ts
+++ b/apps/desktop/src/main/runtime-host-session-domains-ipc-main.ts
@@ -24,7 +24,7 @@ import type {
AgentGraphClientSnapshotOptions,
AgentGraphOperatorInspection,
} from '@maka/runtime/stream-graph-read-model';
-import type { GoalState } from '@maka/runtime/goal-state';
+import { DEFAULT_MAX_ITERATIONS, type GoalState } from '@maka/runtime/goal-state';
import type { ShellRunPtyDataEvent } from '@maka/runtime/shell-run-contract';
import type {
GoalProjection,
@@ -33,10 +33,16 @@ import type {
import type { AgentGraphEpochDirectory } from '@maka/runtime-host/client';
import type { DesktopRuntimeHostClient } from './runtime-host-client.js';
import type { RuntimeHostSessionObserver } from './runtime-host-session-observer.js';
-import { GOAL_ARM_REQUEST_KEYS } from '../shared/goal-arm.js';
+import {
+ GOAL_ARM_REQUEST_KEYS,
+ type GoalArmOutcome,
+} from '../shared/goal-arm.js';
import { projectHostedDeepResearch } from './deep-research-desktop-projection.js';
import {
+ handleReconciledControl,
handleReconnectableRead,
+ isDispatchedControlConnectionLoss,
+ rethrowReconnectableReadFailure,
type ReconnectableReadIpcMain,
} from './ipc-reconnect-policy.js';
import {
@@ -121,13 +127,53 @@ export function registerRuntimeHostSessionDomainsIpc(
ipcMain.handle('goal:resume', async (_event, sessionId: unknown) => {
await deps.client.controlGoalWithRetry(requiredId(sessionId, 'Session'), 'resume');
});
- ipcMain.handle('goal:arm', async (_event, sessionId: unknown, input: unknown) => {
- const result = await deps.client.armGoal({
- sessionId: requiredId(sessionId, 'Session'),
- ...requireGoalArmBudgets(input),
- });
- return toDesktopGoal(result.goal);
- });
+ handleReconciledControl<GoalArmReconciliationContext, GoalArmOutcome>(
+ ipcMain,
+ 'goal:arm',
+ {
+ dispatch: async (_event, ...args) => {
+ const request = canonicalGoalArmRequest(args[0], args[1]);
+ const previous = await deps.client.queryGoal(request.sessionId);
+ try {
+ const result = await deps.client.armGoal(request);
+ return {
+ kind: 'completed',
+ value: { kind: 'armed', goal: toDesktopGoal(result.goal) },
+ };
+ } catch (error) {
+ if (!isDispatchedControlConnectionLoss(error)) throw error;
+ return {
+ kind: 'reconcile',
+ context: Object.freeze({
+ request,
+ previousGoal:
+ previous.goal === null ? null : Object.freeze({ ...previous.goal }),
+ }),
+ };
+ }
+ },
+ reconcile: async (context) => {
+ try {
+ const result = await deps.client.queryGoal(context.request.sessionId);
+ return {
+ kind: 'reconciled',
+ currentGoal: result.goal === null ? null : toDesktopGoal(result.goal),
+ matchesRequestedState: goalMatchesArmRequest(
+ result.goal,
+ context.request,
+ context.previousGoal,
+ ),
+ };
+ } catch (error) {
+ rethrowReconnectableReadFailure(error);
+ return { kind: 'reconciliation_unavailable' };
+ }
+ },
+ reconciliationUnavailable: async () => ({
+ kind: 'reconciliation_unavailable',
+ }),
+ },
+ );
handleReconnectableRead(ipcMain, 'plan-mode:getState', (_event, sessionId: unknown) =>
deps.client.getPlanState(requiredId(sessionId, 'Session')),
@@ -334,6 +380,46 @@ async function refreshRuntimeResources(
}
}
+interface CanonicalGoalArmRequest {
+ readonly sessionId: string;
+ readonly condition: string;
+ readonly maxIterations: number | null;
+ readonly tokenBudget: number | null;
+}
+
+interface GoalArmReconciliationContext {
+ readonly request: CanonicalGoalArmRequest;
+ readonly previousGoal: GoalProjection | null;
+}
+
+function canonicalGoalArmRequest(
+ sessionId: unknown,
+ input: unknown,
+): CanonicalGoalArmRequest {
+ const budgets = requireGoalArmBudgets(input);
+ return Object.freeze({
+ sessionId: requiredId(sessionId, 'Session'),
+ condition: budgets.condition.trim(),
+ maxIterations: budgets.maxIterations,
+ tokenBudget: budgets.tokenBudget,
+ });
+}
+
+function goalMatchesArmRequest(
+ current: GoalProjection | null,
+ request: CanonicalGoalArmRequest,
+ previous: GoalProjection | null,
+): boolean {
+ return (
+ current !== null &&
+ current.goalId !== previous?.goalId &&
+ current.sessionId === request.sessionId &&
+ current.condition === request.condition &&
+ current.maxIterations === (request.maxIterations ?? DEFAULT_MAX_ITERATIONS) &&
+ current.tokenBudget === request.tokenBudget
+ );
+}
+
/**
* The renderer sends what the user typed; the Host owns every bound. This only
* gets the frame into the shape the protocol decodes — numbers stay numbers,
diff --git a/apps/desktop/src/preload/bridge-contract.d.ts b/apps/desktop/src/preload/bridge-contract.d.ts
index 9efe344c7..b00c00e20 100644
--- a/apps/desktop/src/preload/bridge-contract.d.ts
+++ b/apps/desktop/src/preload/bridge-contract.d.ts
@@ -879,7 +879,7 @@ export interface MakaBridge {
arm(
sessionId: string,
goal: import('../shared/goal-arm').GoalArmRequest,
- ): Promise<import('@maka/runtime/goal-state').GoalState>;
+ ): Promise<import('../shared/goal-arm').GoalArmOutcome>;
/** Clear the active goal, stopping autonomous continuation. */
clear(sessionId: string): Promise<void>;
/** Pause the active goal without spending a model turn. */
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index baba2a4f2..cb8dc4f29 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -199,7 +199,11 @@ import {
requireDesktopTargetScope,
type DesktopTargetScope,
} from '../shared/runtime-host-identity.js';
-import type { GoalArmRequest } from '../shared/goal-arm.js';
+import type { GoalArmOutcome, GoalArmRequest } from '../shared/goal-arm.js';
+import {
+ invokeProjectedSessionRuntimeHost as invokeProjectedSessionRuntimeHostBridge,
+ projectProtocolSessionIds,
+} from './projected-session-runtime-host.js';
import {
projectDesktopAttachmentRefs,
projectDesktopDailyReviewSummary,
@@ -569,14 +573,18 @@ async function invokeProjectedSessionRuntimeHost<T>(
sessionId: string,
...args: unknown[]
): Promise<T> {
- const session = await runtimeHostSessionRef(sessionId);
- const value = await ipcRenderer.invoke(
+ return invokeProjectedSessionRuntimeHostBridge<T>(
+ runtimeHostSessionRef,
+ (targetChannel, scope, rawSessionId, ...targetArgs) => ipcRenderer.invoke(
+ targetChannel,
+ scope,
+ rawSessionId,
+ ...targetArgs,
+ ),
channel,
- session.scope,
- session.sessionId,
+ sessionId,
...args,
- ) as T;
- return projectProtocolSessionIds(session.scope.hostId, value);
+ );
}
async function invokeSessionSummary(
@@ -695,31 +703,6 @@ function projectShellRunUpdate(
};
}
-const SESSION_ID_FIELDS = new Set([
- 'sessionId',
- 'rootSessionId',
- 'childSessionId',
- 'sourceSessionId',
- 'ownerSessionId',
-]);
-
-// Closed client models may be projected structurally. Opaque tool/provider data
-// must use the typed projection above so user content is never rewritten.
-function projectProtocolSessionIds<T>(hostId: string, value: T): T {
- if (Array.isArray(value)) {
- return value.map((entry) => projectProtocolSessionIds(hostId, entry)) as T;
- }
- if (!value || typeof value !== 'object') return value;
- return Object.fromEntries(
- Object.entries(value).map(([key, entry]) => [
- key,
- SESSION_ID_FIELDS.has(key) && typeof entry === 'string'
- ? desktopSessionKey({ hostId, sessionId: entry })
- : projectProtocolSessionIds(hostId, entry),
- ]),
- ) as T;
-}
-
function subscribeRuntimeHostEvent<T extends readonly unknown[]>(
channel: string,
scope: DesktopTargetScope,
@@ -2118,7 +2101,7 @@ const makaBridge = {
get(sessionId: string): Promise<GoalState | null> {
return invokeProjectedSessionRuntimeHost('goal:get', sessionId);
},
- arm(sessionId: string, goal: GoalArmRequest): Promise<GoalState> {
+ arm(sessionId: string, goal: GoalArmRequest): Promise<GoalArmOutcome> {
return invokeProjectedSessionRuntimeHost('goal:arm', sessionId, goal);
},
clear(sessionId: string): Promise<void> {
diff --git a/apps/desktop/src/preload/projected-session-runtime-host.ts b/apps/desktop/src/preload/projected-session-runtime-host.ts
new file mode 100644
index 000000000..4fc079c7f
--- /dev/null
+++ b/apps/desktop/src/preload/projected-session-runtime-host.ts
@@ -0,0 +1,76 @@
+/*
+ * 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 {
+ desktopSessionKey,
+ type DesktopTargetScope,
+} from '../shared/runtime-host-identity.js';
+
+export interface ResolvedRuntimeHostSession {
+ readonly scope: DesktopTargetScope;
+ readonly sessionId: string;
+}
+
+export type RuntimeHostSessionResolver = (
+ sessionId: string,
+) => Promise<ResolvedRuntimeHostSession>;
+
+export type ScopedSessionInvoker = (
+ channel: string,
+ scope: DesktopTargetScope,
+ sessionId: string,
+ ...args: unknown[]
+) => Promise<unknown>;
+
+const SESSION_ID_FIELDS = new Set([
+ 'sessionId',
+ 'rootSessionId',
+ 'childSessionId',
+ 'sourceSessionId',
+ 'ownerSessionId',
+]);
+
+// Closed client models may be projected structurally. Opaque tool/provider data
+// must use a typed projection so user content is never rewritten.
+export function projectProtocolSessionIds<T>(hostId: string, value: T): T {
+ if (Array.isArray(value)) {
+ return value.map((entry) => projectProtocolSessionIds(hostId, entry)) as T;
+ }
+ if (!value || typeof value !== 'object') return value;
+ return Object.fromEntries(
+ Object.entries(value).map(([key, entry]) => [
+ key,
+ SESSION_ID_FIELDS.has(key) && typeof entry === 'string'
+ ? desktopSessionKey({ hostId, sessionId: entry })
+ : projectProtocolSessionIds(hostId, entry),
+ ]),
+ ) as T;
+}
+
+export async function invokeProjectedSessionRuntimeHost<T>(
+ resolveSession: RuntimeHostSessionResolver,
+ invoke: ScopedSessionInvoker,
+ channel: string,
+ sessionId: string,
+ ...args: unknown[]
+): Promise<T> {
+ const session = await resolveSession(sessionId);
+ const value = await invoke(channel, session.scope, session.sessionId, ...args) as T;
+ return projectProtocolSessionIds(session.scope.hostId, value);
+}
diff --git a/apps/desktop/src/renderer/goal-arm-outcome.ts b/apps/desktop/src/renderer/goal-arm-outcome.ts
new file mode 100644
index 000000000..a3d065b78
--- /dev/null
+++ b/apps/desktop/src/renderer/goal-arm-outcome.ts
@@ -0,0 +1,50 @@
+/*
+ * 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 type { GoalState } from '@maka/runtime/goal-state';
+import type { GoalArmOutcome } from '../shared/goal-arm.js';
+
+export type GoalArmReconciliationNotice =
+ | { readonly kind: 'matching_goal'; readonly goal: GoalState }
+ | { readonly kind: 'different_goal'; readonly goal: GoalState }
+ | { readonly kind: 'no_goal' }
+ | { readonly kind: 'unavailable' };
+
+export type GoalArmOutcomeAction =
+ | { readonly action: 'close' }
+ | { readonly action: 'lock'; readonly notice: GoalArmReconciliationNotice };
+
+export function interpretGoalArmOutcome(
+ outcome: GoalArmOutcome,
+): GoalArmOutcomeAction {
+ if (outcome.kind === 'armed') return { action: 'close' };
+ if (outcome.kind === 'reconciliation_unavailable') {
+ return { action: 'lock', notice: { kind: 'unavailable' } };
+ }
+ if (outcome.currentGoal === null) {
+ return { action: 'lock', notice: { kind: 'no_goal' } };
+ }
+ return {
+ action: 'lock',
+ notice: {
+ kind: outcome.matchesRequestedState ? 'matching_goal' : 'different_goal',
+ goal: outcome.currentGoal,
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/goal-dialog.tsx b/apps/desktop/src/renderer/goal-dialog.tsx
index 3d9c6b1b9..7418547b5 100644
--- a/apps/desktop/src/renderer/goal-dialog.tsx
+++ b/apps/desktop/src/renderer/goal-dialog.tsx
@@ -33,7 +33,7 @@
* budget the form is no longer showing, and a field that quietly keeps nothing
* can arm no budget at all where the user asked for a tight one.
*/
-import { useEffect, useState } from 'react';
+import { useLayoutEffect, useRef, useState } from 'react';
import { Button } from '@astryxdesign/core/Button';
import { Dialog, DialogHeader } from '@astryxdesign/core/Dialog';
import { Layout, LayoutContent, LayoutFooter } from '@astryxdesign/core/Layout';
@@ -48,6 +48,10 @@ import {
GOAL_TOKEN_BUDGET_MINIMUM,
} from '@maka/core/goal';
import { getShellCopy, localizedShellErrorMessage } from './locales/shell-copy.js';
+import {
+ interpretGoalArmOutcome,
+ type GoalArmReconciliationNotice,
+} from './goal-arm-outcome.js';
type BudgetReading =
| { readonly kind: 'empty' }
@@ -84,42 +88,77 @@ export function GoalDialog(props: {
const [tokenBudgetText, setTokenBudgetText] = useState('');
const [arming, setArming] = useState(false);
const [error, setError] = useState<string>();
+ const [reconciliation, setReconciliation] =
+ useState<GoalArmReconciliationNotice>();
+ const armGenerationRef = useRef(0);
// Each opening starts from empty: the previous Session's condition is not a
// useful default for this one, and a stale error would outlive its cause.
- useEffect(() => {
+ useLayoutEffect(() => {
+ armGenerationRef.current += 1;
if (props.sessionId === undefined) return;
setCondition('');
setMaxIterationsText('');
setTokenBudgetText('');
setError(undefined);
setArming(false);
+ setReconciliation(undefined);
}, [props.sessionId]);
const sessionId = props.sessionId;
const maxIterations = readGoalBudget(maxIterationsText, 1, GOAL_MAX_ITERATIONS_LIMIT);
const tokenBudget = readGoalBudget(tokenBudgetText, GOAL_TOKEN_BUDGET_MINIMUM);
+ const locked = reconciliation !== undefined;
const canSubmit =
condition.trim().length > 0 &&
maxIterations.kind !== 'invalid' &&
tokenBudget.kind !== 'invalid' &&
- !arming;
+ !arming &&
+ !locked;
+
+ const reconciliationMessage = (() => {
+ if (!reconciliation) return undefined;
+ switch (reconciliation.kind) {
+ case 'matching_goal':
+ return copy.reconciledMatching(
+ reconciliation.goal.condition,
+ copy.statusLabels[reconciliation.goal.status],
+ );
+ case 'different_goal':
+ return copy.reconciledDifferent(
+ reconciliation.goal.condition,
+ copy.statusLabels[reconciliation.goal.status],
+ );
+ case 'no_goal':
+ return copy.reconciledNoGoal;
+ case 'unavailable':
+ return copy.reconciliationUnavailable;
+ }
+ })();
async function arm(): Promise<void> {
if (!sessionId || !canSubmit) return;
+ const armGeneration = ++armGenerationRef.current;
setArming(true);
setError(undefined);
try {
- await window.maka.goal.arm(sessionId, {
+ const outcome = await window.maka.goal.arm(sessionId, {
condition: condition.trim(),
maxIterations: maxIterations.kind === 'value' ? maxIterations.value : null,
tokenBudget: tokenBudget.kind === 'value' ? tokenBudget.value : null,
});
- props.onClose();
+ if (armGenerationRef.current !== armGeneration) return;
+ const action = interpretGoalArmOutcome(outcome);
+ if (action.action === 'close') {
+ props.onClose();
+ } else {
+ setReconciliation(action.notice);
+ }
} catch (cause) {
+ if (armGenerationRef.current !== armGeneration) return;
setError(localizedShellErrorMessage(cause, copy.failedFallback, locale));
} finally {
- setArming(false);
+ if (armGenerationRef.current === armGeneration) setArming(false);
}
}
@@ -141,6 +180,9 @@ export function GoalDialog(props: {
<LayoutContent padding={4}>
<VStack gap={4}>
<Text type="body" color="secondary">{copy.description}</Text>
+ {reconciliationMessage ? (
+ <Text type="body" color="secondary">{reconciliationMessage}</Text>
+ ) : null}
<TextArea
label={copy.conditionLabel}
description={copy.conditionDescription}
@@ -150,7 +192,7 @@ export function GoalDialog(props: {
rows={3}
maxLength={GOAL_CONDITION_TEXT_LIMIT.codeUnits}
isRequired
- isDisabled={arming}
+ isDisabled={arming || locked}
hasAutoFocus
{...(error ? { status: { type: 'error' as const, message: error } } : {})}
/>
@@ -161,7 +203,7 @@ export function GoalDialog(props: {
value={maxIterationsText}
onChange={setMaxIterationsText}
isOptional
- isDisabled={arming}
+ isDisabled={arming || locked}
{...(maxIterations.kind === 'invalid'
? { status: { type: 'error' as const, message: copy.maxIterationsInvalid(GOAL_MAX_ITERATIONS_LIMIT) } }
: {})}
@@ -172,7 +214,7 @@ export function GoalDialog(props: {
value={tokenBudgetText}
onChange={setTokenBudgetText}
isOptional
- isDisabled={arming}
+ isDisabled={arming || locked}
{...(tokenBudget.kind === 'invalid'
? { status: { type: 'error' as const, message: copy.tokenBudgetInvalid(GOAL_TOKEN_BUDGET_MINIMUM) } }
: {})}
@@ -186,7 +228,7 @@ export function GoalDialog(props: {
<HStack gap={2} hAlign="end">
<Button
variant="ghost"
- label={copy.cancel}
+ label={locked ? copy.close : copy.cancel}
isDisabled={arming}
onClick={props.onClose}
/>
diff --git a/apps/desktop/src/renderer/locales/shell-copy.ts b/apps/desktop/src/renderer/locales/shell-copy.ts
index 1d8857e59..16a1c8905 100644
--- a/apps/desktop/src/renderer/locales/shell-copy.ts
+++ b/apps/desktop/src/renderer/locales/shell-copy.ts
@@ -28,6 +28,7 @@ import { type ChatDefaultPermissionMode, type SettingsSection } from '@maka/core
import { type SlashCommandIdForSurface } from '@maka/core/slash-command-catalog';
import { type ThinkingLevel } from '@maka/core/model-thinking';
+import { type GoalStatus } from '@maka/core/goal';
export const STATIC_COMMAND_IDS = [
'action:new-chat',
@@ -360,8 +361,14 @@ type ShellCopy = {
tokenBudgetDescription: string;
tokenBudgetInvalid(min: number): string;
cancel: string;
+ close: string;
submit: string;
failedFallback: string;
+ statusLabels: Record<GoalStatus, string>;
+ reconciledMatching(condition: string, status: string): string;
+ reconciledDifferent(condition: string, status: string): string;
+ reconciledNoGoal: string;
+ reconciliationUnavailable: string;
};
errorBoundary: {
copyPending: string;
@@ -1015,8 +1022,26 @@ const SHELL_COPY_BY_LOCALE = {
tokenBudgetDescription: '留空表示不设 token 上限。',
tokenBudgetInvalid: (min) => `请填不小于 ${min} 的整数,或留空。`,
cancel: '取消',
+ close: '关闭',
submit: '开始',
failedFallback: '无法设定 Goal,请稍后重试。',
+ statusLabels: {
+ active: '进行中',
+ waiting: '等待中',
+ paused: '已暂停',
+ achieved: '已达成',
+ impossible: '不可行',
+ cleared: '已清除',
+ stalled: '已停滞',
+ budget_limited: '已达到 Token 预算',
+ max_iterations: '已达到最多轮数',
+ },
+ reconciledMatching: (condition, status) =>
+ `已重新读取当前 Goal:“${condition}”(${status})。它符合你的请求,但无法确认刚才的操作是否提交。`,
+ reconciledDifferent: (condition, status) =>
+ `已重新读取当前 Goal:“${condition}”(${status})。它与本次请求不同。`,
+ reconciledNoGoal: '已重新读取当前状态:当前未读到 Goal。',
+ reconciliationUnavailable: '连接中断后暂时无法确认当前 Goal 状态。请关闭后重新打开再检查;此窗口不会重复提交。',
},
errorBoundary: {
copyPending: '复制中…',
@@ -1517,8 +1542,26 @@ const SHELL_COPY_BY_LOCALE = {
tokenBudgetDescription: 'Leave empty for no token ceiling.',
tokenBudgetInvalid: (min) => `Enter a whole number of at least ${min}, or leave it empty.`,
cancel: 'Cancel',
+ close: 'Close',
submit: 'Start',
failedFallback: 'The goal could not be set. Try again.',
+ statusLabels: {
+ active: 'Active',
+ waiting: 'Waiting',
+ paused: 'Paused',
+ achieved: 'Achieved',
+ impossible: 'Impossible',
+ cleared: 'Cleared',
+ stalled: 'Stalled',
+ budget_limited: 'Token budget reached',
+ max_iterations: 'Maximum turns reached',
+ },
+ reconciledMatching: (condition, status) =>
+ `Current Goal after reconnect: “${condition}” (${status}). It matches your request, but this does not prove that the interrupted operation committed.`,
+ reconciledDifferent: (condition, status) =>
+ `Current Goal after reconnect: “${condition}” (${status}). It differs from this request.`,
+ reconciledNoGoal: 'Current state after reconnect: no Goal was found.',
+ reconciliationUnavailable: 'The connection was interrupted and the current Goal cannot be confirmed yet. Close and reopen to check again; this dialog will not submit twice.',
},
errorBoundary: {
copyPending: 'Copying…',
diff --git a/apps/desktop/src/shared/goal-arm.ts b/apps/desktop/src/shared/goal-arm.ts
index b50548d4c..cf5d5d24f 100644
--- a/apps/desktop/src/shared/goal-arm.ts
+++ b/apps/desktop/src/shared/goal-arm.ts
@@ -17,6 +17,8 @@
* under the License.
*/
+import type { GoalState } from '@maka/runtime/goal-state';
+
/**
* What the renderer sends to arm a Goal.
*
@@ -31,6 +33,15 @@ export interface GoalArmRequest {
readonly tokenBudget?: number | null;
}
+export type GoalArmOutcome =
+ | { readonly kind: 'armed'; readonly goal: GoalState }
+ | {
+ readonly kind: 'reconciled';
+ readonly currentGoal: GoalState | null;
+ readonly matchesRequestedState: boolean;
+ }
+ | { readonly kind: 'reconciliation_unavailable' };
+
export const GOAL_ARM_REQUEST_KEYS: readonly (keyof GoalArmRequest)[] = Object.freeze([
'condition',
'maxIterations',
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org