Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,6 @@ test('drives the renderer Session execution facade through real UDS framing', as
{
client,
observer,
observations: observer,
attachmentApprovals: createAttachmentApprovalRegistry(),
emitSessionsChanged() {},
stat: async () => ({ size: 0 }),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import assert from 'node:assert/strict';
import test from 'node:test';
import {
decodeCollaborationInvitationCode,
encodeCollaborationInvitationCode,
} from '@maka/runtime-host/protocol';
import type { IpcHandler, ReconnectableReadIpcMain } from '../ipc-reconnect-policy.js';
import { decodeDesktopCollaborationInvitation } from '../runtime-host-collaboration-invitation.js';
import { registerRuntimeHostCollaborationIpc } from '../runtime-host-collaboration-ipc-main.js';

const ROOT_ID = 'a'.repeat(64);

test('requires Owner confirmation before issuing a plaintext collaboration invitation', async () => {
const handlers = new Map<string, IpcHandler>();
const ipcMain: ReconnectableReadIpcMain = {
handle(channel, listener) {
handlers.set(channel, listener);
},
};
let prepareCalls = 0;
const client = {
async prepareCollaborationInvitation(sessionId: string, grantKinds: readonly string[]) {
prepareCalls += 1;
assert.equal(sessionId, 'session-1');
assert.deepEqual(grantKinds, ['session_observation']);
return {
invitationCode: encodeCollaborationInvitationCode({
schemaVersion: 1,
rootId: ROOT_ID,
credential: 'guest-token',
}),
principalId: 'guest-1',
expiresAt: '2026-08-31T00:00:00.000Z',
grants: [],
};
},
async queryCollaborationAccess() {
return { principals: [], grants: [] };
},
async revokeCollaborationPrincipal() {
return { revoked: false };
},
};
registerRuntimeHostCollaborationIpc(
client as unknown as Parameters<typeof registerRuntimeHostCollaborationIpc>[0],
ipcMain,
async () => ({
name: 'Lab',
transport: {
kind: 'plaintext',
url: 'ws://runtime.example.com',
acknowledgement: 'plaintext-bearer-v1',
},
}),
);
const prepare = handlers.get('session-collaboration:prepare');
assert.ok(prepare);

assert.deepEqual(await prepare({} as Parameters<IpcHandler>[0], 'session-1', false), {
kind: 'insecure_confirmation_required',
});
assert.equal(prepareCalls, 0);

const result = await prepare({} as Parameters<IpcHandler>[0], 'session-1', true);
assert.equal(prepareCalls, 1);
assert.equal((result as { kind?: unknown }).kind, 'prepared');
const invitation = (result as {
invitation: { invitationCode: string };
}).invitation;
const bundle = decodeDesktopCollaborationInvitation(invitation.invitationCode);
assert.equal(decodeCollaborationInvitationCode(bundle.invitationCode).rootId, ROOT_ID);
assert.equal(bundle.target.transport.kind, 'plaintext');
});
174 changes: 172 additions & 2 deletions apps/desktop/src/main/__tests__/runtime-host-desktop-candidate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import test from 'node:test';
import type { IpcMain } from 'electron';
import type { BotIncomingMessage, BotRegistry } from '@maka/runtime/bots';
import type { ComputerUseToolSet } from '@maka/runtime/computer-use-tools';
import type { ShellRunUpdate } from '@maka/core/events';
import type { MakaTool } from '@maka/runtime/tool-runtime';
import type {
ClientCapabilityProvider,
Expand Down Expand Up @@ -183,6 +184,68 @@ test('owns one complete Desktop candidate generation and can restart cleanly', a
assert.equal(ipc.size, 0);
});

test('registers only shared observation IPC and consumes scoped catalog changes for a Guest', async () => {
const ipc = ipcHarness();
const sharedResource = sharedShellRunUpdate('session-guest');
const host = connectionHarness('guest', { runtimeResourceUpdate: sharedResource });
const changes: Array<{ reason: string; sessionId?: string }> = [];
const rendererEvents: Array<{ channel: string; payload: unknown }> = [];
const candidate = await createCandidate(
host.connection,
{
...deps(ipc),
emitSessionsChanged: (_scope, reason, sessionId) => {
changes.push({ reason, ...(sessionId === undefined ? {} : { sessionId }) });
},
renderer: {
send(channel, _scope, payload) {
rendererEvents.push({ channel, payload });
},
},
},
undefined,
'external',
'remote',
'session_guest',
);

assert.deepEqual(
((await ipc.invoke('sessions:list')) as SessionCatalogProjection[]).map(({ id }) => id),
['session-guest'],
);
assert.equal(ipc.channels.includes('sessions:observe'), true);
assert.equal(ipc.channels.includes('sessions:transcript:open'), true);
assert.equal(ipc.channels.includes('sessions:send'), false);
assert.equal(ipc.channels.includes('sessions:stop'), false);
assert.equal(ipc.channels.includes('tasks:list'), false);
assert.equal(ipc.channels.includes('attachments:readBytes'), true);
assert.deepEqual(await ipc.invoke('shell-runs:list', 'session-guest'), [sharedResource]);
assert.equal(ipc.channels.includes('shell-runs:attach'), false);
await ipc.invoke('sessions:observe', 'session-guest', 'guest-observer');
host.pushSubscriptionFrame({
kind: 'subscription.session_domain_changed',
hostEpoch: 'host-guest',
subscriptionId: 'subscription-guest',
sequence: 1,
sessionId: 'session-guest',
domain: 'runtime_resource',
resources: [
{ sourceSessionId: 'session-guest', ref: sharedResource.result.ref },
],
});
await waitFor(() =>
rendererEvents.some(
({ channel, payload }) =>
channel === 'shell-runs:update' &&
(payload as ShellRunUpdate).result.ref === sharedResource.result.ref,
),
);
host.publishSessionCatalogChange('session-guest');
assert.deepEqual(changes, [{ reason: 'updated', sessionId: 'session-guest' }]);

await candidate.close();
});

test('rejects a stale Host identity when raw Session IDs collide', async () => {
const ipc = ipcHarness();
const browserReleased: string[] = [];
Expand Down Expand Up @@ -778,6 +841,48 @@ test('retries candidate startup when a restored observation cannot seed', async
await observations.close();
});

test('drops a stale shared Session observation when Guest access is gone', async () => {
const observations = new RuntimeHostSessionObservationRegistry();
const firstIpc = ipcHarness();
const firstHost = connectionHarness('shared-before-revoke', {
sessionId: 'session-1',
subscriptionSnapshot: continuitySnapshot(),
});
const firstCandidate = await createCandidate(
firstHost.connection,
deps(firstIpc),
observations,
'external',
'remote',
'session_guest',
);
await firstIpc.invoke('sessions:observe', 'session-1', 'observer-1');
await firstCandidate.close();

const changes: Array<{ reason: string; sessionId?: string }> = [];
const revokedHost = connectionHarness('shared-after-revoke', {
sharedSessionAvailable: false,
});
const candidate = await createCandidate(
revokedHost.connection,
{
...deps(ipcHarness()),
emitSessionsChanged: (_scope, reason, sessionId) => {
changes.push({ reason, ...(sessionId === undefined ? {} : { sessionId }) });
},
},
observations,
'external',
'remote',
'session_guest',
);

assert.deepEqual(observations.trackedSessionIds(), []);
assert.deepEqual(changes, [{ reason: 'deleted', sessionId: 'session-1' }]);
await candidate.close();
await observations.close();
});

type IpcHandler = Parameters<Pick<IpcMain, 'handle'>['handle']>[1];

function ipcHarness(onSend?: (channel: string, payload: unknown) => void) {
Expand Down Expand Up @@ -898,6 +1003,8 @@ function connectionHarness(
activeAssistantStreams?: readonly SessionAssistantStreamIdentity[];
subscriptionError?: Error;
runtimeResourcePty?: ReturnType<typeof ptySnapshot>;
runtimeResourceUpdate?: ShellRunUpdate;
sharedSessionAvailable?: boolean;
} = {},
) {
let resolveClosed: (() => void) | undefined;
Expand All @@ -909,6 +1016,7 @@ function connectionHarness(
resolveTurnStarted = resolve;
});
const closeSubscriptions = new Set<() => void>();
const sessionCatalogListeners = new Set<(frame: { sessionId: string }) => void>();
let provider: ClientCapabilityProvider | undefined;
let capabilityRegistrations = 0;
let capabilityUnregistrations = 0;
Expand All @@ -934,6 +1042,21 @@ function connectionHarness(
nextCursor: null,
};
}
if (operation === 'session.shared.query') {
if (options.sharedSessionAvailable === false) return { session: null };
const id = options.sessionId ?? `session-${label}`;
return {
session: {
kind: 'shared_session',
id,
revision: 1,
createdAt: 1,
activityAt: 1,
name: `Session ${label}`,
status: 'idle',
},
};
}
if (operation === 'session.create') {
return session((input as { sessionId: string }).sessionId);
}
Expand Down Expand Up @@ -967,11 +1090,23 @@ function connectionHarness(
};
}
if (operation === 'runtime.resource.query') {
const query = input as { kind: string; sessionId: string; ref?: string };
if (query.kind === 'get') {
return {
kind: 'resource',
sessionId: query.sessionId,
revision: catalogRevision(`${label}-resource`),
resource:
options.runtimeResourceUpdate?.result.ref === query.ref
? options.runtimeResourceUpdate
: null,
};
}
return {
kind: 'page',
sessionId: (input as { sessionId: string }).sessionId,
sessionId: query.sessionId,
revision: catalogRevision(`${label}-resource`),
resources: [],
resources: options.runtimeResourceUpdate ? [options.runtimeResourceUpdate] : [],
nextCursor: null,
};
}
Expand Down Expand Up @@ -1052,6 +1187,10 @@ function connectionHarness(
capabilityUnregistrations += 1;
return { registrationId: `registration-${label}`, revision: 2 };
},
subscribeSessionCatalogChanges: (listener: (frame: { sessionId: string }) => void) => {
sessionCatalogListeners.add(listener);
return () => sessionCatalogListeners.delete(listener);
},
close: async () => {
closeCalls += 1;
for (const closeSubscription of closeSubscriptions) closeSubscription();
Expand All @@ -1074,6 +1213,9 @@ function connectionHarness(
assert.ok(activeSubscriptionFrames);
activeSubscriptionFrames.push(frame);
},
publishSessionCatalogChange: (sessionId: string) => {
for (const listener of sessionCatalogListeners) listener({ sessionId });
},
get capabilityRegistrations() {
return capabilityRegistrations;
},
Expand Down Expand Up @@ -1160,6 +1302,34 @@ function ptySnapshot(ref: string, buffer: string) {
};
}

function sharedShellRunUpdate(sessionId: string): ShellRunUpdate {
return {
sessionId,
ownership: { kind: 'local' },
sourceTurnId: 'turn-shared',
sourceToolCallId: 'tool-shared',
result: {
kind: 'shell_run',
ref: 'maka://runtime/background-tasks/shared',
mode: 'pipes',
status: 'running',
cwd: '/workspace',
cmd: 'echo shared',
startedAt: 1,
updatedAt: 1,
revision: 1,
output: {
mode: 'pipes',
stdout: 'shared output',
stderr: '',
stdoutTruncated: false,
stderrTruncated: false,
redacted: false,
},
},
};
}

class AsyncFrameQueue implements AsyncIterable<SubscriptionFrame> {
readonly #frames: SubscriptionFrame[] = [];
readonly #waiters: Array<
Expand Down
Loading
Loading