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/23 20:42:07 UTC
(maka) branch feat/runtime-host-rust updated (43c75bf0d5 -> f9d8cb5f6d)
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 43c75bf0d5 merge: integrate native TUI Session recap with Skills inputs
new 489166b633 test(host): use public Skills Remote after retiring the TS CLI
new f9d8cb5f6d feat(host): connect native Session bundles to Desktop
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:
Cargo.lock | 1 +
.../__tests__/import-tasks-settings-page.test.ts | 1 +
.../runtime-host-session-bundle-ipc-main.test.ts | 49 +++--
.../__tests__/session-bundle-export-tree.test.ts | 9 +-
apps/desktop/src/main/runtime-host-client.ts | 13 +-
.../src/main/runtime-host-desktop-candidate.ts | 14 +-
.../main/runtime-host-session-bundle-ipc-main.ts | 45 +++--
apps/desktop/src/preload/bridge-contract.d.ts | 8 +-
apps/desktop/src/preload/preload.ts | 19 +-
.../features/session-bundle/export-tree.tsx | 47 +----
.../src/renderer/features/session-bundle/ports.ts | 17 +-
.../session-bundle/session-bundle-tasks.tsx | 32 +--
.../locales/external-session-import-copy.ts | 4 -
.../desktop/create-session-bundle-services.ts | 1 +
apps/desktop/src/renderer/reference-shell.css | 5 -
.../stories/settings/settings-pages.stories.tsx | 43 ++++-
crates/client/src/notification.rs | 6 +-
crates/event-log/src/bundle/export.rs | 9 +-
crates/event-log/src/bundle/stage.rs | 14 +-
crates/protocol/src/authority.rs | 1 +
crates/protocol/src/lib.rs | 2 +-
crates/protocol/src/operation.rs | 1 +
crates/protocol/src/session.rs | 1 +
crates/protocol/src/session/bundle.rs | 151 +++++++++++++++
crates/protocol/src/session/operations.rs | 23 ++-
crates/runtime-host/Cargo.toml | 1 +
crates/runtime-host/src/server/catalog_feed.rs | 21 +-
crates/runtime-host/src/server/sessions.rs | 22 +++
crates/runtime-host/src/server/sessions/bundle.rs | 186 ++++++++++++++++++
.../src/server/sessions/bundle/binding.rs | 115 +++++++++++
.../src/server/sessions/bundle/file.rs | 172 +++++++++++++++++
crates/runtime-host/tests/integration/main.rs | 1 +
.../tests/integration/session_bundle.rs | 214 +++++++++++++++++++++
.../tests/integration/session_bundle/fixtures.rs | 157 +++++++++++++++
.../tests/integration/session_bundle/host.rs | 80 ++++++++
crates/tui/src/lib.rs | 9 +-
docs/rust-parity.md | 2 +-
docs/rust-parity.zh-CN.md | 2 +-
.../src/__tests__/authenticated-websocket.test.ts | 8 +-
.../runtime-host/src/__tests__/host-kernel.test.ts | 4 +-
.../session-catalog-two-client-uds.test.ts | 4 +-
packages/runtime-host/src/protocol/index.ts | 4 +-
packages/runtime-host/src/protocol/operations.ts | 1 +
.../runtime-host/src/protocol/session-bundle.ts | 66 +++++--
.../src/protocol/session-catalog-change.ts | 20 +-
.../src/server/session-bundle-coordinator.ts | 4 +
tests/fixtures/client-message-submit.mjs | 24 +--
47 files changed, 1416 insertions(+), 217 deletions(-)
create mode 100644 crates/protocol/src/session/bundle.rs
create mode 100644 crates/runtime-host/src/server/sessions/bundle.rs
create mode 100644 crates/runtime-host/src/server/sessions/bundle/binding.rs
create mode 100644 crates/runtime-host/src/server/sessions/bundle/file.rs
create mode 100644 crates/runtime-host/tests/integration/session_bundle.rs
create mode 100644 crates/runtime-host/tests/integration/session_bundle/fixtures.rs
create mode 100644 crates/runtime-host/tests/integration/session_bundle/host.rs
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 01/02: test(host): use public Skills Remote after retiring the TS CLI
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 489166b633f403b435fa9e1aa154ae571bb39562
Author: Wang <m4...@gmail.com>
AuthorDate: Thu Sep 24 04:25:15 2026 +0800
test(host): use public Skills Remote after retiring the TS CLI
Generated-by: OpenAI Codex
---
tests/fixtures/client-message-submit.mjs | 24 ++++++------------------
1 file changed, 6 insertions(+), 18 deletions(-)
diff --git a/tests/fixtures/client-message-submit.mjs b/tests/fixtures/client-message-submit.mjs
index 3dc5e062f7..e27bd7c924 100644
--- a/tests/fixtures/client-message-submit.mjs
+++ b/tests/fixtures/client-message-submit.mjs
@@ -31,7 +31,6 @@ import {
} from './client-message-fixture.mjs';
import { watchSession } from './client-subscription.mjs';
import { pluginRemote } from './client-plugin-remote.mjs';
-import { readRuntimeHostSkills } from '../../packages/cli/src/runtime-host-skills.ts';
export async function verifyMessageSubmit(connection, workspace, reopened, openClient) {
const skills = await pluginRemote(connection, 'maka.skills');
@@ -90,7 +89,7 @@ export async function verifyMessageSubmit(connection, workspace, reopened, openC
return;
}
- await verifyInvocableCatalog(connection, request, skills, workspace);
+ await verifyInvocableCatalog(request, skills, workspace);
const sourcePage = (view) => catalog({ view });
const bundled = await sourcePage('bundled');
assert.equal(bundled.items[0].id, 'computer-use');
@@ -632,7 +631,7 @@ export async function verifyMessageSubmit(connection, workspace, reopened, openC
}
}
-async function verifyInvocableCatalog(connection, request, skills, workspace) {
+async function verifyInvocableCatalog(request, skills, workspace) {
const target = {
path: workspace,
collaborationMode: 'agent',
@@ -640,11 +639,9 @@ async function verifyInvocableCatalog(connection, request, skills, workspace) {
};
const query = (page) =>
skills.method('path-request')({ ...target, request: { kind: 'invocable', page } });
- const baseline = await readRuntimeHostSkills(
- connection,
- { kind: 'host_path', path: workspace },
- 'workspace-write',
- );
+ const baseline = await query(null);
+ assert.equal(baseline.kind, 'page');
+ assert.equal(baseline.nextCursor, null);
const directories = Array.from({ length: 129 }, (_, n) =>
join(workspace, '.maka/skills', 'catalog-' + String(n).padStart(3, '0')),
);
@@ -666,17 +663,8 @@ async function verifyInvocableCatalog(connection, request, skills, workspace) {
});
assert.equal(last.nextCursor, null);
const all = [...first.items, ...last.items];
- assert.equal(all.length, baseline.length + directories.length);
+ assert.equal(all.length, baseline.items.length + directories.length);
assert.equal(new Set(all.map((item) => item.ref)).size, all.length);
- assert.deepEqual(
- await readRuntimeHostSkills(
- connection,
- { kind: 'host_path', path: workspace },
- 'workspace-write',
- ),
- all,
- 'the real CLI picker uses the same public Remote pages',
- );
await assert.rejects(
query({ revision: first.revision, cursor: 'invalid' }),
(error) => error.code === 'invalid_request',
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 02/02: feat(host): connect native Session bundles to Desktop
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 f9d8cb5f6d9aa8cb392f6b10f397751b1e680951
Author: Wang <m4...@gmail.com>
AuthorDate: Thu Sep 24 04:28:44 2026 +0800
feat(host): connect native Session bundles to Desktop
Validate and import native history under current destination authority, with atomic replay receipts and complete Host inventory confirmation.
Generated-by: OpenAI Codex
---
Cargo.lock | 1 +
.../__tests__/import-tasks-settings-page.test.ts | 1 +
.../runtime-host-session-bundle-ipc-main.test.ts | 49 +++--
.../__tests__/session-bundle-export-tree.test.ts | 9 +-
apps/desktop/src/main/runtime-host-client.ts | 13 +-
.../src/main/runtime-host-desktop-candidate.ts | 14 +-
.../main/runtime-host-session-bundle-ipc-main.ts | 45 +++--
apps/desktop/src/preload/bridge-contract.d.ts | 8 +-
apps/desktop/src/preload/preload.ts | 19 +-
.../features/session-bundle/export-tree.tsx | 47 +----
.../src/renderer/features/session-bundle/ports.ts | 17 +-
.../session-bundle/session-bundle-tasks.tsx | 32 +--
.../locales/external-session-import-copy.ts | 4 -
.../desktop/create-session-bundle-services.ts | 1 +
apps/desktop/src/renderer/reference-shell.css | 5 -
.../stories/settings/settings-pages.stories.tsx | 43 ++++-
crates/client/src/notification.rs | 6 +-
crates/event-log/src/bundle/export.rs | 9 +-
crates/event-log/src/bundle/stage.rs | 14 +-
crates/protocol/src/authority.rs | 1 +
crates/protocol/src/lib.rs | 2 +-
crates/protocol/src/operation.rs | 1 +
crates/protocol/src/session.rs | 1 +
crates/protocol/src/session/bundle.rs | 151 +++++++++++++++
crates/protocol/src/session/operations.rs | 23 ++-
crates/runtime-host/Cargo.toml | 1 +
crates/runtime-host/src/server/catalog_feed.rs | 21 +-
crates/runtime-host/src/server/sessions.rs | 22 +++
crates/runtime-host/src/server/sessions/bundle.rs | 186 ++++++++++++++++++
.../src/server/sessions/bundle/binding.rs | 115 +++++++++++
.../src/server/sessions/bundle/file.rs | 172 +++++++++++++++++
crates/runtime-host/tests/integration/main.rs | 1 +
.../tests/integration/session_bundle.rs | 214 +++++++++++++++++++++
.../tests/integration/session_bundle/fixtures.rs | 157 +++++++++++++++
.../tests/integration/session_bundle/host.rs | 80 ++++++++
crates/tui/src/lib.rs | 9 +-
docs/rust-parity.md | 2 +-
docs/rust-parity.zh-CN.md | 2 +-
.../src/__tests__/authenticated-websocket.test.ts | 8 +-
.../runtime-host/src/__tests__/host-kernel.test.ts | 4 +-
.../session-catalog-two-client-uds.test.ts | 4 +-
packages/runtime-host/src/protocol/index.ts | 4 +-
packages/runtime-host/src/protocol/operations.ts | 1 +
.../runtime-host/src/protocol/session-bundle.ts | 66 +++++--
.../src/protocol/session-catalog-change.ts | 20 +-
.../src/server/session-bundle-coordinator.ts | 4 +
46 files changed, 1410 insertions(+), 199 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index cde2a5c88f..4a8f938e4d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5099,6 +5099,7 @@ dependencies = [
name = "maka-runtime-host"
version = "0.2.0"
dependencies = [
+ "async-compression",
"base64 0.22.1",
"cap-fs-ext",
"cap-std",
diff --git a/apps/desktop/src/main/__tests__/import-tasks-settings-page.test.ts b/apps/desktop/src/main/__tests__/import-tasks-settings-page.test.ts
index 06e161a8cc..77e66913dc 100644
--- a/apps/desktop/src/main/__tests__/import-tasks-settings-page.test.ts
+++ b/apps/desktop/src/main/__tests__/import-tasks-settings-page.test.ts
@@ -926,6 +926,7 @@ async function renderPage(options: {
// not, which made every case fail on the provider rather than the case.
const withServices = createElement(SessionBundleServicesProvider, {
services: {
+ previewBundle: async () => ({ ok: true, sessionCount: 1, subtreeDigest: '0'.repeat(64) }) as const,
exportBundle: async () => ({ ok: false, reason: 'canceled' }) as const,
importBundle: async () => ({ ok: false, reason: 'canceled' }) as const,
},
diff --git a/apps/desktop/src/main/__tests__/runtime-host-session-bundle-ipc-main.test.ts b/apps/desktop/src/main/__tests__/runtime-host-session-bundle-ipc-main.test.ts
index d8a5297187..b1aca6728f 100644
--- a/apps/desktop/src/main/__tests__/runtime-host-session-bundle-ipc-main.test.ts
+++ b/apps/desktop/src/main/__tests__/runtime-host-session-bundle-ipc-main.test.ts
@@ -18,7 +18,6 @@
*/
import assert from 'node:assert/strict';
-import { createHash } from 'node:crypto';
import test from 'node:test';
import type { IpcMain } from 'electron';
import { RuntimeHostOperationError } from '@maka/runtime-host/client';
@@ -48,7 +47,7 @@ test('writes to the picked destination and reports what travelled', async () =>
const result = await ipc.invoke('session-bundle:export', 'session-1', 'Hello');
- assert.deepEqual(asked, [{ sessionId: 'session-1', destination: '/picked/Hello.maka-session' }]);
+ assert.deepEqual(asked, [{ sessionId: 'session-1', destination: '/picked/Hello.maka-session', expectedSubtreeDigest: undefined }]);
// The count is the subtree, not one: a bundle rooted at a Session carries the
// subagent conversations under it, and the page says so.
assert.deepEqual(result, {
@@ -80,13 +79,17 @@ test('closing the save dialog asks the Host for nothing', async () => {
assert.equal(called, false, 'a cancelled dialog is a decision, not a request');
});
-test('publishes each imported Session so the shell reads the catalog again', async () => {
+test('binds imported sessions to the selected workspace and invalidates the catalog once', async () => {
const events: Array<{ reason: string; sessionId?: string }> = [];
+ const calls: unknown[] = [];
const ipc = ipcHarness();
registerRuntimeHostSessionBundleIpc(
deps({
client: {
- importSessionBundle: async () => ({ sessionCount: 2, artifactFiles: 3 }),
+ importSessionBundle: async (input) => {
+ calls.push(input);
+ return { sessionCount: 2, artifactFiles: 3 };
+ },
},
dialog: { open: { canceled: false, filePaths: ['/picked/bundle.maka-session'] } },
onSessionsChanged: (reason, sessionId) => events.push({ reason, ...(sessionId ? { sessionId } : {}) }),
@@ -97,6 +100,10 @@ test('publishes each imported Session so the shell reads the catalog again', asy
const result = await ipc.invoke('session-bundle:import');
assert.deepEqual(result, { ok: true, sessionCount: 2 });
+ assert.deepEqual(calls, [{
+ source: '/picked/bundle.maka-session',
+ workspace: { kind: 'host_path', path: '/selected/workspace' },
+ }]);
// The Host republishes its own catalog; the desktop keeps a separate list and
// only re-reads when told, so an imported task is invisible without this. No
// id: a list that grows with the subtree can outgrow a frame after the
@@ -157,18 +164,22 @@ function deps(input: {
dialog?: {
save?: { canceled: boolean; filePath?: string };
open?: { canceled: boolean; filePaths: string[] };
+ workspace?: { canceled: boolean; filePaths: string[] };
};
onSessionsChanged?: (reason: string, sessionId?: string) => void;
}): RuntimeHostSessionBundleIpcDeps {
return {
client: {
+ previewSessionBundle: async () => ({ sessionCount: 1, subtreeDigest: '0'.repeat(64) }),
exportSessionBundle: async () => ({ sessionCount: 0, compressedBytes: 0 }),
importSessionBundle: async () => ({ sessionCount: 0, artifactFiles: 0 }),
...input.client,
},
mainWindowController: {
showSaveDialog: async () => input.dialog?.save ?? { canceled: true },
- showOpenDialog: async () => input.dialog?.open ?? { canceled: true, filePaths: [] },
+ showOpenDialog: async (options) => options.properties?.includes('openDirectory')
+ ? input.dialog?.workspace ?? { canceled: false, filePaths: ['/selected/workspace'] }
+ : input.dialog?.open ?? { canceled: true, filePaths: [] },
},
emitSessionsChanged: (reason, sessionId) => input.onSessionsChanged?.(reason, sessionId),
};
@@ -199,30 +210,34 @@ test('proposes a filename a task name cannot steer', () => {
assert.ok(bundleFileName('x'.repeat(500)).length <= 80, 'bounded for the filesystem');
});
-test('the digest it sends is over the ids the Host knows', async () => {
+test('passes the Host preview unchanged through export and stops when workspace selection is canceled', async () => {
let sent: unknown;
const ipc = ipcHarness();
registerRuntimeHostSessionBundleIpc(
deps({
client: {
+ previewSessionBundle: async (id) => {
+ assert.equal(id, 'root');
+ return { sessionCount: 3, subtreeDigest: 'a'.repeat(64) };
+ },
+ importSessionBundle: async () => { throw new Error('canceled import must not reach Host'); },
exportSessionBundle: async (input) => {
sent = input.expectedSubtreeDigest;
return { sessionCount: 2, compressedBytes: 1 };
},
},
- dialog: { save: { canceled: false, filePath: '/picked/Hello.maka-session' } },
+ dialog: {
+ save: { canceled: false, filePath: '/picked/Hello.maka-session' },
+ open: { canceled: false, filePaths: ['/picked/source.maka-session'] },
+ workspace: { canceled: true, filePaths: [] },
+ },
}),
ipc,
);
- await ipc.invoke('session-bundle:export', 'root', 'Hello', ['child', 'root']);
-
- // Sorted and newline-joined, so the order a walk happened to produce cannot
- // change it, and over the Host's own ids -- a digest taken further upstream
- // would be over host-scoped ids and could never match what the Host fenced.
- assert.equal(
- sent,
- createHash('sha256').update('child\nroot').digest('hex'),
- 'both sides must hash the same thing',
- );
+ const preview = await ipc.invoke('session-bundle:preview', 'root');
+ assert.deepEqual(preview, { ok: true, sessionCount: 3, subtreeDigest: 'a'.repeat(64) });
+ await ipc.invoke('session-bundle:export', 'root', 'Hello', 'a'.repeat(64));
+ assert.equal(sent, 'a'.repeat(64));
+ assert.deepEqual(await ipc.invoke('session-bundle:import'), { ok: false, reason: 'canceled' });
});
diff --git a/apps/desktop/src/main/__tests__/session-bundle-export-tree.test.ts b/apps/desktop/src/main/__tests__/session-bundle-export-tree.test.ts
index 46b274d988..7ba3d7fa7b 100644
--- a/apps/desktop/src/main/__tests__/session-bundle-export-tree.test.ts
+++ b/apps/desktop/src/main/__tests__/session-bundle-export-tree.test.ts
@@ -39,7 +39,7 @@ afterEach(() => {
});
describe('session bundle export tree', () => {
- it('nests a subagent subtree and counts the whole thing', async () => {
+ it('nests known descendants without claiming the export inventory', async () => {
const rendered = await render([
task('root', 'Refactor compaction'),
subagentTask('child-a', 'Find the call sites', 'root', 'Explore'),
@@ -48,11 +48,7 @@ describe('session bundle export tree', () => {
task('unrelated', 'Say hello'),
]);
- // Three descendants, not the two children: a subagent spawns its own, and a
- // bundle rooted here carries all of them.
- assert.match(rendered.container.textContent, /Carries 3 subagent conversations/);
- // The child that has one of its own says so too.
- assert.match(rendered.container.textContent, /Carries 1 subagent conversation/);
+ assert.doesNotMatch(rendered.container.textContent, /Carries \d/);
// Nesting is structural, not an indent class: a child lives inside the list
// that belongs to its parent, which is what draws one continuous rule.
assert.equal(
@@ -77,7 +73,6 @@ describe('session bundle export tree', () => {
{ ...task('child', 'A child'), subagent: { parentSessionId: 'root', agentName: 'Explore' } },
]);
assert.equal(rendered.container.querySelectorAll('.maka-export-subtree').length, 1);
- assert.match(rendered.container.textContent, /Carries 1 subagent conversation/);
await rendered.dispose();
});
diff --git a/apps/desktop/src/main/runtime-host-client.ts b/apps/desktop/src/main/runtime-host-client.ts
index f4fc8da5d0..a9e2731177 100644
--- a/apps/desktop/src/main/runtime-host-client.ts
+++ b/apps/desktop/src/main/runtime-host-client.ts
@@ -148,6 +148,8 @@ const MAX_OPTIMISTIC_ATTEMPTS = 3;
const MAX_SESSION_REVISION_ATTEMPTS = 8;
const MAX_PRICING_SNAPSHOT_ATTEMPTS = 3;
const RUNTIME_HOST_RETIREMENT_TIMEOUT_MS = 15_000;
+// A timed-out waiter does not cancel or retry accepted bundle publication.
+const SESSION_BUNDLE_TRANSFER_TIMEOUT_MS = 15 * 60_000;
export type DesktopSessionConfigurationPatch = SessionConfigurationPatch;
@@ -944,18 +946,25 @@ export class DesktopRuntimeHostClient {
return result;
}
+ previewSessionBundle(sessionId: string): Promise<{
+ readonly sessionCount: number; readonly subtreeDigest: string;
+ }> {
+ return this.request("session-bundle.preview", { sessionId }, 30_000);
+ }
+
exportSessionBundle(input: {
readonly sessionId: string;
readonly destination: string;
readonly expectedSubtreeDigest?: string;
}): Promise<{ readonly sessionCount: number; readonly compressedBytes: number }> {
- return this.request("session-bundle.export", input);
+ return this.request("session-bundle.export", input, SESSION_BUNDLE_TRANSFER_TIMEOUT_MS);
}
importSessionBundle(input: {
readonly source: string;
+ readonly workspace: WorkspaceTarget;
}): Promise<{ readonly sessionCount: number; readonly artifactFiles: number }> {
- return this.request("session-bundle.import", input);
+ return this.request("session-bundle.import", input, SESSION_BUNDLE_TRANSFER_TIMEOUT_MS);
}
updateSessionMetadata(
diff --git a/apps/desktop/src/main/runtime-host-desktop-candidate.ts b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
index d17a24cadb..56c20d2a52 100644
--- a/apps/desktop/src/main/runtime-host-desktop-candidate.ts
+++ b/apps/desktop/src/main/runtime-host-desktop-candidate.ts
@@ -915,14 +915,12 @@ export async function createDesktopRuntimeHostCandidate(
},
ipc,
);
- registerRuntimeHostSessionBundleIpc(
- {
- client,
- mainWindowController: deps.mainWindowController,
- emitSessionsChanged,
- },
- ipc,
- );
+ if (target.kind === 'local') {
+ registerRuntimeHostSessionBundleIpc(
+ { client, mainWindowController: deps.mainWindowController, emitSessionsChanged },
+ ipc,
+ );
+ }
}
const stopSession = sessionCopyCleanup
? registerRuntimeHostSessionExecutionIpc(
diff --git a/apps/desktop/src/main/runtime-host-session-bundle-ipc-main.ts b/apps/desktop/src/main/runtime-host-session-bundle-ipc-main.ts
index 0dd32d8922..53a44be552 100644
--- a/apps/desktop/src/main/runtime-host-session-bundle-ipc-main.ts
+++ b/apps/desktop/src/main/runtime-host-session-bundle-ipc-main.ts
@@ -17,15 +17,16 @@
* under the License.
*/
-import { createHash } from 'node:crypto';
import type { IpcMain } from 'electron';
import type { SessionChangedReason } from '@maka/core/session';
import { RuntimeHostOperationError } from '@maka/runtime-host/client';
+import type { WorkspaceTarget } from '@maka/runtime-host/protocol';
import type {
SessionBundleExportIpcResult,
SessionBundleFailure,
SessionBundleFailureReason,
SessionBundleImportIpcResult,
+ SessionBundlePreviewIpcResult,
} from '../preload/bridge-contract.js';
/**
@@ -38,6 +39,9 @@ import type {
* require stopping the Host the user is looking at.
*/
type SessionBundleClient = {
+ previewSessionBundle(sessionId: string): Promise<{
+ readonly sessionCount: number; readonly subtreeDigest: string;
+ }>;
exportSessionBundle(input: {
readonly sessionId: string;
readonly destination: string;
@@ -45,6 +49,7 @@ type SessionBundleClient = {
}): Promise<{ readonly sessionCount: number; readonly compressedBytes: number }>;
importSessionBundle(input: {
readonly source: string;
+ readonly workspace: WorkspaceTarget;
}): Promise<{ readonly sessionCount: number; readonly artifactFiles: number }>;
};
@@ -75,11 +80,18 @@ export function registerRuntimeHostSessionBundleIpc(
deps: RuntimeHostSessionBundleIpcDeps,
ipcMain: { handle(channel: string, listener: Parameters<IpcMain['handle']>[1]): void },
): void {
+ ipcMain.handle('session-bundle:preview', async (_event, sessionId: string) => {
+ try {
+ return { ok: true, ...await deps.client.previewSessionBundle(sessionId) } satisfies SessionBundlePreviewIpcResult;
+ } catch (error) {
+ return failure(error) satisfies SessionBundlePreviewIpcResult;
+ }
+ });
ipcMain.handle('session-bundle:export', async (_event, ...args: unknown[]) => {
- const [sessionId, suggestedName, confirmedSubtree] = args as [
+ const [sessionId, suggestedName, expectedSubtreeDigest] = args as [
+ string,
string,
string,
- readonly string[] | undefined,
];
const picked = await deps.mainWindowController.showSaveDialog({
defaultPath: `${bundleFileName(suggestedName)}.${BUNDLE_EXTENSION}`,
@@ -92,12 +104,7 @@ export function registerRuntimeHostSessionBundleIpc(
const result = await deps.client.exportSessionBundle({
sessionId,
destination: picked.filePath,
- // The digest is computed here rather than sent from the renderer: this
- // is the first place the ids are the Host's own, and it is the last
- // place before the protocol frame, which only carries the 64 characters.
- ...(confirmedSubtree
- ? { expectedSubtreeDigest: subtreeDigest(confirmedSubtree) }
- : {}),
+ expectedSubtreeDigest,
});
return {
ok: true,
@@ -119,7 +126,18 @@ export function registerRuntimeHostSessionBundleIpc(
return { ok: false, reason: 'canceled' } satisfies SessionBundleImportIpcResult;
}
try {
- const result = await deps.client.importSessionBundle({ source });
+ const destination = await deps.mainWindowController.showOpenDialog({
+ title: 'Workspace for imported sessions',
+ properties: ['openDirectory'],
+ });
+ const path = destination.filePaths[0];
+ if (destination.canceled || !path) {
+ return { ok: false, reason: 'canceled' } satisfies SessionBundleImportIpcResult;
+ }
+ const result = await deps.client.importSessionBundle({
+ source,
+ workspace: { kind: 'host_path', path },
+ });
// The Host republishes the catalog, but the desktop shell keeps its own
// list and only reads again when told.
// No ids: the result is a count, because a list that grows with the
@@ -151,13 +169,6 @@ function bundleFileName(name: unknown): string {
return proposed.length > 0 ? proposed : 'maka-session';
}
-/** Must match the Host: sorted, newline-joined, hex `sha256`. */
-function subtreeDigest(sessionIds: readonly string[]): string {
- return createHash('sha256')
- .update([...sessionIds].sort().join('\n'))
- .digest('hex');
-}
-
function failure(error: unknown): SessionBundleFailure {
const reason = classify(error);
if (reason !== 'failed') return { ok: false, reason };
diff --git a/apps/desktop/src/preload/bridge-contract.d.ts b/apps/desktop/src/preload/bridge-contract.d.ts
index 023276ed0f..af23d62779 100644
--- a/apps/desktop/src/preload/bridge-contract.d.ts
+++ b/apps/desktop/src/preload/bridge-contract.d.ts
@@ -174,6 +174,10 @@ export type SessionBundleExportIpcResult =
| { readonly ok: true; readonly sessionCount: number; readonly path: string }
| SessionBundleFailure;
+export type SessionBundlePreviewIpcResult =
+ | { readonly ok: true; readonly sessionCount: number; readonly subtreeDigest: string }
+ | SessionBundleFailure;
+
export type SessionBundleImportIpcResult =
| { readonly ok: true; readonly sessionCount: number }
| SessionBundleFailure;
@@ -1349,6 +1353,7 @@ export interface MakaBridge {
}, host?: DesktopRuntimeHostRef): Promise<ExternalSessionImportIpcResult<DesktopSessionSummary>>;
};
sessionBundles: {
+ preview(sessionId: string): Promise<SessionBundlePreviewIpcResult>;
/**
* Picks a destination, then writes the Session and its subagent subtree.
*
@@ -1359,8 +1364,7 @@ export interface MakaBridge {
export(input: {
sessionId: string;
suggestedName: string;
- /** Projected ids of the Sessions the user was shown. See the Host operation. */
- confirmedSubtree?: readonly string[];
+ expectedSubtreeDigest: string;
}): Promise<SessionBundleExportIpcResult>;
/** Picks a `.maka-session` file and merges it into the Local workspace. */
import(): Promise<SessionBundleImportIpcResult>;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 8dff6f4143..c3c2cf2a94 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2684,6 +2684,12 @@ const makaBridge = {
},
},
sessionBundles: {
+ async preview(projectedId) {
+ const scope = await localRuntimeHostRef();
+ const { sessionId, hostId } = parseDesktopSessionKey(projectedId);
+ if (hostId !== scope.hostId) throw new Error('Session bundles require a Local Host Session');
+ return invokeWhenReady('session-bundle:preview', scope, sessionId) as ReturnType<MakaBridge['sessionBundles']['preview']>;
+ },
// Both halves name a path the Electron picker chose, which is a path on
// THIS machine, and the protocol interprets it on the Host's filesystem.
// Those are the same filesystem only for the Local Host, so both are routed
@@ -2693,18 +2699,13 @@ const makaBridge = {
async export(input: {
sessionId: string;
suggestedName: string;
- confirmedSubtree?: readonly string[];
+ expectedSubtreeDigest: string;
}): Promise<SessionBundleExportIpcResult> {
const scope = await localRuntimeHostRef();
- const { sessionId } = parseDesktopSessionKey(input.sessionId);
- // Unprojected here, where the boundary already is: the renderer holds
- // host-scoped ids and the Host knows only its own, so a digest computed
- // upstream would compare two different alphabets and never match.
- const confirmed = input.confirmedSubtree?.map(
- (projected) => parseDesktopSessionKey(projected).sessionId,
- );
+ const { sessionId, hostId } = parseDesktopSessionKey(input.sessionId);
+ if (hostId !== scope.hostId) throw new Error('Session bundles require a Local Host Session');
return (await invokeWhenReady(
- 'session-bundle:export', scope, sessionId, input.suggestedName, confirmed,
+ 'session-bundle:export', scope, sessionId, input.suggestedName, input.expectedSubtreeDigest,
)) as SessionBundleExportIpcResult;
},
async import(): Promise<SessionBundleImportIpcResult> {
diff --git a/apps/desktop/src/renderer/features/session-bundle/export-tree.tsx b/apps/desktop/src/renderer/features/session-bundle/export-tree.tsx
index facf8287ec..0f6c85337b 100644
--- a/apps/desktop/src/renderer/features/session-bundle/export-tree.tsx
+++ b/apps/desktop/src/renderer/features/session-bundle/export-tree.tsx
@@ -27,17 +27,11 @@ import { useUiLocale } from '@maka/ui';
import type { DesktopSessionSummary } from '../../../shared/desktop-session-projection.js';
import { getExternalSessionImportCopy } from '../../locales/external-session-import-copy.js';
-/**
- * The local tasks, as the tree a bundle would carry.
- *
- * A bundle can be rooted at any node -- a subagent Session has its own complete
- * history -- so every row exports, and the nesting says which subtree a row
- * would take with it.
- */
+/** Known catalog relationships; only the Host preview defines export membership. */
export function ExportTree(props: {
sessions: readonly DesktopSessionSummary[];
isBusy: boolean;
- onExport: (session: DesktopSessionSummary, subtree: readonly string[]) => void;
+ onExport: (session: DesktopSessionSummary) => void;
}): ReactElement {
const copy = getExternalSessionImportCopy(useUiLocale());
@@ -46,23 +40,6 @@ export function ExportTree(props: {
// archived child nests under a parent that never draws it, so nobody renders
// it at all.
const visible = props.sessions.filter((session) => !session.isArchived);
- // Two subtrees, on purpose. The visible one decides what is drawn; this one
- // is every linked descendant, archived included, because that is the set the
- // Host fences and exports. Confirming from the drawn one would name a
- // different set than the file holds -- and would be refused as stale forever
- // for any parent with an archived child.
- const wholeTree = projectLinkedSessionTree(props.sessions);
- const wholeSubtree = (sessionId: string): readonly string[] => {
- const ids = [sessionId];
- const pending = [...(wholeTree.childrenByParentId.get(sessionId) ?? [])];
- while (pending.length > 0) {
- const next = pending.pop();
- if (next === undefined) continue;
- ids.push(next.id);
- pending.push(...(wholeTree.childrenByParentId.get(next.id) ?? []));
- }
- return ids;
- };
// The read model the rest of the app projects lineage with, rather than a
// second one maintained here. It resolves both spellings of the link, drops a
// parent that is not in the list, and refuses a cycle -- which `subagentParent`
@@ -71,24 +48,9 @@ export function ExportTree(props: {
const childrenOf = (sessionId: string): readonly DesktopSessionSummary[] =>
(tree.childrenByParentId.get(sessionId) ?? []) as readonly DesktopSessionSummary[];
- const descendantCount = (sessionId: string): number => {
- // A subagent spawns its own, so this walks the subtree rather than counting
- // one level.
- let count = 0;
- const pending = [...childrenOf(sessionId)];
- while (pending.length > 0) {
- const next = pending.pop();
- if (next === undefined) continue;
- count += 1;
- pending.push(...childrenOf(next.id));
- }
- return count;
- };
-
if (tree.roots.length === 0) return <EmptyState title={copy.exportEmpty} />;
const node = (session: DesktopSessionSummary, depth: number): ReactElement => {
- const carried = descendantCount(session.id);
const agent = session.subagent?.agentName ?? session.subagentRuntime?.agentName;
const children = childrenOf(session.id);
return (
@@ -99,9 +61,6 @@ export function ExportTree(props: {
<span className="maka-export-name">{session.name ?? session.id}</span>
{agent ? <Badge variant="neutral" label={agent} /> : null}
</HStack>
- {carried > 0 && (
- <span className="maka-export-carries">{copy.exportCarriesSubagents(carried)}</span>
- )}
</VStack>
<Button
// A root is what someone came here to export; a child is usually
@@ -111,7 +70,7 @@ export function ExportTree(props: {
label={copy.exportAction}
aria-label={copy.exportActionFor(session.name ?? session.id)}
isDisabled={props.isBusy}
- onClick={() => props.onExport(session, wholeSubtree(session.id))}
+ onClick={() => props.onExport(session)}
/>
</div>
{children.length > 0 && (
diff --git a/apps/desktop/src/renderer/features/session-bundle/ports.ts b/apps/desktop/src/renderer/features/session-bundle/ports.ts
index 7445170812..a6cd5b9c84 100644
--- a/apps/desktop/src/renderer/features/session-bundle/ports.ts
+++ b/apps/desktop/src/renderer/features/session-bundle/ports.ts
@@ -46,22 +46,15 @@ export type SessionBundleImportOutcome =
| { readonly ok: false; readonly reason: SessionBundleFailureReason; readonly detail?: string };
export interface SessionBundleServices {
+ previewBundle(sessionId: string): Promise<
+ | { readonly ok: true; readonly sessionCount: number; readonly subtreeDigest: string }
+ | { readonly ok: false; readonly reason: SessionBundleFailureReason; readonly detail?: string }
+ >;
/** Picks a destination, then writes the Session and its subagent subtree. */
exportBundle(input: {
readonly sessionId: string;
readonly suggestedName: string;
- /**
- * The Session ids the user was shown, root included.
- *
- * Read from the catalog this renderer has; the save dialog opens, and only
- * then does the Host discover and fence the real subtree. Another client
- * can finish spawning a child in that gap, so the file would hold Sessions
- * nobody was asked about. These become a digest at the boundary where the
- * ids are already the Host's own, and the Host compares it against what it
- * fenced -- a digest, because two subtrees of the same size are not the
- * same subtree.
- */
- readonly confirmedSubtree?: readonly string[];
+ readonly expectedSubtreeDigest: string;
}): Promise<SessionBundleExportOutcome>;
/** Picks a `.maka-session` file and merges it into this workspace. */
importBundle(): Promise<SessionBundleImportOutcome>;
diff --git a/apps/desktop/src/renderer/features/session-bundle/session-bundle-tasks.tsx b/apps/desktop/src/renderer/features/session-bundle/session-bundle-tasks.tsx
index 1a9a6bef26..fc414ca61a 100644
--- a/apps/desktop/src/renderer/features/session-bundle/session-bundle-tasks.tsx
+++ b/apps/desktop/src/renderer/features/session-bundle/session-bundle-tasks.tsx
@@ -180,7 +180,6 @@ interface SessionBundleActions {
readonly importBundle: () => Promise<void>;
readonly exportTask: (
session: DesktopSessionSummary,
- subtree: readonly string[],
) => Promise<void>;
}
@@ -263,26 +262,29 @@ function useSessionBundleActions(): SessionBundleActions {
if (mountedRef.current) setBusy(false);
}
},
- exportTask: async (session, subtree) => {
- const carried = subtree.length - 1;
- if (carried > 0) {
- // The row names one task and the file holds several. Saying so before
- // the save dialog is the last point where that is still a decision.
- const confirmed = await toast.confirm({
- title: copy.exportSubtreeConfirmTitle(carried),
- description: copy.exportSubtreeConfirmBody,
- confirmLabel: copy.exportAction,
- cancelLabel: getSettingsSharedCopy(locale).cancel,
- });
- if (!confirmed) return;
- }
+ exportTask: async (session) => {
setBusy(true);
setNote(undefined);
try {
+ const preview = await services.previewBundle(session.id);
+ if (!preview.ok) {
+ settle(preview);
+ return;
+ }
+ const carried = preview.sessionCount - 1;
+ if (carried > 0) {
+ const confirmed = await toast.confirm({
+ title: copy.exportSubtreeConfirmTitle(carried),
+ description: copy.exportSubtreeConfirmBody,
+ confirmLabel: copy.exportAction,
+ cancelLabel: getSettingsSharedCopy(locale).cancel,
+ });
+ if (!confirmed) return;
+ }
const result = await services.exportBundle({
sessionId: session.id,
suggestedName: session.name ?? session.id,
- confirmedSubtree: subtree,
+ expectedSubtreeDigest: preview.subtreeDigest,
});
settle(result.ok ? { ok: true, text: copy.exported(result.sessionCount) } : result);
} catch (error) {
diff --git a/apps/desktop/src/renderer/locales/external-session-import-copy.ts b/apps/desktop/src/renderer/locales/external-session-import-copy.ts
index ddc04148ab..999867d43b 100644
--- a/apps/desktop/src/renderer/locales/external-session-import-copy.ts
+++ b/apps/desktop/src/renderer/locales/external-session-import-copy.ts
@@ -106,7 +106,6 @@ type ExternalSessionImportCopy = {
exportDescription: string;
exportAction: string;
exportActionFor: (name: string) => string;
- exportCarriesSubagents: (count: number) => string;
exportSubtreeConfirmTitle: (count: number) => string;
exportSubtreeConfirmBody: string;
exportEmpty: string;
@@ -132,7 +131,6 @@ const COPY = {
exportDescription: '把一个任务写成 .maka-session 文件,在另一台机器或另一个版本的 Maka 里导入。它下面的子 Agent 对话会一起导出。',
exportAction: '导出',
exportActionFor: (name) => `导出「${name}」`,
- exportCarriesSubagents: (count) => `含 ${count} 个子 Agent 对话`,
exportSubtreeConfirmTitle: (count) => `连同 ${count} 个子 Agent 对话一起导出?`,
exportSubtreeConfirmBody:
'文件里会包含这个任务和它下面的全部子 Agent 对话。子 Agent 的对话是这个任务某次工具调用的结果,单独留下会让记录不完整。',
@@ -214,7 +212,6 @@ const COPY = {
exportDescription: '把一個任務寫成 .maka-session 檔案,在另一台機器或另一個版本的 Maka 匯入。它底下的子 Agent 對話會一起匯出。',
exportAction: '匯出',
exportActionFor: (name) => `匯出「${name}」`,
- exportCarriesSubagents: (count) => `含 ${count} 個子 Agent 對話`,
exportSubtreeConfirmTitle: (count) => `連同 ${count} 個子 Agent 對話一起匯出?`,
exportSubtreeConfirmBody:
'檔案裡會包含這個任務和它底下的全部子 Agent 對話。子 Agent 的對話是這個任務某次工具呼叫的結果,單獨留下會讓紀錄不完整。',
@@ -296,7 +293,6 @@ const COPY = {
exportDescription: 'Write a task to a .maka-session file to import on another machine, or in another build of Maka. The subagent conversations under it are carried with it.',
exportAction: 'Export',
exportActionFor: (name) => `Export ${name}`,
- exportCarriesSubagents: (count) => `Carries ${count} subagent ${count === 1 ? 'conversation' : 'conversations'}`,
exportSubtreeConfirmTitle: (count) =>
`Export with ${count} subagent ${count === 1 ? 'conversation' : 'conversations'}?`,
exportSubtreeConfirmBody:
diff --git a/apps/desktop/src/renderer/platform/desktop/create-session-bundle-services.ts b/apps/desktop/src/renderer/platform/desktop/create-session-bundle-services.ts
index f369353282..be9f9dc7d5 100644
--- a/apps/desktop/src/renderer/platform/desktop/create-session-bundle-services.ts
+++ b/apps/desktop/src/renderer/platform/desktop/create-session-bundle-services.ts
@@ -27,6 +27,7 @@ export function createDesktopSessionBundleServices(
bridge: DesktopSessionBundleBridge = window.maka,
): SessionBundleServices {
return {
+ previewBundle: (sessionId) => bridge.sessionBundles.preview(sessionId),
// No host argument: a Session belongs to the Host that holds it, not to
// whichever one Settings happens to be pointed at, and the bridge routes by
// the projected id for exactly that reason.
diff --git a/apps/desktop/src/renderer/reference-shell.css b/apps/desktop/src/renderer/reference-shell.css
index 0e277bd6e0..6668463914 100644
--- a/apps/desktop/src/renderer/reference-shell.css
+++ b/apps/desktop/src/renderer/reference-shell.css
@@ -137,8 +137,3 @@
.maka-export-name {
font-size: var(--font-size-base);
}
-
-.maka-export-carries {
- font-size: var(--font-size-sm);
- color: var(--muted-foreground);
-}
diff --git a/apps/desktop/stories/settings/settings-pages.stories.tsx b/apps/desktop/stories/settings/settings-pages.stories.tsx
index 47f5388972..9e279b41ad 100644
--- a/apps/desktop/stories/settings/settings-pages.stories.tsx
+++ b/apps/desktop/stories/settings/settings-pages.stories.tsx
@@ -21,6 +21,7 @@
import { useRef, useState } from 'react';
import { createSessionCatalogController } from '../../src/renderer/application/contracts/session-catalog/session-catalog-state.js';
import type { Meta, StoryObj } from '@storybook/react-vite';
+import { ClientPluginServicesProvider, type ClientPluginServices } from '../../src/renderer/features/client-plugins/index.js';
import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
import { ToastProvider, useToast } from '@maka/ui';
import type {
@@ -133,10 +134,25 @@ const noop = () => undefined;
// Both halves open a native file dialog, which a story has none of. Cancelled is
// the outcome that leaves the page exactly as it was.
const sessionBundleServices: SessionBundleServices = {
+ previewBundle: async () => ({ ok: true, sessionCount: 1, subtreeDigest: '0'.repeat(64) }),
exportBundle: async () => ({ ok: false, reason: 'canceled' }),
importBundle: async () => ({ ok: false, reason: 'canceled' }),
};
+// Native settings with no Client Contributions installed.
+const emptyClientPlugins: ClientPluginServices = {
+ defaultHost: async () => ({ profileId: 'local', hostId: 'storybook-local' }),
+ subscribeDefaultHost: () => noop,
+ connect: (host) => ({
+ snapshot: async () => ({ revision: '1', connection: host.hostId, entries: [] }),
+ source: async () => { throw new Error('No Client Contribution is installed'); },
+ remote: () => { throw new Error('No Client Contribution is installed'); },
+ session: async (id) => JSON.stringify([host.hostId, id]),
+ subscribe: () => noop,
+ subscribeContext: () => noop,
+ }),
+};
+
function makeConnection(input: {
slug: string;
name: string;
@@ -1598,6 +1614,7 @@ function useArchivedTasksStoryBridge(seed: readonly SessionSummary[]): ArchivedT
const catalog = createSessionCatalogController();
catalog.commitSessions(seed.map((session) => ({
...session,
+ activityAt: session.lastMessageAt ?? NOW,
revision: 1,
runtimeHostId: 'storybook-local',
approvalPolicy: { kind: 'on-request' },
@@ -1854,6 +1871,7 @@ function renderedLinkColors(renderedLink: HTMLElement) {
}
type SettingsStoryProps = {
+ bundleServices?: SessionBundleServices;
reopenable?: boolean;
section: SettingsSection;
connections?: LlmConnection[];
@@ -1898,6 +1916,7 @@ function fieldChrome(element: HTMLElement) {
*/
function SettingsStory(props: SettingsStoryProps) {
return (
+ <ClientPluginServicesProvider services={emptyClientPlugins}>
<ToastProvider>
<AppUpdateServicesProvider services={settingsAppUpdateServices}>
<AppUpdateProvider>
@@ -1905,6 +1924,7 @@ function SettingsStory(props: SettingsStoryProps) {
</AppUpdateProvider>
</AppUpdateServicesProvider>
</ToastProvider>
+ </ClientPluginServicesProvider>
);
}
@@ -1951,7 +1971,7 @@ function SettingsStoryFrame(props: SettingsStoryProps) {
>
<ConnectionSettingsServicesProvider services={connectionSettingsServices}>
<RuntimeHostManagementServicesProvider services={runtimeHostManagementServices}>
- <SessionBundleServicesProvider services={sessionBundleServices}>
+ <SessionBundleServicesProvider services={props.bundleServices ?? sessionBundleServices}>
{open && <SettingsSurface
onClose={noop}
themePref={themePref}
@@ -3459,19 +3479,32 @@ export const ImportTasks: Story = {
/**
* Real path: 设置 → 导入/导出任务 → 导出任务.
*
- * A bundle can be rooted at any node, so every row exports; the nesting says
- * which subtree a row would carry, and the count on a parent is the whole
- * subtree rather than its children.
+ * Known catalog links are displayed, but confirmation uses the Host inventory,
+ * including archived descendants not shown here. Cancel returns focus and admission.
*/
export const ImportTasksExport: Story = {
decorators: [withSettingsBridge],
render: () => (
- <SettingsStory section="import-tasks" archivedTaskSessions={exportTaskSessions} />
+ <SettingsStory section="import-tasks" archivedTaskSessions={exportTaskSessions}
+ bundleServices={{
+ ...sessionBundleServices,
+ // The Host also carries two archived descendants absent from this catalog page.
+ previewBundle: async () => ({ ok: true, sessionCount: 6, subtreeDigest: 'a'.repeat(64) }),
+ exportBundle: async () => { throw new Error('Canceled confirmation must not open the file picker'); },
+ }}
+ />
),
play: async ({ canvasElement }) => {
const body = within(canvasElement.ownerDocument.body);
await userEvent.click(await body.findByRole('radio', { name: '导出任务' }));
await body.findByText('Refactor the compaction module');
+ const action = await body.findByRole('button', { name: '导出「Refactor the compaction module」' });
+ await userEvent.click(action);
+ await body.findByText('连同 5 个子 Agent 对话一起导出?');
+ await userEvent.click(await body.findByRole('button', { name: '取消' }));
+ await waitFor(() => {
+ if (action.hasAttribute('disabled')) throw new Error('Canceled export did not release the action');
+ });
},
};
diff --git a/crates/client/src/notification.rs b/crates/client/src/notification.rs
index ffd309ca80..d9dcf5b892 100644
--- a/crates/client/src/notification.rs
+++ b/crates/client/src/notification.rs
@@ -50,8 +50,10 @@ pub(crate) fn decode(value: &Value) -> Result<Notification> {
None
}
"session.catalog.changed" => {
- codec::exact(row, &["kind", "revision", "sessionId"])?;
- Some(codec::string(&value["sessionId"], "sessionId", 128)?)
+ codec::shaped(row, &["kind", "revision"], &["sessionId"])?;
+ row.get("sessionId")
+ .map(|id| codec::string(id, "sessionId", 128))
+ .transpose()?
}
_ => {
return Err(ProtocolError::invalid(format!(
diff --git a/crates/event-log/src/bundle/export.rs b/crates/event-log/src/bundle/export.rs
index ebe35c298e..e702ea629f 100644
--- a/crates/event-log/src/bundle/export.rs
+++ b/crates/event-log/src/bundle/export.rs
@@ -24,6 +24,7 @@ use super::{
};
use crate::{EventLog, StoreError, sequence_number};
use sqlx::{Connection, SqliteConnection};
+use std::{io, time::Duration};
use tokio::io::AsyncWrite;
/// Inventory and checksum of a complete uncompressed transfer, not permission
@@ -47,7 +48,9 @@ impl EventLog {
let (root, expected) = (root.to_owned(), expected_subtree_digest.to_owned());
self.connection.read(move |db| Box::pin(async move {
let mut tx = db.begin().await?;
- let result = async {
+ // Bound snapshot ownership even when a reader keeps making tiny
+ // progress, or the caller disappears without cancelling owned work.
+ let result = tokio::time::timeout(Duration::from_secs(300), async {
let inventory = super::inventory(&mut tx, &root).await?;
inventory.verify_confirmation(&expected)?;
require_idle(&mut tx, &inventory).await?;
@@ -68,7 +71,9 @@ impl EventLog {
accounting(&mut tx, &closure, &mut writer).await?;
let (output, bytes, digest) = writer.finish().await?;
Ok((output, BundleSummary { inventory, bytes, digest }))
- }.await;
+ }).await.unwrap_or_else(|_| Err(StoreError::Io(io::Error::new(
+ io::ErrorKind::TimedOut, "Session bundle export deadline exceeded",
+ )).into()));
tx.rollback().await?;
Ok(result)
})).await?
diff --git a/crates/event-log/src/bundle/stage.rs b/crates/event-log/src/bundle/stage.rs
index 45584d56b6..c67f3a0219 100644
--- a/crates/event-log/src/bundle/stage.rs
+++ b/crates/event-log/src/bundle/stage.rs
@@ -66,6 +66,7 @@ pub(super) async fn payload(
pub struct StagedBundle {
pub(super) database: SqliteConnection,
pub(super) summary: BundleSummary,
+ history_validated: bool,
}
impl StagedBundle {
@@ -119,7 +120,11 @@ impl StagedBundle {
}
.await;
match result {
- Ok(summary) => Ok(Self { database, summary }),
+ Ok(summary) => Ok(Self {
+ database,
+ summary,
+ history_validated: false,
+ }),
Err(error) => {
database.close().await.map_err(StoreError::from)?;
Err(error.into())
@@ -167,7 +172,12 @@ impl StagedBundle {
/// Validate original history before any position or proof relocation. This
/// does not bind destination workspaces, grant execution or publish Sessions.
pub async fn validate_history(&mut self) -> Result<(), BundleError> {
- super::validation::validate(&mut self.database).await?;
+ // Staged source bytes are private and immutable after read. Callers may
+ // validate before acquiring destination admission without repeating it.
+ if !self.history_validated {
+ super::validation::validate(&mut self.database).await?;
+ self.history_validated = true;
+ }
Ok(())
}
diff --git a/crates/protocol/src/authority.rs b/crates/protocol/src/authority.rs
index b90aa08c27..da2d708a4e 100644
--- a/crates/protocol/src/authority.rs
+++ b/crates/protocol/src/authority.rs
@@ -120,6 +120,7 @@ impl Operation {
| Self::SessionRecapGenerate
| Self::SessionRemove
| Self::SessionRemovePreview
+ | Self::SessionBundlePreview
| Self::SessionRemoveQuery
| Self::SessionRevisionAbandon
| Self::SessionRevisionCreate
diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs
index 9ab733fbce..95e024b2e4 100644
--- a/crates/protocol/src/lib.rs
+++ b/crates/protocol/src/lib.rs
@@ -59,7 +59,7 @@ use serde::Serialize;
use serde_json::Value;
pub const PROTOCOL_VERSION: u64 = 0;
-pub const COMPATIBILITY_EPOCH: u64 = 181;
+pub const COMPATIBILITY_EPOCH: u64 = 182;
pub const COMPOSITION_ID: &str = "maka.interactive";
pub const MAX_MESSAGE_BYTES: usize = 768 * 1024;
pub const MAX_IN_FLIGHT_DOMAIN_REQUESTS: usize = 64;
diff --git a/crates/protocol/src/operation.rs b/crates/protocol/src/operation.rs
index a48368e613..0ebb9bb71a 100644
--- a/crates/protocol/src/operation.rs
+++ b/crates/protocol/src/operation.rs
@@ -140,6 +140,7 @@ operations! {
ExternalAgentsSetupStart => ("external_agents.setup.start", Command, Ready),
ExternalAgentsSetupQuery => ("external_agents.setup.query", Query, Ready),
ExternalAgentsSetupCancel => ("external_agents.setup.cancel", Control, Ready),
+ SessionBundlePreview => ("session-bundle.preview", Query, Ready),
SessionBundleExport => ("session-bundle.export", Command, Ready),
SessionBundleImport => ("session-bundle.import", Command, Ready),
ExternalSessionImport => ("external-session.import", Command, Ready),
diff --git a/crates/protocol/src/session.rs b/crates/protocol/src/session.rs
index a6b76b4936..86b89e9d89 100644
--- a/crates/protocol/src/session.rs
+++ b/crates/protocol/src/session.rs
@@ -20,6 +20,7 @@
//! Session catalog and retirement wire contracts.
//! Use the decode functions at the JSON boundary; they enforce semantic limits
//! in addition to the owned serde representations.
+pub mod bundle;
mod configuration;
pub mod copy;
mod mutation;
diff --git a/crates/protocol/src/session/bundle.rs b/crates/protocol/src/session/bundle.rs
new file mode 100644
index 0000000000..27acf5e074
--- /dev/null
+++ b/crates/protocol/src/session/bundle.rs
@@ -0,0 +1,151 @@
+/*
+ * 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.
+ */
+
+//! Native history transfer names paths on the Host, never on a remote client.
+use super::WorkspaceTarget;
+use crate::{OperationErrorCode, ProtocolError, Result, codec};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Preview {
+ pub session_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Previewed {
+ pub session_count: u64,
+ pub subtree_digest: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Export {
+ pub session_id: String,
+ pub destination: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub expected_subtree_digest: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Exported {
+ pub session_count: u64,
+ pub compressed_bytes: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Import {
+ pub source: String,
+ pub workspace: WorkspaceTarget,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct Imported {
+ pub session_count: u64,
+ pub artifact_files: u64,
+}
+
+pub fn decode_preview(value: &Value) -> Result<Preview> {
+ super::validation::decode(value)
+}
+
+pub fn decode_previewed(value: &Value) -> Result<Previewed> {
+ let output: Previewed = decode(value)?;
+ counts(value, &["sessionCount"])?;
+ digest(&output.subtree_digest)?;
+ Ok(output)
+}
+
+pub fn decode_export(value: &Value) -> Result<Export> {
+ let input: Export = super::validation::decode(value)?;
+ path(&input.destination)?;
+ if let Some(expected) = &input.expected_subtree_digest {
+ digest(expected)?;
+ }
+ Ok(input)
+}
+
+fn digest(value: &str) -> Result<()> {
+ if value.len() != 64
+ || !value
+ .bytes()
+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
+ {
+ return Err(ProtocolError::invalid("Invalid subtree digest"));
+ }
+ Ok(())
+}
+
+pub fn decode_import(value: &Value) -> Result<Import> {
+ let input: Import = super::validation::decode(value)?;
+ path(&input.source)?;
+ Ok(input)
+}
+
+pub fn decode_exported(value: &Value) -> Result<Exported> {
+ let output: Exported = decode(value)?;
+ counts(value, &["sessionCount", "compressedBytes"])?;
+ Ok(output)
+}
+
+pub fn decode_imported(value: &Value) -> Result<Imported> {
+ let output: Imported = decode(value)?;
+ counts(value, &["sessionCount", "artifactFiles"])?;
+ Ok(output)
+}
+
+fn decode<T: serde::de::DeserializeOwned>(value: &Value) -> Result<T> {
+ serde_json::from_value(value.clone()).map_err(|e| ProtocolError::invalid(e.to_string()))
+}
+
+fn path(path: &str) -> Result<()> {
+ if path.len() > 4096 || path.contains('\0') || !codec::absolute_host_path(path) {
+ return Err(ProtocolError::invalid(
+ "Bundle path must be an absolute Host path",
+ ));
+ }
+ Ok(())
+}
+
+fn counts(value: &Value, names: &[&str]) -> Result<()> {
+ for name in names {
+ codec::count(&value[*name], name)?;
+ }
+ Ok(())
+}
+
+pub const ERRORS: &[OperationErrorCode] = &[
+ OperationErrorCode::HostNotReady,
+ OperationErrorCode::HostDraining,
+ OperationErrorCode::OperationUnavailable,
+ OperationErrorCode::InvalidRequest,
+ OperationErrorCode::NotFound,
+ OperationErrorCode::SessionBusy,
+ OperationErrorCode::OperationConflict,
+ OperationErrorCode::SourceUnreadable,
+ OperationErrorCode::CandidateSetStale,
+ OperationErrorCode::PersistenceFailed,
+ OperationErrorCode::CommitOutcomeUnknown,
+ OperationErrorCode::InternalFailure,
+];
diff --git a/crates/protocol/src/session/operations.rs b/crates/protocol/src/session/operations.rs
index 297f78919a..dbfd5fa95e 100644
--- a/crates/protocol/src/session/operations.rs
+++ b/crates/protocol/src/session/operations.rs
@@ -24,6 +24,9 @@ pub fn supports(operation: Operation) -> bool {
matches!(
operation,
Operation::SessionCreate
+ | Operation::SessionBundlePreview
+ | Operation::SessionBundleExport
+ | Operation::SessionBundleImport
| Operation::SessionBranchCreate
| Operation::SessionRevisionCreate
| Operation::SessionRevisionAbandon
@@ -43,6 +46,15 @@ pub fn supports(operation: Operation) -> bool {
pub fn decode_input(operation: Operation, value: &Value) -> crate::Result<Value> {
match operation {
+ Operation::SessionBundlePreview => {
+ bundle::decode_preview(value)?;
+ }
+ Operation::SessionBundleExport => {
+ bundle::decode_export(value)?;
+ }
+ Operation::SessionBundleImport => {
+ bundle::decode_import(value)?;
+ }
Operation::SessionRemove => {
decode_session_remove_input(value)?;
}
@@ -91,7 +103,13 @@ pub fn decode_input(operation: Operation, value: &Value) -> crate::Result<Value>
}
pub fn decode_output(operation: Operation, value: &Value) -> crate::Result<Value> {
- if operation == Operation::SessionRemove {
+ if operation == Operation::SessionBundlePreview {
+ bundle::decode_previewed(value)?;
+ } else if operation == Operation::SessionBundleExport {
+ bundle::decode_exported(value)?;
+ } else if operation == Operation::SessionBundleImport {
+ bundle::decode_imported(value)?;
+ } else if operation == Operation::SessionRemove {
decode_session_remove_result(value)?;
} else if operation == Operation::SessionRemovePreview {
decode_session_remove_preview_result(value)?;
@@ -191,6 +209,9 @@ pub const CONFIGURATION_ERRORS: &[OperationErrorCode] = &[
pub fn errors(operation: Operation) -> Option<&'static [OperationErrorCode]> {
match operation {
+ Operation::SessionBundlePreview
+ | Operation::SessionBundleExport
+ | Operation::SessionBundleImport => Some(bundle::ERRORS),
Operation::SessionBranchCreate
| Operation::SessionRevisionCreate
| Operation::SessionRevisionAbandon
diff --git a/crates/runtime-host/Cargo.toml b/crates/runtime-host/Cargo.toml
index ca5d67ce39..b0da69dade 100644
--- a/crates/runtime-host/Cargo.toml
+++ b/crates/runtime-host/Cargo.toml
@@ -24,6 +24,7 @@ license.workspace = true
publish.workspace = true
[dependencies]
+async-compression = { version = "0.4.46", features = ["tokio", "gzip"] }
rusqlite = { workspace = true, features = ["hooks", "limits"] }
maka-providers.workspace = true
maka-workhub.workspace = true
diff --git a/crates/runtime-host/src/server/catalog_feed.rs b/crates/runtime-host/src/server/catalog_feed.rs
index f61d7f3d4b..8d0f71230b 100644
--- a/crates/runtime-host/src/server/catalog_feed.rs
+++ b/crates/runtime-host/src/server/catalog_feed.rs
@@ -50,7 +50,14 @@ impl CatalogFeed {
}
pub(crate) async fn publish_session(&self, session_id: &str) -> Result<(), HostError> {
- self.cursor.lock().await.publish(&self.changes, session_id)
+ self.cursor
+ .lock()
+ .await
+ .publish(&self.changes, Some(session_id))
+ }
+
+ pub(super) async fn publish_all(&self) -> Result<(), HostError> {
+ self.cursor.lock().await.publish(&self.changes, None)
}
/// Processes one bounded page. True asks the connection loop to schedule
@@ -71,7 +78,7 @@ impl CatalogFeed {
let mut seen = HashSet::new();
for (sequence, session_id) in rows.iter().take(PAGE_SIZE) {
if seen.insert(session_id) {
- cursor.publish(&self.changes, session_id)?;
+ cursor.publish(&self.changes, Some(session_id))?;
}
cursor.after = *sequence;
}
@@ -86,15 +93,17 @@ impl Cursor {
fn publish(
&mut self,
changes: &broadcast::Sender<Value>,
- session_id: &str,
+ session_id: Option<&str>,
) -> Result<(), HostError> {
if self.revision == MAX_NOTICE_REVISION {
return Err("session notice revision exhausted".into());
}
self.revision += 1;
- let _ = changes.send(json!({
- "kind": "session.catalog.changed", "revision": self.revision, "sessionId": session_id,
- }));
+ let mut notice = json!({"kind": "session.catalog.changed", "revision": self.revision});
+ if let Some(id) = session_id {
+ notice["sessionId"] = id.into();
+ }
+ let _ = changes.send(notice);
Ok(())
}
}
diff --git a/crates/runtime-host/src/server/sessions.rs b/crates/runtime-host/src/server/sessions.rs
index 2e94aa6a02..776841d1f3 100644
--- a/crates/runtime-host/src/server/sessions.rs
+++ b/crates/runtime-host/src/server/sessions.rs
@@ -17,6 +17,7 @@
* under the License.
*/
+mod bundle;
pub(super) mod configuration;
pub(super) mod copy;
pub(super) mod create;
@@ -38,6 +39,9 @@ type Result<T> = std::result::Result<T, OperationError>;
#[derive(serde::Serialize)]
#[serde(untagged)]
pub(super) enum Output {
+ BundlePreviewed(maka_protocol::session::bundle::Previewed),
+ BundleExported(maka_protocol::session::bundle::Exported),
+ BundleImported(maka_protocol::session::bundle::Imported),
Query(SessionCatalogQueryResult),
Item(Box<SessionCatalogProjection>),
Mutation(SessionUpdateResult),
@@ -68,6 +72,24 @@ pub(super) async fn execute(
) -> Result<Output> {
let log = host.log.as_ref();
match operation {
+ Operation::SessionBundlePreview => bundle::preview(
+ host,
+ maka_protocol::session::bundle::decode_preview(value).map_err(invalid)?,
+ )
+ .await
+ .map(Output::BundlePreviewed),
+ Operation::SessionBundleExport => bundle::export(
+ host,
+ maka_protocol::session::bundle::decode_export(value).map_err(invalid)?,
+ )
+ .await
+ .map(Output::BundleExported),
+ Operation::SessionBundleImport => bundle::import(
+ host,
+ maka_protocol::session::bundle::decode_import(value).map_err(invalid)?,
+ )
+ .await
+ .map(Output::BundleImported),
Operation::SessionRemove => {
removal::remove(host, decode_session_remove_input(value).map_err(invalid)?)
.await
diff --git a/crates/runtime-host/src/server/sessions/bundle.rs b/crates/runtime-host/src/server/sessions/bundle.rs
new file mode 100644
index 0000000000..6cfb66a9ac
--- /dev/null
+++ b/crates/runtime-host/src/server/sessions/bundle.rs
@@ -0,0 +1,186 @@
+/*
+ * 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.
+ */
+
+mod binding;
+mod file;
+
+use super::{Result, failure, stored};
+use crate::server::Host;
+use async_compression::tokio::{bufread::GzipDecoder, write::GzipEncoder};
+use maka_event_log::{
+ StoreError,
+ bundle::{BundleError, StagedBundle},
+};
+use maka_protocol::{OperationErrorCode as Code, session::bundle as api};
+use std::time::Duration;
+use tokio::{
+ io::{AsyncWriteExt, BufReader},
+ sync::Semaphore,
+};
+
+static TRANSFERS: Semaphore = Semaphore::const_new(2);
+const READ_TIMEOUT: Duration = Duration::from_secs(300);
+
+pub(super) async fn preview(host: &Host, input: api::Preview) -> Result<api::Previewed> {
+ let inventory = host
+ .log
+ .preview_bundle(&input.session_id)
+ .await
+ .map_err(error)?;
+ Ok(api::Previewed {
+ session_count: inventory.sessions.len() as u64,
+ subtree_digest: inventory.subtree_digest,
+ })
+}
+
+pub(super) async fn export(host: &Host, input: api::Export) -> Result<api::Exported> {
+ let _permit = TRANSFERS.try_acquire().map_err(|_| {
+ failure(
+ Code::OperationConflict,
+ "Two Session transfers are already active",
+ )
+ })?;
+ let inventory = host
+ .log
+ .preview_bundle(&input.session_id)
+ .await
+ .map_err(error)?;
+ let expected = match input.expected_subtree_digest {
+ Some(digest) => digest,
+ None if inventory.sessions.len() == 1 => inventory.subtree_digest,
+ None => {
+ return Err(failure(
+ Code::CandidateSetStale,
+ "Confirm the complete Session subtree before exporting",
+ ));
+ }
+ };
+ let output = GzipEncoder::new(file::Output::open(host, &input.destination).await?);
+ let (mut output, summary) = host
+ .log
+ .export_bundle(&input.session_id, &expected, output)
+ .await
+ .map_err(error)?;
+ output
+ .shutdown()
+ .await
+ .map_err(|e| failure(Code::PersistenceFailed, &e.to_string()))?;
+ let compressed_bytes = output.into_inner().publish().await?;
+ Ok(api::Exported {
+ session_count: summary.inventory.sessions.len() as u64,
+ compressed_bytes,
+ })
+}
+
+pub(super) async fn import(host: &Host, input: api::Import) -> Result<api::Imported> {
+ let _permit = TRANSFERS.try_acquire().map_err(|_| {
+ failure(
+ Code::OperationConflict,
+ "Two Session transfers are already active",
+ )
+ })?;
+ let file = file::input(host, &input.source).await?;
+ let mut reader = GzipDecoder::new(BufReader::new(file));
+ // The bundle reader checks decoded EOF; concatenated members cannot hide
+ // trailing content behind an otherwise valid first gzip stream.
+ reader.multiple_members(true);
+ let mut staged = tokio::time::timeout(READ_TIMEOUT, StagedBundle::read(reader))
+ .await
+ .map_err(|_| failure(Code::SourceUnreadable, "Bundle read deadline exceeded"))?
+ .map_err(source_error)?;
+ let artifact_files = staged.artifact_count().await.map_err(error)?;
+ let binding = maka_runtime::artifact::content_digest(
+ &serde_json::to_vec(&("session-bundle.import.v1", &input.workspace))
+ .map_err(|e| failure(Code::InvalidRequest, &e.to_string()))?,
+ );
+ if let Some(receipt) = host
+ .log
+ .bundle_import_receipt(&staged.summary().digest, &binding)
+ .await
+ .map_err(stored)?
+ {
+ staged.close().await.map_err(error)?;
+ return Ok(api::Imported {
+ session_count: receipt.session_ids.len() as u64,
+ artifact_files,
+ });
+ }
+ tokio::time::timeout(READ_TIMEOUT, staged.validate_history())
+ .await
+ .map_err(|_| {
+ failure(
+ Code::SourceUnreadable,
+ "Bundle validation deadline exceeded",
+ )
+ })?
+ .map_err(source_error)?;
+ let _admission = host.executions.lock_admission().await;
+ if host.draining.is_cancelled() {
+ return Err(failure(Code::HostDraining, "Host is draining"));
+ }
+ // Another transfer may have committed while we validated or waited for
+ // admission. Its accepted binding wins over defaults that changed since.
+ if let Some(receipt) = host
+ .log
+ .bundle_import_receipt(&staged.summary().digest, &binding)
+ .await
+ .map_err(stored)?
+ {
+ staged.close().await.map_err(error)?;
+ return Ok(api::Imported {
+ session_count: receipt.session_ids.len() as u64,
+ artifact_files,
+ });
+ }
+ let configurations = binding::resolve(host, &mut staged, input.workspace).await?;
+ let receipt = host
+ .log
+ .import_bundle(staged, &binding, configurations)
+ .await
+ .map_err(source_error)?;
+ // One unscoped notice invalidates the catalog, including Sessions without events.
+ host.session_catalog
+ .publish_all()
+ .await
+ .map_err(|e| failure(Code::InternalFailure, &e.to_string()))?;
+ Ok(api::Imported {
+ session_count: receipt.session_ids.len() as u64,
+ artifact_files,
+ })
+}
+
+fn source_error(error: BundleError) -> maka_protocol::OperationError {
+ match error {
+ BundleError::Store(StoreError::Io(_) | StoreError::Json(_)) => {
+ failure(Code::SourceUnreadable, &error.to_string())
+ }
+ other => self::error(other),
+ }
+}
+
+fn error(error: BundleError) -> maka_protocol::OperationError {
+ match error {
+ BundleError::CandidateSetStale => failure(Code::CandidateSetStale, &error.to_string()),
+ BundleError::TooManySessions => failure(Code::InvalidRequest, &error.to_string()),
+ BundleError::Store(
+ error @ (StoreError::InvalidTransition(_) | StoreError::PrefixTooLarge),
+ ) => failure(Code::SourceUnreadable, &error.to_string()),
+ BundleError::Store(error) => stored(error),
+ }
+}
diff --git a/crates/runtime-host/src/server/sessions/bundle/binding.rs b/crates/runtime-host/src/server/sessions/bundle/binding.rs
new file mode 100644
index 0000000000..a4be9bcf5c
--- /dev/null
+++ b/crates/runtime-host/src/server/sessions/bundle/binding.rs
@@ -0,0 +1,115 @@
+/*
+ * 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.
+ */
+
+use super::{Result, source_error};
+use crate::{
+ server::Host,
+ session::{PreparedSession, SessionConfiguration},
+};
+use maka_event_log::bundle::StagedBundle;
+use maka_protocol::session::*;
+use serde::Deserialize;
+use std::collections::BTreeMap;
+
+/// Only user-facing metadata crosses the boundary. Source paths, credentials,
+/// executor/behavior choices, tool ceilings and execution policy are not grants.
+#[derive(Deserialize)]
+struct Metadata {
+ name: String,
+ #[serde(default)]
+ labels: Vec<String>,
+ #[serde(default)]
+ is_flagged: bool,
+ #[serde(default)]
+ title_is_manual: bool,
+}
+
+pub(super) async fn resolve(
+ host: &Host,
+ staged: &mut StagedBundle,
+ workspace: WorkspaceTarget,
+) -> Result<BTreeMap<String, SessionConfiguration>> {
+ let destination = super::super::workspace::resolve(host, &workspace).await?;
+ let mut configurations = BTreeMap::new();
+ let mut defaults: Option<SessionConfiguration> = None;
+ let ids: Vec<_> = staged
+ .summary()
+ .inventory
+ .sessions
+ .iter()
+ .map(|s| s.id.clone())
+ .collect();
+ for id in ids {
+ let metadata: Metadata = staged.configuration(&id).await.map_err(source_error)?;
+ let input = SessionCreateInput {
+ session_id: id.clone(),
+ workspace: workspace.clone(),
+ target: SessionCreateTarget::Model {
+ model_target: SessionModelTarget::Default,
+ },
+ name: Some(metadata.name),
+ labels: Some(
+ metadata
+ .labels
+ .into_iter()
+ .filter(|label| label != "mode:bot")
+ .collect(),
+ ),
+ mode: None,
+ thinking_level: SessionThinkingPreference::ModelDefault,
+ tool_profile: None,
+ sandbox_mode: None,
+ approval_policy: None,
+ collaboration_mode: None,
+ orchestration_mode: None,
+ };
+ let input = decode_session_create_input(&serde_json::to_value(input).map_err(|e| {
+ super::failure(
+ maka_protocol::OperationErrorCode::InvalidRequest,
+ &e.to_string(),
+ )
+ })?)
+ .map_err(super::super::invalid)?;
+ let prepared = PreparedSession::new(input).map_err(super::super::invalid)?;
+ let mut config = if let Some(defaults) = &defaults {
+ let mut config = prepared.bind(
+ destination.clone(),
+ defaults.target.clone(),
+ defaults.sandbox_mode,
+ );
+ config.thinking_level = defaults.thinking_level;
+ config
+ } else {
+ let config = super::super::create::resolve(
+ &host.configuration,
+ prepared,
+ SessionThinkingPreference::ModelDefault,
+ destination.clone(),
+ )
+ .await?;
+ defaults = Some(config.clone());
+ config
+ };
+ config.is_flagged = metadata.is_flagged;
+ config.title_is_manual = metadata.title_is_manual;
+ host.executions.validate_workspace(&config)?;
+ configurations.insert(id, config);
+ }
+ Ok(configurations)
+}
diff --git a/crates/runtime-host/src/server/sessions/bundle/file.rs b/crates/runtime-host/src/server/sessions/bundle/file.rs
new file mode 100644
index 0000000000..3de937919a
--- /dev/null
+++ b/crates/runtime-host/src/server/sessions/bundle/file.rs
@@ -0,0 +1,172 @@
+/*
+ * 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.
+ */
+
+use super::super::{Result, failure};
+use crate::server::Host;
+use maka_protocol::OperationErrorCode as Code;
+use std::{
+ io,
+ path::{Path, PathBuf},
+ pin::Pin,
+ task::{Context, Poll},
+};
+use tokio::{fs::File, io::AsyncWrite};
+
+pub(super) struct Output {
+ file: File,
+ temporary: tempfile::NamedTempFile,
+ destination: PathBuf,
+}
+
+impl Output {
+ pub async fn open(host: &Host, path: &str) -> Result<Self> {
+ let destination = destination(host, path).await?;
+ let target = destination.clone();
+ let temporary = tokio::task::spawn_blocking(move || {
+ tempfile::NamedTempFile::new_in(target.parent().expect("validated parent"))
+ })
+ .await
+ .map_err(join)?
+ .map_err(write)?;
+ let file = File::from_std(temporary.as_file().try_clone().map_err(write)?);
+ Ok(Self {
+ file,
+ temporary,
+ destination,
+ })
+ }
+
+ pub async fn publish(self) -> Result<u64> {
+ let Self {
+ file,
+ temporary,
+ destination,
+ } = self;
+ file.sync_all().await.map_err(write)?;
+ let bytes = file.metadata().await.map_err(write)?.len();
+ drop(file.into_std().await);
+ tokio::task::spawn_blocking(move || {
+ temporary
+ .persist_noclobber(&destination)
+ .map_err(|e| write(e.error))?;
+ #[cfg(unix)]
+ std::fs::File::open(destination.parent().expect("validated parent"))
+ .and_then(|directory| directory.sync_all())
+ .map_err(write)?;
+ Ok::<_, maka_protocol::OperationError>(bytes)
+ })
+ .await
+ .map_err(join)?
+ }
+}
+
+impl AsyncWrite for Output {
+ fn poll_write(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<io::Result<usize>> {
+ Pin::new(&mut self.file).poll_write(cx, bytes)
+ }
+ fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Pin::new(&mut self.file).poll_flush(cx)
+ }
+ fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Pin::new(&mut self.file).poll_shutdown(cx)
+ }
+}
+
+pub(super) async fn input(host: &Host, path: &str) -> Result<File> {
+ let path = tokio::fs::canonicalize(path).await.map_err(read)?;
+ permitted(host, &path)?;
+ if !tokio::fs::metadata(&path).await.map_err(read)?.is_file() {
+ return Err(failure(
+ Code::SourceUnreadable,
+ "Bundle must be a regular file",
+ ));
+ }
+ let file = File::open(path).await.map_err(read)?;
+ let metadata = file.metadata().await.map_err(read)?;
+ if !metadata.is_file() || metadata.len() > 2 * 1024 * 1024 * 1024 {
+ return Err(failure(
+ Code::SourceUnreadable,
+ "Bundle must be a regular file of at most 2 GiB",
+ ));
+ }
+ Ok(file)
+}
+
+async fn destination(host: &Host, path: &str) -> Result<PathBuf> {
+ let path = Path::new(path);
+ if !path.is_absolute() {
+ return Err(failure(
+ Code::InvalidRequest,
+ "Bundle path must be absolute",
+ ));
+ }
+ let parent = path
+ .parent()
+ .ok_or_else(|| failure(Code::InvalidRequest, "Bundle path has no parent"))?;
+ let name = path
+ .file_name()
+ .ok_or_else(|| failure(Code::InvalidRequest, "Bundle path has no filename"))?;
+ let destination = tokio::fs::canonicalize(parent)
+ .await
+ .map_err(write)?
+ .join(name);
+ permitted(host, &destination)?;
+ match tokio::fs::symlink_metadata(&destination).await {
+ Ok(_) => {
+ return Err(failure(
+ Code::OperationConflict,
+ "Bundle destination already exists",
+ ));
+ }
+ Err(error) if error.kind() == io::ErrorKind::NotFound => {}
+ Err(error) => return Err(write(error)),
+ }
+ Ok(destination)
+}
+
+fn permitted(host: &Host, path: &Path) -> Result<()> {
+ if path.starts_with(host.root.canonical_path()) || path.starts_with(host.control_directory()) {
+ return Err(failure(
+ Code::InvalidRequest,
+ "Session bundles cannot access Host state directories",
+ ));
+ }
+ Ok(())
+}
+
+fn read(error: io::Error) -> maka_protocol::OperationError {
+ failure(Code::SourceUnreadable, &error.to_string())
+}
+fn write(error: io::Error) -> maka_protocol::OperationError {
+ failure(
+ if error.kind() == io::ErrorKind::AlreadyExists {
+ Code::OperationConflict
+ } else {
+ Code::PersistenceFailed
+ },
+ &error.to_string(),
+ )
+}
+fn join(error: tokio::task::JoinError) -> maka_protocol::OperationError {
+ failure(Code::InternalFailure, &error.to_string())
+}
diff --git a/crates/runtime-host/tests/integration/main.rs b/crates/runtime-host/tests/integration/main.rs
index 21d5948605..a7e0546b14 100644
--- a/crates/runtime-host/tests/integration/main.rs
+++ b/crates/runtime-host/tests/integration/main.rs
@@ -86,6 +86,7 @@ mod resume;
mod retirement;
mod runtime_policy;
mod scheduler_plugin;
+mod session_bundle;
mod session_history;
mod session_recap_plugin;
mod session_removal;
diff --git a/crates/runtime-host/tests/integration/session_bundle.rs b/crates/runtime-host/tests/integration/session_bundle.rs
new file mode 100644
index 0000000000..0f12815051
--- /dev/null
+++ b/crates/runtime-host/tests/integration/session_bundle.rs
@@ -0,0 +1,214 @@
+/*
+ * 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.
+ */
+
+use super::support::client_probe::ClientFixture;
+mod fixtures;
+mod host;
+use fixtures::{configure, seed};
+use host::Running;
+use maka_client::Notification;
+use maka_protocol::{Operation, OperationErrorCode, session::*};
+use maka_runtime_host::session::SessionConfiguration;
+use serde_json::{Value, json};
+use std::time::Duration;
+
+#[tokio::test]
+async fn native_bundle_file_transfer_binds_local_authority_and_retries_after_restart() {
+ let source = ClientFixture::new("maka-bundle-source-");
+ let destination = ClientFixture::new("maka-bundle-destination-");
+ let log = source.log().await;
+ seed(&log, &source).await;
+ let inventory = log.preview_bundle("source").await.unwrap();
+ log.close().await.unwrap();
+ let path = source.workspace.join("history.maka-session");
+ let source_host = Running::open(&source).await;
+ let preview = source_host
+ .client
+ .request(
+ Operation::SessionBundlePreview,
+ json!({"sessionId":"source"}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ preview,
+ json!({"sessionCount":3,"subtreeDigest":inventory.subtree_digest})
+ );
+ let export = json!({"sessionId":"source","destination":path,"expectedSubtreeDigest":inventory.subtree_digest});
+ let result = source_host
+ .client
+ .request(Operation::SessionBundleExport, export.clone())
+ .await
+ .unwrap();
+ assert_eq!(result["sessionCount"], 3);
+ let bytes = tokio::fs::read(&path).await.unwrap();
+ assert_eq!(result["compressedBytes"], bytes.len());
+ assert_eq!(&bytes[..2], &[0x1f, 0x8b]);
+ rejected(
+ source_host
+ .client
+ .request(Operation::SessionBundleExport, export)
+ .await,
+ OperationErrorCode::OperationConflict,
+ );
+ assert_eq!(tokio::fs::read(&path).await.unwrap(), bytes);
+ source_host.close().await;
+
+ let mut target = Running::open(&destination).await;
+ configure(&target.client).await;
+ let request =
+ json!({"source":path,"workspace":{"kind":"host_path","path":destination.workspace}});
+ let invalid = source.workspace.join("truncated.maka-session");
+ tokio::fs::write(&invalid, &bytes[..bytes.len() / 2])
+ .await
+ .unwrap();
+ rejected(
+ target
+ .client
+ .request(
+ Operation::SessionBundleImport,
+ json!({
+ "source":invalid,"workspace":request["workspace"]
+ }),
+ )
+ .await,
+ OperationErrorCode::SourceUnreadable,
+ );
+ let before = target
+ .client
+ .session_catalog(SessionCatalogQueryInput::ListStart)
+ .await
+ .unwrap();
+ assert!(
+ matches!(before, SessionCatalogQueryResult::Page { sessions, .. } if sessions.is_empty())
+ );
+ let (first, concurrent) = tokio::join!(
+ target
+ .client
+ .request(Operation::SessionBundleImport, request.clone()),
+ target
+ .client
+ .request(Operation::SessionBundleImport, request.clone()),
+ );
+ let imported = first.unwrap();
+ assert_eq!(concurrent.unwrap(), imported, "concurrent exact retry");
+ assert_eq!(imported, json!({"sessionCount":3,"artifactFiles":0}));
+ assert_eq!(
+ target
+ .client
+ .request(
+ Operation::SessionBundlePreview,
+ json!({"sessionId":"source"})
+ )
+ .await
+ .unwrap(),
+ preview
+ );
+ loop {
+ let notice = tokio::time::timeout(Duration::from_secs(5), target.notices.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ if let Notification::Catalog(notice) = notice
+ && notice.kind == "session.catalog.changed"
+ {
+ assert!(
+ notice.session_id.is_none(),
+ "one whole-catalog invalidation"
+ );
+ break;
+ }
+ }
+ // A lost response must replay the accepted binding even if defaults disappear.
+ target
+ .client
+ .request(
+ Operation::ConnectionCatalogSetDefaultTarget,
+ json!({"expectedCatalogRevision":2,"target":null}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ target
+ .client
+ .request(Operation::SessionBundleImport, request.clone())
+ .await
+ .unwrap(),
+ imported
+ );
+ rejected(
+ target
+ .client
+ .request(
+ Operation::SessionBundleImport,
+ json!({
+ "source":path,"workspace":{"kind":"host_path","path":source.workspace}
+ }),
+ )
+ .await,
+ OperationErrorCode::OperationConflict,
+ );
+ target.close().await;
+
+ let log = destination.log().await;
+ assert_eq!(
+ log.preview_bundle("source").await.unwrap().sessions.len(),
+ 3
+ );
+ let config = log
+ .get_session::<SessionConfiguration>("source")
+ .await
+ .unwrap()
+ .unwrap()
+ .configuration;
+ assert_eq!(config.name, "Transferred title");
+ assert_ne!(config.sandbox_mode, SandboxMode::DangerFullAccess);
+ assert_eq!(config.approval_policy, ApprovalPolicy::OnRequest);
+ assert!(config.instructions.is_none() && config.bound_tools.is_none());
+ assert_eq!(config.target.model().unwrap().model, "fixture-model");
+ assert!(log.session_manager("child").await.unwrap().is_none());
+ assert!(log.session_manager("managed").await.unwrap().is_none());
+ assert!(log.unfinished_invocations(10).await.unwrap().is_empty());
+ log.read_model_context("source", None, 100, 65536)
+ .await
+ .unwrap();
+ log.close().await.unwrap();
+ let target = Running::open(&destination).await;
+ assert_eq!(
+ target
+ .client
+ .request(Operation::SessionBundleImport, request)
+ .await
+ .unwrap(),
+ imported
+ );
+ target.close().await;
+ let names: Vec<_> = std::fs::read_dir(&source.workspace)
+ .unwrap()
+ .map(|entry| entry.unwrap().file_name())
+ .collect();
+ assert_eq!(names.len(), 2, "no abandoned publication temporary files");
+}
+
+fn rejected(result: Result<Value, maka_client::RequestFailure>, code: OperationErrorCode) {
+ assert!(
+ matches!(&result, Err(maka_client::RequestFailure::Rejected(maka_client::ClientError::Rejected(error))) if error.code == code),
+ "{result:?}"
+ );
+}
diff --git a/crates/runtime-host/tests/integration/session_bundle/fixtures.rs b/crates/runtime-host/tests/integration/session_bundle/fixtures.rs
new file mode 100644
index 0000000000..388bff0522
--- /dev/null
+++ b/crates/runtime-host/tests/integration/session_bundle/fixtures.rs
@@ -0,0 +1,157 @@
+/*
+ * 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.
+ */
+
+use super::{ClientFixture, SessionConfiguration};
+use maka_client::Client;
+use maka_event_log::{
+ EventLog,
+ sessions::{PluginSession, SessionCopy},
+};
+use maka_plugins::{composition::Scope, storage::Namespace};
+use maka_protocol::{Operation, session::*};
+use maka_runtime::{event::*, session::CopyPurpose};
+use maka_runtime_host::session::{PreparedSession, SessionModel};
+use serde_json::json;
+
+pub(super) async fn seed(log: &EventLog, fixture: &ClientFixture) {
+ let path =
+ maka_fs_tools::workspace::project::host_path(&fixture.workspace.canonicalize().unwrap())
+ .unwrap()
+ .to_owned();
+ let prepared = PreparedSession::new(
+ serde_json::from_value(json!({
+ "sessionId":"source","name":"Transferred title",
+ "workspace":{"kind":"host_path","path":path},"modelTarget":{"kind":"default"},
+ "sandboxMode":"danger-full-access","approvalPolicy":{"kind":"never"}
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ let mut config = prepared.bind(
+ WorkspaceProjection {
+ target: WorkspaceTarget::HostPath { path: path.clone() },
+ host_cwd: path,
+ },
+ SessionModel {
+ connection_id: "source-only".into(),
+ connection_slug: "source-only".into(),
+ model: "source-model".into(),
+ },
+ SandboxMode::DangerFullAccess,
+ );
+ config.instructions = Some("Source instructions are not destination authority".into());
+ config.bound_tools = Some(["source-only-tool".into()].into());
+ log.create_session("source", "source", &config, 1)
+ .await
+ .unwrap();
+ let invocation = Invocation {
+ session_id: "source".into(),
+ turn_id: "turn".into(),
+ run_id: "run".into(),
+ invocation_id: "invocation".into(),
+ };
+ for fact in [
+ Fact::InvocationOpened {
+ configuration: None,
+ input: InvocationInput::Message {
+ content: "Retained conversation".into(),
+ source_messages: vec![],
+ request_fingerprint: None,
+ },
+ },
+ Fact::InvocationEnded {
+ outcome: InvocationOutcome::Completed,
+ },
+ ] {
+ log.append(&EventWrite::plain(RuntimeEvent::new(invocation.clone(), fact)).unwrap())
+ .await
+ .unwrap();
+ }
+ let revision = log
+ .get_session::<SessionConfiguration>("source")
+ .await
+ .unwrap()
+ .unwrap()
+ .revision;
+ log.create_plugin_session(
+ &PluginSession {
+ session_id: "managed".into(),
+ creator: Namespace::new("example.bundle", Scope::Profile).unwrap(),
+ fingerprint: "managed".into(),
+ managed: true,
+ authority_session_id: Some("source".into()),
+ },
+ &config,
+ 2,
+ )
+ .await
+ .unwrap();
+ log.copy_session(
+ SessionCopy {
+ source_session_id: "source".into(),
+ target_session_id: "child".into(),
+ expected_source_revision: revision,
+ purpose: CopyPurpose::Branch {
+ turn_id: None,
+ side_conversation: false,
+ },
+ },
+ &config,
+ 2,
+ )
+ .await
+ .unwrap();
+}
+
+pub(super) async fn configure(client: &Client) {
+ let created = client
+ .request(
+ Operation::ConnectionCatalogCreate,
+ json!({
+ "expectedCatalogRevision":0,"connection":{"slug":"bundle","name":"Bundle fixture",
+ "providerType":"openai-compatible","baseUrl":"http://127.0.0.1:1/v1",
+ "enabled":true,"enabledModelIds":["fixture-model"]}
+ }),
+ )
+ .await
+ .unwrap();
+ let id = &created["connection"]["connectionId"];
+ client
+ .request(
+ Operation::CredentialVaultSet,
+ json!({
+ "locator":{"scope":"connection","connectionId":id,"kind":"api_key"},
+ "expected":null,"secret":"unused-fixture",
+ "expectedConnection":{"connectionId":id,"revision":1,"slug":"bundle",
+ "providerType":"openai-compatible","effectiveBaseUrl":"http://127.0.0.1:1/v1"}
+ }),
+ )
+ .await
+ .unwrap();
+ client
+ .request(
+ Operation::ConnectionCatalogSetDefaultTarget,
+ json!({
+ "expectedCatalogRevision":created["catalogRevision"],
+ "target":{"connectionId":id,"modelId":"fixture-model"}
+ }),
+ )
+ .await
+ .unwrap();
+}
diff --git a/crates/runtime-host/tests/integration/session_bundle/host.rs b/crates/runtime-host/tests/integration/session_bundle/host.rs
new file mode 100644
index 0000000000..7d3717fdd5
--- /dev/null
+++ b/crates/runtime-host/tests/integration/session_bundle/host.rs
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+use super::super::support::{client_probe::ClientFixture, peer::Peer};
+use maka_client::{Client, Notification};
+use maka_runtime_host::server::{Host, HostError, local::LocalListener};
+use std::time::Duration;
+use tokio_util::sync::CancellationToken;
+
+pub(super) struct Running {
+ pub client: Client,
+ pub notices: tokio::sync::mpsc::Receiver<Notification>,
+ stop: CancellationToken,
+ server: tokio::task::JoinHandle<Result<(), HostError>>,
+}
+impl Running {
+ pub async fn open(fixture: &ClientFixture) -> Self {
+ let owner = fixture.owner();
+ let root = owner.root_id().to_owned();
+ let host = Host::open(owner).await.unwrap();
+ let (peer, hello) = Peer::handshake(host.clone(), "bundle-bootstrap").await;
+ peer.close().await;
+ #[cfg(unix)]
+ let endpoint = fixture.workspace.parent().unwrap().join("h.sock");
+ #[cfg(windows)]
+ let endpoint =
+ std::path::PathBuf::from(format!(r"\\.\pipe\maka-bundle-{}", uuid::Uuid::new_v4()));
+ let stop = CancellationToken::new();
+ let server = tokio::spawn(
+ LocalListener::bind(&endpoint)
+ .unwrap()
+ .serve(host, stop.clone()),
+ );
+ let (client, notices) = Client::connect(
+ maka_client::local::open_stream(&endpoint).await.unwrap(),
+ &root,
+ hello["hostEpoch"].as_str().unwrap(),
+ maka_client::Operations,
+ )
+ .await
+ .unwrap();
+ Self {
+ client,
+ notices,
+ stop,
+ server,
+ }
+ }
+ pub async fn close(mut self) {
+ self.client.disconnect();
+ self.stop.cancel();
+ tokio::time::timeout(Duration::from_secs(10), &mut self.server)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap();
+ }
+}
+impl Drop for Running {
+ fn drop(&mut self) {
+ self.client.disconnect();
+ self.stop.cancel();
+ }
+}
diff --git a/crates/tui/src/lib.rs b/crates/tui/src/lib.rs
index df8c7688f0..bf194521fc 100644
--- a/crates/tui/src/lib.rs
+++ b/crates/tui/src/lib.rs
@@ -1090,11 +1090,14 @@ pub async fn run(options: Options) -> Result<(), Error> {
app.connections.refresh();
app.chat.context.refresh();
}
- if notice.kind == "session.catalog.changed"
- && let Some(id) = ¬ice.session_id {
+ if notice.kind == "session.catalog.changed" {
+ if let Some(id) = ¬ice.session_id {
app.sessions.invalidate(id);
- app.inbox.refresh();
+ } else {
+ app.sessions.refresh();
}
+ app.inbox.refresh();
+ }
app.notice = Some(Notice::Catalog { kind: notice.kind, revision: notice.revision.to_string() });
}
Some(Notification::Observation(frame)) => {
diff --git a/docs/rust-parity.md b/docs/rust-parity.md
index 4285f59ce3..f660427e2f 100644
--- a/docs/rust-parity.md
+++ b/docs/rust-parity.md
@@ -94,7 +94,7 @@ implementations; wire adapters may retain existing client vocabulary.
| Background health | BackgroundTaskHealth process and endpoint checks. | **Plugin + Host.** Health interpretation and Tool in a plugin; Host exposes authorized resource observations and bounded probes. A stored PID is not resource ownership. |
| Session lineage | Public Rust/JS history copying and source reads, native branch/revision create/abandon, independent inherited pruning, Desktop canonical-input editing and complete durable drafts are implemented. Regeneration is removed; edits use revision and resend. | **Host.** One transactional lineage and workspace authority; plugins request changes through commands, not private lineage storage. |
| Session lifecycle | Native and public plugin removal/preview/receipt APIs, atomic family retirement and queued cancellation, restart cleanup and shared-worktree ownership are implemented. Unreferenced conversation bodies, tool payloads and request surfaces are reclaimed in restartable batches while accounting, receipts and referenced history survive. Shared Session queries remain. | **Host.** Preserve referenced history and accepted receipts; unknown process cleanup must not delete its [...]
-| Session transfer | Public Rust/JS historical import supports bounded staging, exact retries, current-ceiling checks and atomic publication. The built-in plugin owns Codex, Claude Code and OpenCode conversion, catalogs, source configuration and durable intents. Its Desktop settings page and standalone Remote share destination reauthorization and receipt recovery. Dedicated TUI import UI and native bundle export/import remain. | **Plugin + Host.** Adapters own discovery and parsing; Host [...]
+| Session transfer | Public Rust/JS historical import supports bounded staging, exact retries, current-ceiling checks and atomic publication. The built-in plugin owns Codex, Claude Code and OpenCode conversion, catalogs, source configuration and durable intents. Its Desktop settings page and standalone Remote share destination reauthorization and receipt recovery. Native bundles preserve original history/proofs, archived output, attachments and accounting through bounded compression and [...]
| Runtime policy | Shell/external-agent consumers and ordinary named tool profiles. | **Split.** Shell launch policy and capability ceilings stay in Host. External-agent settings belong to their domain. Profiles contribute definitions; Host applies the intersection at admission and per-step capture. Storing settings alone is insufficient. |
| Access / collaboration | Credential rotation prepare/revoke; principal revoke; collaboration access, invitation, grant revoke, principal rename/revoke; Turn-request create/query/decide/acknowledge/withdraw. | **Host.** Reuse credential and durable admission authority. Plugins may provide workflows/UI but cannot decide grants, bypass revocation or own canonical accepted Turn requests. |
| Peer Mesh | Create/query/invite/join/leave/remove/close/reconcile, rename/display-name and transit control. | **Host for this rewrite.** Identity, routing and transport recovery must work during plugin recovery/unavailability. Do not add a transport-plugin platform to complete these protocols. |
diff --git a/docs/rust-parity.zh-CN.md b/docs/rust-parity.zh-CN.md
index fb17a7c372..c9c8624127 100644
--- a/docs/rust-parity.zh-CN.md
+++ b/docs/rust-parity.zh-CN.md
@@ -85,7 +85,7 @@ runtime 契约不能反向依赖插件实现,协议适配层可以保留现有
| 后台健康 | `maka.background-health` 已提供 `BackgroundTaskHealth` Agent 工具,Desktop 使用现有工具结果展示;进程状态与可选 HTTP 端点探测分开,日志默认省略。 | **插件 + Host。** 复用授权 `Read(ref)` 和 HTTP 服务;HEAD/GET fallback、不跟随重定向,等待网络授权不计入插件超时。重启后的 orphaned 如实返回;端点成功不证明进程拥有监听端口。 |
| Session 谱系 | 已实现公共 Rust/JS 历史复制和原始输入读取、原生分支/修订创建与放弃、继承历史独立裁剪、Desktop 规范输入编辑及完整持久草稿。已移除 regenerate,修改请求使用编辑重发。 | **Host。** 谱系及工作区只有一个事务权威;插件请求命令,不在私有存储中重做谱系。 |
| Session 生命周期 | 已实现原生与公共插件删除/预览/回执接口、原子家族退休及队列取消、重启清理和共享 worktree 所有权。无引用对话正文、工具载荷与请求表面已支持可恢复的分批回收,保留计量、回执及被引用历史;shared 查询仍待完成。 | **Host。** 保留被引用历史及已接受回执;进程清理不确定时不得删除工作目录。shared 查询需要真实协作授权。 |
-| Session 迁入迁出 | 公共 Rust/JS 历史导入已支持有界暂存、精确重试、当前权限上限检查和原子发布。内置插件拥有 Codex、Claude Code、OpenCode 的转换、目录、来源配置及持久意图;Desktop 设置页与独立 Remote 共用目标重新授权和回执恢复。专用 TUI 导入界面及原生 bundle 导入/导出仍待完成。 | **插件 + Host。** adapter 拥有发现与解析;Host 拥有规范材料、身份和发布。导入对话参与历史、分支及压缩,不声称发生了本机执行或用量。原生 bundle 格式仍是 Host 契约。 |
+| Session 迁入迁出 | 公共 Rust/JS 历史导入已支持有界暂存、精确重试、当前权限上限检查和原子发布。内置插件拥有 Codex、Claude Code、OpenCode 的转换、目录、来源配置及持久意图;Desktop 设置页与独立 Remote 共用目标重新授权和回执恢复。原生 bundle 通过有界压缩和原子导入回执保留原始历史/证明、归档输出、附件和计量。Desktop 使用 Host 清单确认,并明确选择目标工作区;不恢复源权限、插件所有权或待执行工作。专用 TUI 导入界面仍待完成。 | **插件 + Host。** adapter 拥有发现与解析;Host 拥有规范材料、身份和发布。导入对话参与历史、分支及压缩,不声称发生了本机执行或用量。原生 bundle 格式仍是 Host 契约。 |
| Runtime policy | shell/external-agent 消费,普通 named tool profiles。 | **拆分。** shell 启动策略和能力上限留在 Host;外部 agent 设置由对应领域消费。Profile 提供定义,Host 在准入和每步捕获时取能力交集。只保存设置不算完成。 |
| 接入/协作 | credential rotation prepare/revoke、principal revoke;collaboration access、邀请、grant revoke、principal rename/revoke;Turn-request create/query/decide/acknowledge/withdraw。 | **Host。** 复用凭据和持久化准入权威。插件可以提供流程/UI,但不能决定授权、绕过撤销或拥有规范的已接受 Turn request。 |
| Peer Mesh | create/query/invite/join/leave/remove/close/reconcile,rename/display-name、transit 控制。 | **本次重写保留 Host 实现。** 身份、路由与传输恢复必须在插件不可用时工作,不为补这些协议再造传输插件平台。 |
diff --git a/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts b/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts
index f0f735a388..1ade844f80 100644
--- a/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts
+++ b/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts
@@ -247,7 +247,9 @@ test('one Local IPC owner and one authenticated WebSocket Client control the sam
(grant) => grant.kind === 'session_observation',
)!;
const guestCatalogChanged = new Promise<string>((resolve) => {
- guest?.subscribeSessionCatalogChanges((frame) => resolve(frame.sessionId));
+ guest?.subscribeSessionCatalogChanges((frame) => {
+ if (frame.sessionId) resolve(frame.sessionId);
+ });
});
await local.request('collaboration.grant.revoke', {
grantId: observationGrant.grantId,
@@ -271,7 +273,9 @@ test('one Local IPC owner and one authenticated WebSocket Client control the sam
);
const catalogChanged = new Promise<string>((resolve) => {
- local?.subscribeSessionCatalogChanges((frame) => resolve(frame.sessionId));
+ local?.subscribeSessionCatalogChanges((frame) => {
+ if (frame.sessionId) resolve(frame.sessionId);
+ });
});
const renamed = await remote.request('session.metadata.update', {
sessionId: 'shared-session',
diff --git a/packages/runtime-host/src/__tests__/host-kernel.test.ts b/packages/runtime-host/src/__tests__/host-kernel.test.ts
index b9c2cd4658..3480dcd172 100644
--- a/packages/runtime-host/src/__tests__/host-kernel.test.ts
+++ b/packages/runtime-host/src/__tests__/host-kernel.test.ts
@@ -3179,7 +3179,9 @@ describe('non-serving Runtime Host kernel', () => {
activeConnection.subscribeConfigurationChanges(resolve);
});
const observedCatalog = new Promise<string>((resolve) => {
- activeConnection.subscribeSessionCatalogChanges(({ sessionId }) => resolve(sessionId));
+ activeConnection.subscribeSessionCatalogChanges(({ sessionId }) => {
+ if (sessionId) resolve(sessionId);
+ });
});
releaseFactory();
host = await hostTask;
diff --git a/packages/runtime-host/src/__tests__/session-catalog-two-client-uds.test.ts b/packages/runtime-host/src/__tests__/session-catalog-two-client-uds.test.ts
index a1c1aa27c4..74f84ce5a5 100644
--- a/packages/runtime-host/src/__tests__/session-catalog-two-client-uds.test.ts
+++ b/packages/runtime-host/src/__tests__/session-catalog-two-client-uds.test.ts
@@ -92,7 +92,9 @@ test('two Clients share stable Session creation, CAS configuration, and catalog
const tui = await connectClient(root);
try {
const catalogChanged = new Promise<string>((resolve) => {
- tui.subscribeSessionCatalogChanges(({ sessionId }) => resolve(sessionId));
+ tui.subscribeSessionCatalogChanges(({ sessionId }) => {
+ if (sessionId) resolve(sessionId);
+ });
});
const createInput: SessionCreateInput = {
sessionId: 'stable-session',
diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts
index 75e286f54a..059fcfd458 100644
--- a/packages/runtime-host/src/protocol/index.ts
+++ b/packages/runtime-host/src/protocol/index.ts
@@ -109,8 +109,8 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const;
export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
// Increment when the same protocol version no longer guarantees safe Client-Host
// interoperability. Mismatches are rejected before domain commands are admitted.
-// Rust preview: no turn regeneration operation; requires the matching client.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 180 as const;
+// Native bundle bindings and whole-catalog invalidation require matching clients.
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 182 as const;
export const RUNTIME_HOST_MAX_MESSAGE_BYTES = 768 * 1024;
export const RUNTIME_HOST_MAX_IN_FLIGHT_DOMAIN_REQUESTS = 64;
export const INTERACTIVE_RUNTIME_HOST_COMPOSITION_ID = 'maka.interactive' as const;
diff --git a/packages/runtime-host/src/protocol/operations.ts b/packages/runtime-host/src/protocol/operations.ts
index fec373ef25..047ecbe4a9 100644
--- a/packages/runtime-host/src/protocol/operations.ts
+++ b/packages/runtime-host/src/protocol/operations.ts
@@ -355,6 +355,7 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([
'session.recap.generate',
'session.remove',
'session.remove.preview',
+ 'session-bundle.preview',
'session.remove.query',
'session.revision.abandon',
'session.revision.create',
diff --git a/packages/runtime-host/src/protocol/session-bundle.ts b/packages/runtime-host/src/protocol/session-bundle.ts
index 1e80121b21..574b12b0ce 100644
--- a/packages/runtime-host/src/protocol/session-bundle.ts
+++ b/packages/runtime-host/src/protocol/session-bundle.ts
@@ -24,7 +24,9 @@ import {
requireShapedRecord,
requireUtf8String,
} from './codec.js';
-import { defineHostPathOperation } from './operation-spec.js';
+import { defineHostPathOperation, defineOperation } from './operation-spec.js';
+import { invalidProtocolFrame } from './errors.js';
+import { decodeHostPath, decodeWorkspaceTarget, type WorkspaceTarget } from './workspace.js';
/** A destination or source path, named on the Host's filesystem. */
export const SESSION_BUNDLE_PATH_MAX_BYTES = 4 * 1024;
@@ -48,6 +50,7 @@ const BUNDLE_ERRORS = [
// The subtree changed between what the caller confirmed and what was fenced.
'candidate_set_stale',
'persistence_failed',
+ 'commit_outcome_unknown',
'internal_failure',
] as const;
@@ -58,12 +61,7 @@ export interface SessionBundleExportInput {
/**
* Digest of the subtree the caller told the user this would carry.
*
- * `sha256` over the Session ids, sorted and newline-joined, root included.
- * The caller reads them from the catalog it holds and the Host discovers the
- * real subtree later, under its fence; a child finishing in that gap would
- * put Sessions in the file that nobody was asked about. A digest rather than
- * a count because two subtrees of the same size are not the same subtree,
- * and rather than the ids themselves because this has to stay bounded.
+ * Returned by session-bundle.preview. Export rejects a changed subtree.
*/
readonly expectedSubtreeDigest?: string;
}
@@ -77,6 +75,8 @@ export interface SessionBundleExportResult {
export interface SessionBundleImportInput {
/** Absolute path of the `.maka-session` file to read. */
readonly source: string;
+ /** Destination binding; source execution settings are never imported as grants. */
+ readonly workspace: WorkspaceTarget;
}
/**
@@ -93,6 +93,29 @@ export interface SessionBundleImportResult {
}
export const SESSION_BUNDLE_OPERATION_SPECS = {
+ 'session-bundle.preview': defineOperation<
+ { readonly sessionId: string },
+ { readonly sessionCount: number; readonly subtreeDigest: string },
+ (typeof BUNDLE_ERRORS)[number]
+ >({
+ mode: 'query',
+ availability: 'ready',
+ errors: BUNDLE_ERRORS,
+ decodeInput: (value) => {
+ const record = requireExactRecord(value, 'Session bundle preview input', ['sessionId']);
+ return { sessionId: requireEntityId(record.sessionId, 'Session id') };
+ },
+ decodeOutput: (value) => {
+ const record = requireExactRecord(value, 'Session bundle preview result', [
+ 'sessionCount',
+ 'subtreeDigest',
+ ]);
+ return {
+ sessionCount: requireCount(record.sessionCount, 'Session bundle Session count'),
+ subtreeDigest: decodeDigest(record.subtreeDigest),
+ };
+ },
+ }),
// Both name paths on the Host's filesystem: the desktop picks them with a
// native dialog, which is the Host's machine in the local case and would be
// the remote one otherwise.
@@ -129,18 +152,14 @@ export function decodeSessionBundleExportInput(value: unknown): SessionBundleExp
);
return {
sessionId: requireEntityId(record.sessionId, 'Session id'),
- destination: requireUtf8String(
+ destination: decodeBundlePath(
record.destination,
'Session bundle destination',
SESSION_BUNDLE_PATH_MAX_BYTES,
),
...(Object.hasOwn(record, 'expectedSubtreeDigest')
? {
- expectedSubtreeDigest: requireUtf8String(
- record.expectedSubtreeDigest,
- 'Session bundle expected subtree digest',
- SESSION_BUNDLE_DIGEST_MAX_BYTES,
- ),
+ expectedSubtreeDigest: decodeDigest(record.expectedSubtreeDigest),
}
: {}),
};
@@ -158,13 +177,10 @@ export function decodeSessionBundleExportResult(value: unknown): SessionBundleEx
}
export function decodeSessionBundleImportInput(value: unknown): SessionBundleImportInput {
- const record = requireExactRecord(value, 'Session bundle import input', ['source']);
+ const record = requireExactRecord(value, 'Session bundle import input', ['source', 'workspace']);
return {
- source: requireUtf8String(
- record.source,
- 'Session bundle source',
- SESSION_BUNDLE_PATH_MAX_BYTES,
- ),
+ workspace: decodeWorkspaceTarget(record.workspace),
+ source: decodeBundlePath(record.source, 'Session bundle source', SESSION_BUNDLE_PATH_MAX_BYTES),
};
}
@@ -178,3 +194,15 @@ export function decodeSessionBundleImportResult(value: unknown): SessionBundleIm
artifactFiles: requireCount(record.artifactFiles, 'Session bundle artifact files'),
};
}
+
+function decodeDigest(value: unknown): string {
+ const digest = requireUtf8String(value, 'Subtree digest', SESSION_BUNDLE_DIGEST_MAX_BYTES);
+ if (!/^[0-9a-f]{64}$/.test(digest)) throw invalidProtocolFrame('Invalid subtree digest');
+ return digest;
+}
+
+function decodeBundlePath(value: unknown, label: string, maxBytes: number): string {
+ const path = decodeHostPath(value, label, maxBytes);
+ if (path.includes('\0')) throw invalidProtocolFrame(`${label} contains NUL`);
+ return path;
+}
diff --git a/packages/runtime-host/src/protocol/session-catalog-change.ts b/packages/runtime-host/src/protocol/session-catalog-change.ts
index f0c7d91bcc..2476bc9ff5 100644
--- a/packages/runtime-host/src/protocol/session-catalog-change.ts
+++ b/packages/runtime-host/src/protocol/session-catalog-change.ts
@@ -17,23 +17,27 @@
* under the License.
*/
-import { requireCount, requireExactRecord, requireId } from './codec.js';
+import { requireCount, requireShapedRecord, requireId } from './codec.js';
export interface SessionCatalogChangedFrame {
readonly kind: 'session.catalog.changed';
readonly revision: number;
- readonly sessionId: string;
+ /** Omitted when the whole catalog changed atomically. */
+ readonly sessionId?: string;
}
export function decodeSessionCatalogChangedFrame(value: unknown): SessionCatalogChangedFrame {
- const frame = requireExactRecord(value, 'Session catalog changed frame', [
- 'kind',
- 'revision',
- 'sessionId',
- ]);
+ const frame = requireShapedRecord(
+ value,
+ 'Session catalog changed frame',
+ ['kind', 'revision'],
+ ['sessionId'],
+ );
return {
kind: 'session.catalog.changed',
revision: requireCount(frame.revision, 'Session catalog change revision'),
- sessionId: requireId(frame.sessionId, 'sessionId'),
+ ...(Object.hasOwn(frame, 'sessionId')
+ ? { sessionId: requireId(frame.sessionId, 'sessionId') }
+ : {}),
};
}
diff --git a/packages/runtime-host/src/server/session-bundle-coordinator.ts b/packages/runtime-host/src/server/session-bundle-coordinator.ts
index b3a17c8a3b..32b232e49f 100644
--- a/packages/runtime-host/src/server/session-bundle-coordinator.ts
+++ b/packages/runtime-host/src/server/session-bundle-coordinator.ts
@@ -64,6 +64,10 @@ export interface HostSessionBundleCoordinatorOptions {
export class HostSessionBundleCoordinator {
readonly handlers: SessionBundleOperationHandlerMap = {
+ 'session-bundle.preview': async () => ({
+ ok: false,
+ error: { code: 'operation_unavailable', message: 'Native bundles require the Rust Host' },
+ }),
'session-bundle.export': (input) => this.export(input),
'session-bundle.import': (input) => this.import(input),
};
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org