Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
34 changes: 34 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,40 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

xterm.js dependency patch

Source: https://www.npmjs.com/package/@xterm/xterm/v/6.0.0
Repository: https://github.com/xtermjs/xterm.js
Version: 6.0.0
Dependency patch: patches/@xterm+xterm+6.0.0.patch
License: MIT

Maka redistributes a patch to the TypeScript source and both shipped JavaScript
bundles that defers selection rendering while the terminal is hidden. The
following upstream license applies to that material:

Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Pi TUI dependency patch

Source: https://www.npmjs.com/package/@earendil-works/pi-tui/v/0.84.4
Expand Down
13 changes: 6 additions & 7 deletions apps/desktop/renderer-architecture.json
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@
"react": 1
},
"importSpecifiers": 19,
"nonTriviaTokens": 3736
"nonTriviaTokens": 3715
},
"src/renderer/app-shell-overlays.tsx": {
"importDeclarations": 7,
Expand Down Expand Up @@ -866,7 +866,7 @@
"react": 1
},
"importSpecifiers": 104,
"nonTriviaTokens": 13531
"nonTriviaTokens": 13515
},
"src/renderer/use-app-shell-composer-quotes.ts": {
"importDeclarations": 2,
Expand Down Expand Up @@ -938,9 +938,8 @@
"useAppShellSessionList": 1,
"useAppShellSessionUiState": 1,
"useExternalStoreSelector": 1,
"useRef": 7,
"useSessionCatalogController": 1,
"useState": 3
"useRef": 4,
"useSessionCatalogController": 1
},
"lifecycleMethods": {},
"unresolvedDependencies": 0,
Expand All @@ -955,8 +954,8 @@
"./use-external-store-selector.js": 1,
"react": 1
},
"importSpecifiers": 10,
"nonTriviaTokens": 466
"importSpecifiers": 9,
"nonTriviaTokens": 412
}
},
"closure": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { strict as assert } from 'node:assert';
import { afterEach, describe, it } from 'node:test';
import { act, createElement } from 'react';
import { LocaleProvider } from '@maka/ui';
import type { StoredMessage } from '@maka/core/session';
import { cleanupFakeDom, installReactRenderer } from './fake-dom.js';
import { useAppShellSessionWorkspace } from '../../renderer/use-app-shell-session-workspace.js';

Expand Down Expand Up @@ -50,6 +51,55 @@ function actionKeys(workspace: Workspace): string[] {
describe('session workspace action identity', () => {
afterEach(cleanupFakeDom);

it('hands over identity and rows together and rejects superseded reads', () => {
const { root } = installReactRenderer();
let workspace!: Workspace;
const displays: Array<{ id: string | undefined; messages: StoredMessage[] }> = [];
function Probe(): null {
workspace = useAppShellSessionWorkspace({ error: () => {} });
displays.push({ id: workspace.activeId, messages: workspace.messages });
return null;
}
act(() => root.render(createElement(LocaleProvider, {
locale: 'en', children: createElement(Probe),
})));
act(() => workspace.seedSessions(['a', 'b', 'c'].map((id) => ({
id, name: id, isFlagged: false, isArchived: false, labels: [],
hasUnread: false, status: 'active' as const, backend: 'ai-sdk' as const,
revision: 1, runtimeHostId: 'local', profileId: 'local', profileName: 'Local',
llmConnectionSlug: 'test', connectionLocked: false, model: 'test',
permissionMode: 'ask' as const, profileKind: 'local' as const,
}))));
const row = (id: string): StoredMessage => ({ id, type: 'user', text: id, turnId: id, ts: 1 });
const a = [row('a-message')];
const c = [row('c-message')];
act(() => { workspace.setActiveId('a'); workspace.commitTranscript('a', a); });
displays.length = 0;
act(() => workspace.setActiveId('b'));
assert.equal(workspace.requestedSessionId, 'b');
assert.equal(workspace.activeId, 'a');
assert.equal(workspace.messages, a);
act(() => workspace.setActiveId('c'));
act(() => workspace.commitTranscript('b', [row('b-message')]));
assert.equal(workspace.activeId, 'a');
act(() => workspace.commitTranscript('c', c));
assert.equal(workspace.activeId, 'c');
assert.equal(workspace.messageLoadPending, false);
assert.ok(displays.every((display) =>
(display.id === 'a' && display.messages === a) ||
(display.id === 'c' && display.messages === c)));

act(() => workspace.setActiveId('b'));
act(() => workspace.startNewSession());
act(() => workspace.commitTranscript('b', [row('b-message')]));
assert.equal(workspace.activeId, undefined);
assert.deepEqual(workspace.messages, []);
// A first-send task has no readable Host history yet; it must activate
// immediately rather than waiting for its own first message to be sent.
act(() => workspace.setActiveId('new-local-task'));
assert.equal(workspace.activeId, 'new-local-task');
});

it('keeps every action identity fixed across re-renders', () => {
const { root } = installReactRenderer();
const reads: Workspace[] = [];
Expand Down
88 changes: 75 additions & 13 deletions apps/desktop/src/main/__tests__/workbar-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { LocaleProvider } from '@maka/ui';
import { cleanupFakeDom, installReactRenderer } from './fake-dom.js';
import {
createFakeWorkbarServices,
projectWorkbarPanelsForSession,
useWorkbarController,
WorkbarServicesProvider,
type UseWorkbarControllerInput,
Expand Down Expand Up @@ -71,14 +72,18 @@ type ControllerProbeInput = UseWorkbarControllerInput & { openOnActivation?: boo
function ControllerProbe(props: ControllerProbeInput) {
const workbar = useWorkbarController(props);
latestController = workbar;
const visiblePanels = projectWorkbarPanelsForSession(
workbar.host.panelsState, workbar.host.activeId,
new Set(workbar.host.quotes?.map((quote) => `side-chat:${quote.id}`)),
);
useLayoutEffect(() => {
if (props.openOnActivation) workbar.host.onOpenLauncher('right');
}, [props.activeSession?.id, props.openOnActivation]);
controllerRenderSnapshots.push({
activeId: latestController.host.activeId,
terminalOwnerIds: [
...latestController.host.panelsState.right.tabs,
...latestController.host.panelsState.bottom.tabs,
...visiblePanels.right.tabs,
...visiblePanels.bottom.tabs,
]
.filter((tab) => tab.kind === 'terminal')
.map((tab) => tab.ownerSessionId),
Expand Down Expand Up @@ -125,7 +130,7 @@ function input(
activeSession,
projectId: activeSession?.projectId,
projectAliases: [],
authoritativeSessionIds: new Set(activeSession ? [activeSession.id] : []),
authoritativeSessionIds: new Set(['a', 'b', ...(activeSession ? [activeSession.id] : [])]),
shellObscured: false,
modelChoices: [],
reportError: (title, description) => errors.push(`${title}: ${description}`),
Expand Down Expand Up @@ -194,7 +199,7 @@ describe('useWorkbarController', () => {
assert.equal(controller().host.rightCollapsed, false);
});

it("preserves the active Session's visibility while removing the previous Session's Terminal", async () => {
it("preserves visibility while hiding, rather than removing, another Session's Terminal", async () => {
const { root } = installReactRenderer();
const defaults = createFakeWorkbarServices();
const services = createFakeWorkbarServices({
Expand All @@ -217,7 +222,10 @@ describe('useWorkbarController', () => {
assert.equal(controller().host.panelsState.right.tabs.length, 1);
await act(async () => show('b'));

assert.equal(controller().host.panelsState.right.tabs.length, 0);
assert.equal(controller().host.panelsState.right.tabs.length, 1);
assert.equal(projectWorkbarPanelsForSession(
controller().host.panelsState, 'b', new Set(),
).right.tabs.length, 0);
assert.equal(controller().host.rightCollapsed, false);
});

Expand Down Expand Up @@ -340,7 +348,7 @@ describe('useWorkbarController', () => {
);
});

it('stops a Terminal whose start resolves after the owner Session changes', async () => {
it('retains a Terminal whose start resolves after navigation without revealing it in the new Session', async () => {
const { root } = installReactRenderer();
const start = deferred<ShellRunUpdate>();
const starts: string[] = [];
Expand All @@ -367,16 +375,21 @@ describe('useWorkbarController', () => {
await act(async () => renderController(root, services, input(session('b'))));
await act(async () => start.resolve(shellUpdate('a', 'terminal-a')));

assert.deepEqual(stops, [{ sessionId: 'a', ref: 'terminal-a' }]);
assert.deepEqual(stops, []);
assert.equal(
controller().host.panelsState.right.tabs.some(
(tab) => tab.kind === 'terminal',
),
false,
true,
);
assert.equal(controller().host.rightCollapsed, true);
await act(async () => renderController(root, services, input(session('a'))));
const owned = controller().host.panelsState.right.tabs.find((tab) => tab.kind === 'terminal');
assert.equal(owned?.ownerSessionId, 'a');
assert.equal(owned?.resourceRef, 'terminal-a');
});

it('stops an opened Terminal exactly once on close and on Session switch', async () => {
it('stops only explicitly closed Terminals and retains the same resource across navigation', async () => {
const { root } = installReactRenderer();
const stops: Array<{ sessionId: string; ref: string }> = [];
const defaults = createFakeWorkbarServices();
Expand Down Expand Up @@ -407,7 +420,6 @@ describe('useWorkbarController', () => {
await act(async () => renderController(root, services, input(session('b'))));
assert.deepEqual(stops, [
{ sessionId: 'a', ref: 'terminal-1' },
{ sessionId: 'a', ref: 'terminal-2' },
]);
assert.equal(
controllerRenderSnapshots
Expand All @@ -419,11 +431,16 @@ describe('useWorkbarController', () => {
),
false,
);
await act(async () => renderController(root, services, input(session('a'))));
const retained = controller().host.panelsState.right.tabs.find((tab) => tab.kind === 'terminal');
assert.equal(retained?.resourceRef, 'terminal-2');
assert.deepEqual(stops, [{ sessionId: 'a', ref: 'terminal-1' }]);
});

it('retries a failed Terminal stop during later Session cleanup', async () => {
it('retains a failed Terminal close for visible retry and removes it only after Stop succeeds', async () => {
const { root } = installReactRenderer();
const firstStop = deferred<ShellRunUpdate | null>();
const retryStop = deferred<ShellRunUpdate | null>();
const stops: Array<{ sessionId: string; ref: string }> = [];
const defaults = createFakeWorkbarServices();
const services = createFakeWorkbarServices({
Expand All @@ -432,7 +449,7 @@ describe('useWorkbarController', () => {
start: async (sessionId) => shellUpdate(sessionId, 'terminal-retry'),
stop: (request) => {
stops.push(request);
return stops.length === 1 ? firstStop.promise : Promise.resolve(null);
return stops.length === 1 ? firstStop.promise : retryStop.promise;
},
},
});
Expand All @@ -444,22 +461,67 @@ describe('useWorkbarController', () => {
);
assert.ok(tab);
await act(async () => controller().host.onCloseTab('right', tab));
await act(async () => controller().host.onCloseTab('right', tab));
assert.deepEqual(stops, [{ sessionId: 'a', ref: 'terminal-retry' }]);
assert.ok(controller().host.panelsState.right.tabs.includes(tab));

await act(async () => {
firstStop.reject(new Error('Host disconnected'));
await Promise.resolve();
});
await act(async () => renderController(root, services, input(session('b'))));
assert.equal(stops.length, 1);
Comment thread
Astro-Han marked this conversation as resolved.
await act(async () => renderController(root, services, input(session('a'))));
assert.ok(controller().host.panelsState.right.tabs.includes(tab));
await act(async () => controller().host.onCloseTab('right', tab));
await act(async () => renderController(root, services, input(session('b'))));
await act(async () => controller().commands.toggleRight());
assert.equal(controller().host.rightCollapsed, false);
await act(async () => retryStop.resolve(null));
assert.equal(controller().host.panelsState.right.tabs.includes(tab), false);
assert.equal(controller().host.rightCollapsed, false);
assert.deepEqual(stops, [
{ sessionId: 'a', ref: 'terminal-retry' },
{ sessionId: 'a', ref: 'terminal-retry' },
]);

await act(async () => renderController(root, services, input(session('c'))));
await act(async () => root.unmount());
assert.equal(stops.length, 2);
});

it('releases a retired owner’s terminal topology and teardown obligation', async () => {
const { root } = installReactRenderer();
const lateStart = deferred<ShellRunUpdate>();
const stops: string[] = [];
const defaults = createFakeWorkbarServices();
const services = createFakeWorkbarServices({ terminal: {
...defaults.terminal,
start: async (id) => id === 'c' ? lateStart.promise : shellUpdate(id, `terminal-${id}`),
stop: async ({ ref }) => { stops.push(ref); return null; },
} });
await act(async () => renderController(root, services, input(session('a'))));
await act(async () => controller().commands.openTool('terminal'));
await act(async () => renderController(root, services, input(session('b'))));
await act(async () => controller().commands.openTool('terminal'));
// Host admits retirement only after A's resource is terminal. Its catalog
// removal is authoritative; the renderer does not issue another Stop.
await act(async () => renderController(root, services, {
...input(session('b')), authoritativeSessionIds: new Set(['b']),
}));
assert.deepEqual(controller().host.panelsState.right.tabs.map((tab) => tab.ownerSessionId), ['b']);
await act(async () => renderController(root, services, input(session('c'))));
await act(async () => controller().commands.openTool('terminal'));
await act(async () => renderController(root, services, {
...input(session('b')), authoritativeSessionIds: new Set(['b']),
}));
// A delayed response cannot resurrect a terminal whose owner has retired.
await act(async () => lateStart.resolve(shellUpdate('c', 'terminal-c')));
assert.deepEqual(controller().host.panelsState.right.tabs.map((tab) => tab.ownerSessionId), ['b']);
assert.deepEqual(stops, []);
await act(async () => root.unmount());
assert.deepEqual(stops, ['terminal-b']);
});

it('owns a resolved Terminal before its tab state commits', async () => {
const { root } = installReactRenderer();
const start = deferred<ShellRunUpdate>();
Expand Down
20 changes: 7 additions & 13 deletions apps/desktop/src/renderer/app-shell-effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,38 +318,32 @@ export function useActiveSessionEvents(options: {
beginObservationSeed: (sessionId: string) => void;
completeObservationSeed: (sessionId: string) => void;
setMessageLoadErrorBySession: (updater: (current: Record<string, string>) => Record<string, string>) => void;
clearMessageLoadError(sessionId: string): void;
setMessageLoadPending: (pending: boolean) => void;
setMessages: (messages: StoredMessage[]) => void;
commitTranscript: (sessionId: string, messages: StoredMessage[]) => void;
transcriptRangeRef: RefBox<desktopTranscript.DesktopTranscriptRangeController | undefined>;
setSessionEventHealthBySession: SessionEventHealthUpdater;
toastApi: Pick<ToastApi, 'error'>;
}) {
const activeId = options.activeId;
const clearMessageLoadError = useEffectEvent((sessionId: string) => {
options.setMessageLoadErrorBySession((current) => {
if (!current[sessionId]) return current;
const next = { ...current };
delete next[sessionId];
return next;
});
});
const clearMessageLoadError = useEffectEvent(options.clearMessageLoadError);
// Reached only from the store subscription, which the effect unsubscribes on
// teardown, so the window it publishes is always a live one.
const applyTranscript = useEffectEvent((
sessionId: string,
store: desktopTranscript.DesktopTranscriptRangeStore,
) => {
if (options.activeIdRef.current === sessionId) {
if (options.activeId === sessionId) {
const snapshot = store.snapshot();
options.setMessages([...snapshot.messages]);
if (snapshot.ready) {
options.commitTranscript(sessionId, [...snapshot.messages]);
clearMessageLoadError(sessionId);
options.setMessageLoadPending(false);
}
}
});
const applyReadError = useEffectEvent((sessionId: string, error: unknown) => {
if (options.activeIdRef.current === sessionId) {
if (options.activeId === sessionId) {
if (options.activeIdRef.current !== sessionId) options.commitTranscript(sessionId, []);
const message = messageReadErrorMessage(error, options.uiLocale);
options.setMessageLoadErrorBySession((current) => ({
...current,
Expand Down
Loading
Loading