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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
118 changes: 118 additions & 0 deletions apps/desktop/src/main/__tests__/app-shell-session-ui-state.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import type { PermissionRequestEvent } from '@maka/core';
import { applyThinkingComplete, applyThinkingDelta } from '@maka/ui';
import {
clearAppShellSessionUiStateForSession,
createAppShellSessionUiStateController,
createInitialAppShellSessionUiState,
type AppShellSessionUiState,
} from '../../renderer/app-shell-session-ui-state.js';

function permissionRequest(requestId: string): PermissionRequestEvent {
return {
type: 'permission_request',
id: `event-${requestId}`,
ts: 1,
requestId,
toolUseId: `tool-${requestId}`,
toolName: 'shell',
} as unknown as PermissionRequestEvent;
}

function seededState(): AppShellSessionUiState {
return {
...createInitialAppShellSessionUiState(),
messageLoadErrorBySession: { drop: 'failed', keep: 'still failed' },
messageRetryPendingBySession: { drop: true, keep: true },
stopPendingBySession: { drop: true, keep: true },
streamingBySession: {
drop: { text: 'drop stream', truncated: false, phase: 'streaming' },
keep: { text: 'keep stream', truncated: true, phase: 'draining', messageId: 'm-keep' },
},
thinkingBySession: { drop: 'drop thinking', keep: 'keep thinking' },
thinkingTruncatedBySession: { drop: true, keep: true },
liveToolsBySession: {
drop: [{ toolUseId: 'tool-drop', toolName: 'Shell', status: 'running', args: {} }],
keep: [{ toolUseId: 'tool-keep', toolName: 'Shell', status: 'pending', args: {} }],
},
permissionBySession: {
drop: [permissionRequest('drop')],
keep: [permissionRequest('keep')],
},
sessionEventHealthBySession: {
drop: { sessionId: 'drop', status: 'connected', subscribedAt: 1, checkedAt: 1 },
keep: { sessionId: 'keep', status: 'stale', subscribedAt: 1, checkedAt: 2, staleSince: 2 },
},
pendingPermissionModeBySession: { drop: true, keep: true },
pendingSessionModelBySession: { drop: true, keep: true },
};
}

describe('app shell session UI state controller', () => {
it('clears one session from every per-session UI map without touching other sessions', () => {
const next = clearAppShellSessionUiStateForSession(seededState(), 'drop');

assert.deepEqual(Object.keys(next.messageLoadErrorBySession), ['keep']);
assert.deepEqual(Object.keys(next.messageRetryPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.stopPendingBySession), ['keep']);
assert.deepEqual(Object.keys(next.streamingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingBySession), ['keep']);
assert.deepEqual(Object.keys(next.thinkingTruncatedBySession), ['keep']);
assert.deepEqual(Object.keys(next.liveToolsBySession), ['keep']);
assert.deepEqual(Object.keys(next.permissionBySession), ['keep']);
assert.deepEqual(Object.keys(next.sessionEventHealthBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingPermissionModeBySession), ['keep']);
assert.deepEqual(Object.keys(next.pendingSessionModelBySession), ['keep']);
});

it('keeps state identity for no-op map updates and only replaces the selected map', () => {
const controller = createAppShellSessionUiStateController();
const state = controller.getState();
controller.setMessageLoadErrorBySession((current) => current);
assert.equal(controller.getState(), state);

controller.setMessageLoadErrorBySession((current) => ({ ...current, session: 'failed' }));
const next = controller.getState();

assert.notEqual(next, state);
assert.deepEqual(next.messageLoadErrorBySession, { session: 'failed' });
assert.equal(next.stopPendingBySession, state.stopPendingBySession);
assert.equal(next.streamingBySession, state.streamingBySession);
});

it('preserves nested thinking flag updates from thinking delta and complete events', () => {
const sessionId = 'thinking-session';
const controller = createAppShellSessionUiStateController();

controller.setThinkingBySession((current) => {
const applied = applyThinkingDelta(current[sessionId] ?? '', 'x'.repeat(5 * 1024));
if (applied.truncated) {
controller.setThinkingTruncatedBySession((flags) =>
flags[sessionId] ? flags : { ...flags, [sessionId]: true },
);
}
return { ...current, [sessionId]: applied.text };
});

const afterDelta = controller.getState();
assert.match(afterDelta.thinkingBySession[sessionId], /单条 delta 已截断/);
assert.equal(afterDelta.thinkingTruncatedBySession[sessionId], true);

controller.setThinkingBySession((current) => {
const applied = applyThinkingComplete('final thinking');
controller.setThinkingTruncatedBySession((flags) => {
if ((flags[sessionId] === true) === applied.truncated) return flags;
if (applied.truncated) return { ...flags, [sessionId]: true };
const next = { ...flags };
delete next[sessionId];
return next;
});
return { ...current, [sessionId]: applied.text };
});

const afterComplete = controller.getState();
assert.equal(afterComplete.thinkingBySession[sessionId], 'final thinking');
assert.equal(afterComplete.thinkingTruncatedBySession[sessionId], undefined);
});
});
Original file line numberDiff line numberDiff line change
Expand Up@@ -81,8 +81,8 @@ describe('active session message lifecycle contract', () => {
);
assert.match(
src,
/const \[messageRetryPendingBySession, setMessageRetryPendingBySession\] = useState<Record<string, boolean>>\(\{\}\);[\s\S]*const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\)/,
'desktop shell must track message retry pending state outside React render timing',
/const messageRetryPendingRef = useRef<Set<string>>\(new Set\(\)\);[\s\S]*const \{[\s\S]*setMessageRetryPendingBySession,[\s\S]*\} = useAppShellSessionUiState\(\);[\s\S]*const \{[\s\S]*messageRetryPendingBySession,[\s\S]*\} = sessionUiState;/,
'desktop shell must keep the ref-backed duplicate guard while exposing per-session retry pending state from the shell UI reducer',
);
assert.match(
src,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,17 +44,11 @@ describe('session row actions fail soft', () => {
assert.match(cleanupBlock, /clearPendingTurnActionsForSession\(sessionId\);/);
assert.match(cleanupBlock, /pendingPermissionModeChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(cleanupBlock, /setMessageRetryPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStopPendingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingPermissionModeBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPendingSessionModelBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setMessageLoadErrorBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setStreamingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setThinkingTruncatedBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setLiveToolsBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setPermissionBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(cleanupBlock, /setSessionEventHealthBySession\(\(current\) => omitSessionKey\(current, sessionId\)\);/);
assert.match(
cleanupBlock,
/clearSessionUiState\(sessionId\);/,
'archive/delete cleanup must use the centralized per-session UI state cleanup',
);

assert.match(
main,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,7 +201,8 @@ describe('permission mode transition guard copy', () => {
const setPermissionModeBlock = renderer.match(/async function setPermissionMode[\s\S]*?async function setSessionModel/)?.[0] ?? '';

assert.match(renderer, /const pendingPermissionModeChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingPermissionModeBySession, setPendingPermissionModeBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingPermissionModeBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingPermissionModeBySession,[\s\S]*\} = sessionUiState;/);
assert.match(
setPermissionModeBlock,
/const sessionId = activeIdRef\.current;[\s\S]*if \(!sessionId\) \{[\s\S]*setPendingNewChatPermissionMode\(mode\);[\s\S]*return;[\s\S]*\}[\s\S]*pendingPermissionModeChangesRef\.current\.has\(sessionId\)/,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -85,7 +85,8 @@ describe('PR-SESSION-STICKY-MODEL-0 contract', () => {
assert.match(globalTypes, /setModel\(sessionId: string, input: \{ llmConnectionSlug: string; model: string \}\): Promise<SessionSummary>/);
assert.match(renderer, /modelChoices=\{chatModelChoices\}/);
assert.match(renderer, /const pendingSessionModelChangesRef = useRef<Set<string>>\(new Set\(\)\);/);
assert.match(renderer, /const \[pendingSessionModelBySession, setPendingSessionModelBySession\] = useState<Record<string, boolean>>\(\{\}\);/);
assert.match(renderer, /const \{[\s\S]*setPendingSessionModelBySession,[\s\S]*\} = useAppShellSessionUiState\(\);/);
assert.match(renderer, /const \{[\s\S]*pendingSessionModelBySession,[\s\S]*\} = sessionUiState;/);
assert.match(renderer, /const sessionId = activeIdRef\.current;[\s\S]*pendingSessionModelChangesRef\.current\.has\(sessionId\)[\s\S]*window\.maka\.sessions\.setModel\(sessionId, input\)[\s\S]*finally \{[\s\S]*pendingSessionModelChangesRef\.current\.delete\(sessionId\);/);
assert.match(
renderer,
Expand Down
166 changes: 166 additions & 0 deletions apps/desktop/src/renderer/app-shell-session-ui-state.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
import { useReducer, useRef } from 'react';
import type { SessionEventStreamSnapshot } from '@maka/core';
import type { AssistantStreamSlot, PermissionQueues, ToolActivityItem } from '@maka/ui';

type StateUpdater<T> = (updater: (current: T) => T) => void;

export interface AppShellSessionUiState {
messageLoadErrorBySession: Record<string, string>;
messageRetryPendingBySession: Record<string, boolean>;
stopPendingBySession: Record<string, boolean>;
streamingBySession: Record<string, AssistantStreamSlot>;
thinkingBySession: Record<string, string>;
thinkingTruncatedBySession: Record<string, boolean>;
liveToolsBySession: Record<string, ToolActivityItem[]>;
permissionBySession: PermissionQueues;
sessionEventHealthBySession: Record<string, SessionEventStreamSnapshot>;
pendingPermissionModeBySession: Record<string, boolean>;
pendingSessionModelBySession: Record<string, boolean>;
}

type AppShellSessionUiStateMapKey = keyof AppShellSessionUiState;

const SESSION_UI_MAP_KEYS = [
'messageLoadErrorBySession',
'messageRetryPendingBySession',
'stopPendingBySession',
'streamingBySession',
'thinkingBySession',
'thinkingTruncatedBySession',
'liveToolsBySession',
'permissionBySession',
'sessionEventHealthBySession',
'pendingPermissionModeBySession',
'pendingSessionModelBySession',
] as const satisfies readonly AppShellSessionUiStateMapKey[];

type MissingSessionUiMapKey = Exclude<AppShellSessionUiStateMapKey, typeof SESSION_UI_MAP_KEYS[number]>;
const allSessionUiMapsAreListed: Record<MissingSessionUiMapKey, never> = {};
void allSessionUiMapsAreListed;

export function createInitialAppShellSessionUiState(): AppShellSessionUiState {
return Object.fromEntries(SESSION_UI_MAP_KEYS.map((key) => [key, {}])) as unknown as AppShellSessionUiState;
}

function omitSessionKey<K extends AppShellSessionUiStateMapKey>(
current: AppShellSessionUiState[K],
sessionId: string,
): AppShellSessionUiState[K] {
if (!(sessionId in current)) return current;
const next = { ...current };
delete (next as Record<string, unknown>)[sessionId];
return next as AppShellSessionUiState[K];
}

function updateAppShellSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): AppShellSessionUiState {
const current = state[key];
const next = updater(current);
if (next === current) return state;
return { ...state, [key]: next };
}

function clearSessionUiStateMap<K extends AppShellSessionUiStateMapKey>(
state: AppShellSessionUiState,
key: K,
sessionId: string,
): AppShellSessionUiState {
return updateAppShellSessionUiStateMap(state, key, (current) => omitSessionKey(current, sessionId));
}

export function clearAppShellSessionUiStateForSession(
state: AppShellSessionUiState,
sessionId: string,
): AppShellSessionUiState {
let nextState = state;
for (const key of SESSION_UI_MAP_KEYS) {
nextState = clearSessionUiStateMap(nextState, key, sessionId);
}
return nextState;
}

export function createAppShellSessionUiStateController(
initialState: AppShellSessionUiState = createInitialAppShellSessionUiState(),
onChange: (state: AppShellSessionUiState) => void = () => {},
) {
let currentState = initialState;
const streamingBySessionRef = { current: currentState.streamingBySession };
const sessionEventHealthBySessionRef = { current: currentState.sessionEventHealthBySession };

function replaceState(next: AppShellSessionUiState): void {
if (next === currentState) return;
currentState = next;
streamingBySessionRef.current = next.streamingBySession;
sessionEventHealthBySessionRef.current = next.sessionEventHealthBySession;
onChange(next);
}

function updateMap<K extends AppShellSessionUiStateMapKey>(
key: K,
updater: (current: AppShellSessionUiState[K]) => AppShellSessionUiState[K],
): void {
const nextMap = updater(currentState[key]);
const latestState = currentState;
if (nextMap === latestState[key]) return;
replaceState({ ...latestState, [key]: nextMap });
}

function createMapSetter<K extends AppShellSessionUiStateMapKey>(key: K): StateUpdater<AppShellSessionUiState[K]> {
return (updater) => updateMap(key, updater);
}

return {
getState: () => currentState,
streamingBySessionRef,
sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: createMapSetter('messageLoadErrorBySession'),
setMessageRetryPendingBySession: createMapSetter('messageRetryPendingBySession'),
setStopPendingBySession: createMapSetter('stopPendingBySession'),
setStreamingBySession: createMapSetter('streamingBySession'),
setThinkingBySession: createMapSetter('thinkingBySession'),
setThinkingTruncatedBySession: createMapSetter('thinkingTruncatedBySession'),
setLiveToolsBySession: createMapSetter('liveToolsBySession'),
setPermissionBySession: createMapSetter('permissionBySession'),
setSessionEventHealthBySession: createMapSetter('sessionEventHealthBySession'),
setPendingPermissionModeBySession: createMapSetter('pendingPermissionModeBySession'),
setPendingSessionModelBySession: createMapSetter('pendingSessionModelBySession'),
clearSessionUiState: (sessionId: string) => {
replaceState(clearAppShellSessionUiStateForSession(currentState, sessionId));
},
};
}

export function useAppShellSessionUiState() {
const [, forceRender] = useReducer((version: number) => version + 1, 0);
const controllerRef = useRef<ReturnType<typeof createAppShellSessionUiStateController> | null>(null);

if (!controllerRef.current) {
controllerRef.current = createAppShellSessionUiStateController(
createInitialAppShellSessionUiState(),
() => forceRender(),
);
}

const controller = controllerRef.current;

return {
state: controller.getState(),
streamingBySessionRef: controller.streamingBySessionRef,
sessionEventHealthBySessionRef: controller.sessionEventHealthBySessionRef,
setMessageLoadErrorBySession: controller.setMessageLoadErrorBySession,
setMessageRetryPendingBySession: controller.setMessageRetryPendingBySession,
setStopPendingBySession: controller.setStopPendingBySession,
setStreamingBySession: controller.setStreamingBySession,
setThinkingBySession: controller.setThinkingBySession,
setThinkingTruncatedBySession: controller.setThinkingTruncatedBySession,
setLiveToolsBySession: controller.setLiveToolsBySession,
setPermissionBySession: controller.setPermissionBySession,
setSessionEventHealthBySession: controller.setSessionEventHealthBySession,
setPendingPermissionModeBySession: controller.setPendingPermissionModeBySession,
setPendingSessionModelBySession: controller.setPendingSessionModelBySession,
clearSessionUiState: controller.clearSessionUiState,
};
}
Loading