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
2 changes: 1 addition & 1 deletion apps/desktop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ npm Electron bundle, which macOS will not accept as a durable grant.
| Suffix | Role | Examples |
|---|---|---|
| `runtime-host-*-ipc-main.ts` | Projects one Runtime Host protocol domain onto renderer IPC | `runtime-host-connections-ipc-main`, `runtime-host-session-execution-ipc-main`, `runtime-host-settings-ipc-main` |
| `*-ipc-main.ts` | Registers a client-local Electron or OS-facing IPC domain | `browser-ipc-main`, `notifications-ipc-main`, `workspace-search-ipc-main` |
| `*-ipc-main.ts` | Registers a client-local Electron or OS-facing IPC domain | `browser-ipc-main`, `workspace-search-ipc-main` |
| `*-service.ts` / `*-controller.ts` | A client-local service without direct IPC ownership | `app-update-service`, `project-management-service`, `project-root-controller` |
| `*-guard.ts` | Validation / security boundary | `external-link-guard`, `open-path-guard`, `permission-response-guard` |
| (other) | Window, state, platform wiring | `main.ts` (entry), `main-window`, `window-state`, `theme-source`, `credential-store`, `skills`, `attachment-*` |
Expand Down
7 changes: 3 additions & 4 deletions apps/desktop/renderer-architecture.json
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@
"react": 1
},
"importSpecifiers": 14,
"nonTriviaTokens": 3509
"nonTriviaTokens": 3507
},
"src/renderer/app-shell-overlays.tsx": {
"importDeclarations": 5,
Expand Down Expand Up @@ -597,7 +597,7 @@
"@maka/ui": 1
},
"importSpecifiers": 7,
"nonTriviaTokens": 2681
"nonTriviaTokens": 2603
},
"src/renderer/app-shell-session-ui-state.ts": {
"importDeclarations": 0,
Expand Down Expand Up @@ -684,7 +684,6 @@
"window.maka.diagnostics.copyPreviousMainProcessInterruption": 1,
"window.maka.diagnostics.copyReport": 1,
"window.maka.diagnostics.takePreviousMainProcessInterruption": 1,
"window.maka.notifications.runEnded": 1,
"window.maka.onboarding.setMilestone": 1,
"window.maka.sessions.compact": 1,
"window.maka.sessions.listActiveInteractions": 1,
Expand Down Expand Up @@ -821,7 +820,7 @@
"react": 1
},
"importSpecifiers": 94,
"nonTriviaTokens": 12526
"nonTriviaTokens": 12465
},
"src/renderer/use-app-shell-composer-quotes.ts": {
"importDeclarations": 0,
Expand Down
31 changes: 0 additions & 31 deletions apps/desktop/src/main/__tests__/message-queue-ui-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,34 +284,3 @@ test('complete events deliver the durable context compaction outcome to Desktop'
},
]);
});

test('an interaction request notifies that the turn is waiting on the user', () => {
const controller = createAppShellSessionUiStateController();
const notified: unknown[] = [];
const handlers = createAppShellSessionEventHandlers({
uiLocale: 'en',
activeIdRef: { current: 'session-1' },
liveTurnBySessionRef: controller.liveTurnBySessionRef,
refreshMessages: async () => true,
refreshSessions: async () => [],
setLiveTurnBySession: controller.setLiveTurnBySession,
setInteractionBySession: controller.setInteractionBySession,
showModelSetupToast() {},
toastApi: { error() {} },
notifyRunEnded(payload) {
notified.push(payload);
},
});

handlers.handleEvent('session-1', {
type: 'user_question_request',
id: 'question-1',
turnId: 'turn-1',
ts: 1,
requestId: 'request-1',
toolUseId: 'tool-1',
questions: [{ question: 'Which branch?', options: [{ label: 'main' }] }],
});

assert.deepEqual(notified, [{ kind: 'waiting', sessionId: 'session-1', body: 'Which branch?' }]);
});
36 changes: 8 additions & 28 deletions apps/desktop/src/main/__tests__/notifications-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,17 @@
import { it } from 'node:test';
import assert from 'node:assert/strict';
import {
isRunNotificationKind,
resolveNotificationContent,
runNotificationCopy,
shouldRaiseRunNotification,
} from '../notifications-policy.js';

it('gates native notifications through every required condition', () => {
const base = { enabled: true, supported: true, windowFocused: false, incognito: false, e2e: false };
const base = { enabled: true, supported: true, windowFocused: false, e2e: false };
const cases = [
[base, true],
[{ ...base, enabled: false }, false],
[{ ...base, supported: false }, false],
[{ ...base, windowFocused: true }, false],
[{ ...base, incognito: true }, false],
[{ ...base, e2e: true }, false],
] as const;

Expand All @@ -42,36 +39,17 @@ it('gates native notifications through every required condition', () => {
}
});

it('recognizes terminal kinds and keeps distinct localized fallback copy', () => {
for (const value of ['completed', 'errored', 'waiting']) assert.equal(isRunNotificationKind(value), true);
for (const value of ['complete', 'error', 'aborted', '', undefined, null, 1, {}]) {
assert.equal(isRunNotificationKind(value), false);
}

const completed = runNotificationCopy('completed', 'zh-CN');
const errored = runNotificationCopy('errored', 'zh-CN');
assert.ok(completed.title && completed.body);
assert.ok(errored.title && errored.body);
assert.notEqual(completed.title, errored.title);

assert.deepEqual(runNotificationCopy('completed', 'zh-TW'), {
title: '回答已產生',
body: 'Maka 已完成本次回答,按一下以檢視。',
});
});

it('sanitizes renderer content, caps it, and falls back per field', () => {
it('sanitizes notification content, caps it, and falls back per field', () => {
const clean = resolveNotificationContent(
{ kind: 'completed', title: ' 会话 A ', body: 'line one\n\nline two\tindented' },
'zh-CN',
);
assert.deepEqual(clean, { title: '会话 A', body: 'line one line two indented' });

const completedFallback = runNotificationCopy('completed', 'zh-CN');
for (const value of ['', ' ', undefined, null, 42, {}]) {
for (const value of ['', ' ', undefined]) {
assert.deepEqual(
resolveNotificationContent({ kind: 'completed', title: value, body: value }, 'zh-CN'),
completedFallback,
{ title: '回答已生成', body: 'Maka 已完成本轮回答,点击查看。' },
);
}

Expand All @@ -82,9 +60,11 @@ it('sanitizes renderer content, caps it, and falls back per field', () => {
assert.equal(capped.body.length, 160);
assert.ok(capped.body.endsWith('…'));

const erroredFallback = runNotificationCopy('errored', 'zh-CN');
assert.deepEqual(
resolveNotificationContent({ kind: 'errored', title: '出错的会话', body: '' }, 'zh-CN'),
{ title: '出错的会话', body: erroredFallback.body },
{ title: '出错的会话', body: '本轮回答未能完成,点击查看详情。' },
);
assert.deepEqual(resolveNotificationContent({ kind: 'completed' }, 'zh-TW'), {
title: '回答已產生', body: 'Maka 已完成本次回答,按一下以檢視。',
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ test('drives the renderer Session catalog facade through real UDS framing', asyn
resolveExternalSessionImportWorkspace: async () => ({ kind: 'host_path', path: base }),
emitSessionsChanged: (_hostId, reason, sessionId) => changes.push({ reason, sessionId }),
completeDesktopInteractionTurn() {},
notifyRun: async () => {},
createSessionCopyCleanup: () => ({
ownCreation: (_creation, operation) => operation(),
rejectCreation: async () => undefined,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
type OperationKey,
type SessionAssistantStreamIdentity,
type SessionCatalogProjection,
type SessionCatalogChangedFrame,
type SessionContinuitySnapshot,
type SubscriptionFrame,
} from '@maka/runtime-host/protocol';
Expand Down Expand Up @@ -394,6 +395,28 @@ test('routes Guest catalog changes through the mount projection authority', asyn
await candidate.close();
});

test('owner and Guest candidates notify without opening a conversation and detach on close', async () => {
for (const access of ['owner', 'session_guest'] as const) {
const host = connectionHarness(access);
const notifications: unknown[] = [];
const candidate = await createCandidate(
host.connection,
{
...deps(ipcHarness()),
onGuestSessionCatalogChanged: () => {},
notifyRun: async (input) => { notifications.push(input); },
},
undefined, 'external', 'remote', access,
);
host.publishSessionCatalogChange('session-' + access, { kind: 'waiting', eventId: 'question-1', body: 'Answer?' });
await pollFor(() => notifications.length === 1, { timeoutMs: 1000 });
assert.equal((notifications[0] as { body: string }).body, 'Answer?');
await candidate.close();
host.publishSessionCatalogChange('session-' + access, { kind: 'completed', eventId: 'terminal-1' });
assert.equal(notifications.length, 1);
}
});

test('rejects a stale Host identity when raw Session IDs collide', async () => {
const ipc = ipcHarness();
const browserReleased: string[] = [];
Expand Down Expand Up @@ -1265,6 +1288,7 @@ function deps(
resolveExternalSessionImportWorkspace: async () => ({ kind: 'host_path', path: '/workspace' }),
emitSessionsChanged() {},
completeDesktopInteractionTurn() {},
notifyRun: async () => {},
createSessionCopyCleanup: () => ({
ownCreation: (_creation, operation) => operation(),
rejectCreation: async () => undefined,
Expand Down Expand Up @@ -1313,7 +1337,7 @@ function connectionHarness(
resolveTurnStarted = resolve;
});
const closeSubscriptions = new Set<() => void>();
const sessionCatalogListeners = new Set<(frame: { sessionId: string }) => void>();
const sessionCatalogListeners = new Set<(frame: SessionCatalogChangedFrame) => void>();
let provider: ClientCapabilityProvider | undefined;
let capabilityRegistrations = 0;
let capabilityUnregistrations = 0;
Expand Down Expand Up @@ -1503,7 +1527,7 @@ function connectionHarness(
capabilityUnregistrations += 1;
return { registrationId: `registration-${label}`, revision: 2 };
},
subscribeSessionCatalogChanges: (listener: (frame: { sessionId: string }) => void) => {
subscribeSessionCatalogChanges: (listener: (frame: SessionCatalogChangedFrame) => void) => {
sessionCatalogListeners.add(listener);
return () => sessionCatalogListeners.delete(listener);
},
Expand Down Expand Up @@ -1534,8 +1558,8 @@ function connectionHarness(
}
activeSubscriptionFrames.push(frame);
},
publishSessionCatalogChange: (sessionId: string) => {
for (const listener of sessionCatalogListeners) listener({ sessionId });
publishSessionCatalogChange: (sessionId: string, attention?: SessionCatalogChangedFrame['attention']) => {
for (const listener of sessionCatalogListeners) listener({ kind: 'session.catalog.changed', revision: 1, sessionId, ...(attention ? { attention } : {}) });
},
get capabilityRegistrations() {
return capabilityRegistrations;
Expand Down
145 changes: 145 additions & 0 deletions apps/desktop/src/main/__tests__/runtime-host-notifications.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* 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 { setImmediate } from 'node:timers/promises';
import { deferred, waitFor } from '@maka/core/test-only/async-primitives';
import type { RuntimeHostConnection } from '@maka/runtime-host/client';
import type { SessionCatalogChangedFrame } from '@maka/runtime-host/protocol';
import { DesktopRuntimeHostClient } from '../runtime-host-client.js';
import { deduplicateRunNotifications, type RunNotificationEvent } from '../notifications-policy.js';
import { observeRuntimeHostNotifications } from '../runtime-host-notifications.js';

test('notifies for every session through the Host feed without renderer or transcript subscriptions', async (t) => {
const f = fixture();
t.after(f.close);
assert.deepEqual(f.operations, []);
f.changed({ kind: 'session.catalog.changed', revision: 1, sessionId: 'old' });
for (const [sessionId, kind, body] of [
['background-question', 'waiting', 'Which branch?'],
['background-complete', 'completed', undefined],
['background-failed', 'errored', 'provider failed'],
] as const) {
f.changed({
kind: 'session.catalog.changed', revision: 2, sessionId,
attention: { kind, eventId: sessionId, ...(body ? { body } : {}) },
});
}
await waitFor(() => f.notifications.length === 3, { timeoutMs: 1000 });
assert.deepEqual(f.notifications, [
{ kind: 'waiting', title: 'background-question', body: 'Which branch?' },
{ kind: 'completed', title: 'background-complete', body: 'reply-background-complete' },
{ kind: 'errored', title: 'background-failed', body: 'provider failed' },
]);
assert.deepEqual(f.errors, []);
});

test('discards in-flight notification content after disposal', async () => {
const f = fixture();
const content = deferred<null>();
f.client.getSession = () => content.promise;
f.changed({
kind: 'session.catalog.changed', revision: 1, sessionId: 'a',
attention: { kind: 'completed', eventId: 'done' },
});
f.close();
content.resolve(null);
await setImmediate();
assert.deepEqual(f.notifications, []);
assert.equal(f.listenersRemaining(), 0);
});

test('shared sessions use the scoped catalog and content-read failures still notify with fallback copy', async (t) => {
const f = fixture(true);
t.after(f.close);
f.client.getSession = async () => { throw new Error('Owner-only query must not be used'); };
f.client.getSharedSession = async () => { throw new Error('Host disconnected'); };
f.changed({
kind: 'session.catalog.changed', revision: 1, sessionId: 'shared',
attention: { kind: 'waiting', eventId: 'question', body: 'Answer?' },
});
await waitFor(() => f.notifications.length === 1, { timeoutMs: 1000 });
assert.deepEqual(f.notifications, [{ kind: 'waiting', title: undefined, body: 'Answer?' }]);
});

test('overlapping owner and Guest feeds notify once while distinct events, sessions and Hosts still notify', async (t) => {
const notifications: RunNotificationEvent[] = [];
const pending = deferred<void>();
const notify = deduplicateRunNotifications(async (input) => {
notifications.push(input);
await pending.promise;
});
const owner = fixture(false, notify);
const guest = fixture(true, notify);
const otherHost = fixture(false, notify, 'host-2');
t.after(() => {
pending.resolve();
owner.close();
guest.close();
otherHost.close();
});
const frame: SessionCatalogChangedFrame = {
kind: 'session.catalog.changed', revision: 1, sessionId: 'shared',
attention: { kind: 'waiting', eventId: 'question' },
};
owner.changed(frame);
guest.changed(frame);
otherHost.changed(frame);
owner.changed({ ...frame, sessionId: 'other-session' });
owner.changed({ ...frame, attention: { kind: 'completed', eventId: 'terminal' } });
await setImmediate();
assert.deepEqual(notifications.map(({ hostEpoch, sessionId, eventId }) => [hostEpoch, sessionId, eventId]), [
['host-1', 'shared', 'question'],
['host-2', 'shared', 'question'],
['host-1', 'other-session', 'question'],
['host-1', 'shared', 'terminal'],
]);
});

function fixture(
shared = false,
notify?: (input: RunNotificationEvent) => Promise<void>,
hostEpoch = 'host-1',
) {
let listener: ((frame: SessionCatalogChangedFrame) => void) | undefined;
const notifications: Pick<RunNotificationEvent, 'kind' | 'title' | 'body'>[] = [];
const errors: unknown[] = [];
const operations: string[] = [];
const connection = {
hostEpoch,
request: async (operation: string, input: { sessionId?: string }) => {
operations.push(operation);
return { kind: 'session', session: { id: input.sessionId, name: input.sessionId, lastMessagePreview: 'reply-' + input.sessionId } };
},
subscribeSessionCatalogChanges(next: typeof listener) {
listener = next;
return () => { listener = undefined; };
},
} as unknown as RuntimeHostConnection;
const client = new DesktopRuntimeHostClient(connection);
const close = observeRuntimeHostNotifications(client, notify ?? (async ({ kind, title, body }) => {
notifications.push({ kind, title, body });
}), (error) => errors.push(error), shared);
return {
client, close, operations, notifications, errors,
changed(frame: SessionCatalogChangedFrame) { listener?.(frame); },
listenersRemaining: () => Number(!!listener),
};
}
Loading