mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-20 23:20:46 +00:00
820 lines
30 KiB
TypeScript
820 lines
30 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import test from 'node:test';
|
|
import { createAiPrivacyService } from '../../electron/shared/aiPrivacyService.cjs';
|
|
import {
|
|
hasReversibleModelPrivacy,
|
|
setReversibleModelPrivacy,
|
|
} from '../../infrastructure/ai/harness/modelSecretRedaction';
|
|
import type { AISession } from '../../infrastructure/ai/types';
|
|
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
|
import {
|
|
cleanupClosedTerminalSessions,
|
|
cleanupDeletedAIChatSessions,
|
|
cleanupOrphanedAISessions,
|
|
cleanupSdkAgentSessions,
|
|
latestAIActiveSessionMapSnapshot,
|
|
latestAISessionsSnapshot,
|
|
setLatestAIActiveSessionMapSnapshot,
|
|
setLatestAISessionsSnapshot,
|
|
} from './aiStateSnapshots';
|
|
|
|
test('orphan cleanup keeps durable Catty output while explicit deletion removes it', async () => {
|
|
const sdkCleanups: string[] = [];
|
|
const outputCleanups: string[] = [];
|
|
const terminalOutputCleanups: string[] = [];
|
|
const previousWindow = globalThis.window;
|
|
Object.defineProperty(globalThis, 'window', {
|
|
configurable: true,
|
|
value: {
|
|
netcatty: {
|
|
aiSdkAgentCleanup: async (chatSessionId: string) => {
|
|
sdkCleanups.push(chatSessionId);
|
|
return { ok: true };
|
|
},
|
|
deleteChatToolOutputsTemp: async (chatSessionId: string) => {
|
|
outputCleanups.push(chatSessionId);
|
|
return { deletedCount: 1 };
|
|
},
|
|
deleteTerminalToolOutputsEverywhereTemp: async (terminalSessionId: string) => {
|
|
terminalOutputCleanups.push(terminalSessionId);
|
|
return { deletedCount: 1 };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
try {
|
|
cleanupSdkAgentSessions(['history-kept']);
|
|
cleanupDeletedAIChatSessions(['history-deleted']);
|
|
cleanupClosedTerminalSessions(['terminal-closed', 'terminal-closed']);
|
|
await new Promise(resolve => setTimeout(resolve, 0));
|
|
|
|
assert.deepEqual(sdkCleanups, ['history-kept', 'history-deleted']);
|
|
assert.deepEqual(outputCleanups, ['history-deleted']);
|
|
assert.deepEqual(terminalOutputCleanups, ['terminal-closed']);
|
|
} finally {
|
|
Object.defineProperty(globalThis, 'window', {
|
|
configurable: true,
|
|
value: previousWindow,
|
|
});
|
|
}
|
|
});
|
|
|
|
function makeSession(id: string, updatedAt: number, messages: unknown[]): AISession {
|
|
return {
|
|
id,
|
|
title: id,
|
|
agentId: 'agent',
|
|
scope: { type: 'terminal', targetId: 't' },
|
|
messages: messages as never,
|
|
createdAt: updatedAt,
|
|
updatedAt,
|
|
} as never;
|
|
}
|
|
|
|
test('orphan cleanup preserves resumable privacy maps until explicit chat deletion', (t) => {
|
|
const service = createAiPrivacyService({ maxSessions: 3 });
|
|
service.configure({ enabled: true });
|
|
const sessions = [
|
|
{ ...makeSession('privacy-orphan', 1, []), scope: { type: 'terminal' as const, targetId: 'closed' } },
|
|
{ ...makeSession('privacy-live', 2, []), scope: { type: 'terminal' as const, targetId: 'open' } },
|
|
{ ...makeSession('privacy-resumed', 3, []), scope: { type: 'terminal' as const, targetId: 'closed' } },
|
|
];
|
|
const aliases = sessions.map(session => {
|
|
setReversibleModelPrivacy(session.id, true);
|
|
return service.redact(session.id, '8.8.8.8');
|
|
});
|
|
const sdkCleanups: string[] = [];
|
|
const privacyCleanups: string[] = [];
|
|
const outputCleanups: string[] = [];
|
|
const previousWindow = globalThis.window;
|
|
const previousSessions = latestAISessionsSnapshot;
|
|
const previousActiveSessionMap = latestAIActiveSessionMapSnapshot;
|
|
t.mock.method(localStorageAdapter, 'write', () => true);
|
|
Object.defineProperty(globalThis, 'window', {
|
|
configurable: true,
|
|
value: {
|
|
dispatchEvent: () => true,
|
|
netcatty: {
|
|
aiSdkAgentCleanup: async (id: string) => {
|
|
sdkCleanups.push(id);
|
|
return { ok: true };
|
|
},
|
|
aiPrivacyClearSession: async (id: string) => {
|
|
privacyCleanups.push(id);
|
|
service.clearSession(id);
|
|
return { ok: true };
|
|
},
|
|
deleteChatToolOutputsTemp: async (id: string) => {
|
|
outputCleanups.push(id);
|
|
return { deletedCount: 1 };
|
|
},
|
|
},
|
|
},
|
|
});
|
|
setLatestAISessionsSnapshot(sessions);
|
|
setLatestAIActiveSessionMapSnapshot({
|
|
'terminal:closed': 'privacy-orphan',
|
|
'terminal:open': 'privacy-live',
|
|
'terminal:resumed-into': 'privacy-resumed',
|
|
});
|
|
|
|
try {
|
|
cleanupOrphanedAISessions(new Set(['open', 'resumed-into']));
|
|
|
|
assert.equal(latestAISessionsSnapshot, sessions);
|
|
assert.deepEqual(latestAIActiveSessionMapSnapshot, {
|
|
'terminal:open': 'privacy-live',
|
|
'terminal:resumed-into': 'privacy-resumed',
|
|
});
|
|
assert.deepEqual(sdkCleanups, ['privacy-orphan']);
|
|
assert.deepEqual(privacyCleanups, []);
|
|
assert.deepEqual(outputCleanups, []);
|
|
for (const [index, session] of sessions.entries()) {
|
|
assert.equal(hasReversibleModelPrivacy(session.id), true);
|
|
assert.equal(service.redact(session.id, '8.8.8.8'), aliases[index]);
|
|
assert.equal(service.restore(session.id, aliases[index]), '8.8.8.8');
|
|
}
|
|
assert.throws(() => service.checkSession('privacy-next'), /session limit reached/);
|
|
|
|
cleanupDeletedAIChatSessions(['privacy-orphan']);
|
|
|
|
assert.deepEqual(privacyCleanups, ['privacy-orphan']);
|
|
assert.deepEqual(outputCleanups, ['privacy-orphan']);
|
|
assert.equal(hasReversibleModelPrivacy('privacy-orphan'), false);
|
|
assert.equal(service.hasSession('privacy-orphan'), false);
|
|
assert.throws(() => service.checkSession('privacy-orphan'), /start a new chat/);
|
|
assert.equal(service.checkSession('privacy-next'), true);
|
|
for (const [index, session] of sessions.entries()) {
|
|
if (session.id === 'privacy-orphan') continue;
|
|
assert.equal(hasReversibleModelPrivacy(session.id), true);
|
|
assert.equal(service.restore(session.id, aliases[index]), '8.8.8.8');
|
|
}
|
|
} finally {
|
|
for (const session of sessions) setReversibleModelPrivacy(session.id, false);
|
|
setLatestAISessionsSnapshot(previousSessions ?? []);
|
|
setLatestAIActiveSessionMapSnapshot(previousActiveSessionMap ?? {});
|
|
Object.defineProperty(globalThis, 'window', { configurable: true, value: previousWindow });
|
|
}
|
|
});
|
|
|
|
test('serializeSessionsForStorage strips oldest ciphertext before dropping visible sessions', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const ciphertext = 'gAAAA'.repeat(50000); // ~250 KB of ciphertext per message
|
|
const messages = () => [{
|
|
id: 'm',
|
|
role: 'assistant' as const,
|
|
content: 'hello',
|
|
timestamp: 0,
|
|
providerContinuation: {
|
|
reasoningParts: [{ text: '', providerOptions: { openai: { reasoningEncryptedContent: ciphertext } } }],
|
|
},
|
|
}];
|
|
const sessions = [
|
|
makeSession('newest', 3, messages()),
|
|
makeSession('older', 2, messages()),
|
|
makeSession('oldest', 1, messages()),
|
|
];
|
|
|
|
const hasCiphertext = (result: { sessions: AISession[] }) =>
|
|
result.sessions.some(s => s.messages.some(m =>
|
|
m.providerContinuation?.reasoningParts?.some(p => typeof p.providerOptions?.openai?.reasoningEncryptedContent === 'string')));
|
|
|
|
// Removing replay-only ciphertext from the oldest session fits the budget,
|
|
// so every visible chat remains available after restart.
|
|
const withOldestCiphertextStripped = serializeSessionsForStorage(sessions, 600 * 1024);
|
|
assert.deepEqual(
|
|
withOldestCiphertextStripped.sessions.map(s => s.id),
|
|
['newest', 'older', 'oldest'],
|
|
);
|
|
assert.equal(hasCiphertext(withOldestCiphertextStripped), true);
|
|
assert.ok(withOldestCiphertextStripped.json.length <= 600 * 1024);
|
|
|
|
// Tight budget that even a single session exceeds: ciphertext stripped but
|
|
// the visible conversation content survives.
|
|
const withCiphertextStripped = serializeSessionsForStorage(sessions, 220 * 1024);
|
|
assert.ok(withCiphertextStripped.json.length <= 220 * 1024);
|
|
assert.equal(hasCiphertext(withCiphertextStripped), false);
|
|
assert.deepEqual(withCiphertextStripped.sessions.map(s => s.id), ['newest', 'older', 'oldest']);
|
|
assert.equal(withCiphertextStripped.sessions[0].messages[0].content, 'hello');
|
|
});
|
|
|
|
test('serializeSessionsForStorage keeps new ciphertext when an oversized old chat must be dropped', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const ciphertext = 'gAAAA'.repeat(20 * 1024); // ~100 KB
|
|
const newest = makeSession('newest', 2, [{
|
|
id: 'new-message',
|
|
role: 'assistant',
|
|
content: 'new visible chat',
|
|
timestamp: 2,
|
|
providerContinuation: {
|
|
source: { providerConfigId: 'p', providerType: 'openai', modelId: 'm' },
|
|
reasoningParts: [{ text: '', providerOptions: { openai: { reasoningEncryptedContent: ciphertext } } }],
|
|
},
|
|
}]);
|
|
const oversizedOld = makeSession('oldest', 1, [{
|
|
id: 'old-message',
|
|
role: 'user',
|
|
content: 'x'.repeat(300 * 1024),
|
|
timestamp: 1,
|
|
}]);
|
|
|
|
const result = serializeSessionsForStorage([oversizedOld, newest], 200 * 1024);
|
|
|
|
assert.deepEqual(result.sessions.map(session => session.id), ['newest']);
|
|
assert.equal(
|
|
result.sessions[0].messages[0].providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
ciphertext,
|
|
);
|
|
assert.ok(result.json.length <= 200 * 1024);
|
|
});
|
|
|
|
test('serializeSessionsForStorage prioritizes a usable newest chat over older visible history', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const ciphertext = 'gAAAA'.repeat(20 * 1024); // ~100 KB
|
|
const newest = makeSession('newest', 2, [{
|
|
id: 'new-message',
|
|
role: 'assistant',
|
|
content: 'new visible chat',
|
|
timestamp: 2,
|
|
providerContinuation: {
|
|
source: { providerConfigId: 'p', providerType: 'openai', modelId: 'm' },
|
|
reasoningParts: [{ text: '', providerOptions: { openai: { reasoningEncryptedContent: ciphertext } } }],
|
|
},
|
|
}]);
|
|
const olderVisible = makeSession('oldest', 1, [{
|
|
id: 'old-message',
|
|
role: 'user',
|
|
content: 'x'.repeat(100 * 1024),
|
|
timestamp: 1,
|
|
}]);
|
|
|
|
const result = serializeSessionsForStorage([olderVisible, newest], 150 * 1024);
|
|
|
|
assert.deepEqual(result.sessions.map(session => session.id), ['newest']);
|
|
assert.equal(
|
|
result.sessions[0].messages[0].providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
ciphertext,
|
|
);
|
|
assert.ok(result.json.length <= 150 * 1024);
|
|
});
|
|
|
|
test('serializeSessionsForStorage keeps the newest replayable turn in one oversized chat', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const ciphertext = 'gAAAA'.repeat(20 * 1024); // ~100 KB per reasoning turn
|
|
const reasoning = (itemId: string) => ({
|
|
source: { providerConfigId: 'p', providerType: 'openai', modelId: 'm' },
|
|
reasoningParts: [{
|
|
text: '',
|
|
providerOptions: { openai: { itemId, reasoningEncryptedContent: ciphertext } },
|
|
}],
|
|
});
|
|
const session = makeSession('active', 1, [
|
|
{
|
|
id: 'assistant-old',
|
|
role: 'assistant',
|
|
content: 'old turn',
|
|
timestamp: 1,
|
|
providerContinuation: reasoning('rs_old'),
|
|
toolCalls: [{ id: 'call-old', name: 'terminal_execute', arguments: { command: 'pwd' } }],
|
|
},
|
|
{
|
|
id: 'tool-old',
|
|
role: 'tool',
|
|
content: '',
|
|
timestamp: 2,
|
|
toolResults: [{ toolCallId: 'call-old', content: '/tmp' }],
|
|
},
|
|
{
|
|
id: 'assistant-new',
|
|
role: 'assistant',
|
|
content: 'new turn',
|
|
timestamp: 3,
|
|
providerContinuation: reasoning('rs_new'),
|
|
toolCalls: [{ id: 'call-new', name: 'terminal_execute', arguments: { command: 'ls' } }],
|
|
},
|
|
{
|
|
id: 'tool-new',
|
|
role: 'tool',
|
|
content: '',
|
|
timestamp: 4,
|
|
toolResults: [{ toolCallId: 'call-new', content: 'file.txt' }],
|
|
},
|
|
]);
|
|
|
|
const result = serializeSessionsForStorage([session], 150 * 1024);
|
|
|
|
assert.ok(result.json.length <= 150 * 1024);
|
|
assert.deepEqual(result.sessions[0].messages.map(message => message.id), [
|
|
'assistant-old',
|
|
'tool-old',
|
|
'assistant-new',
|
|
'tool-new',
|
|
]);
|
|
assert.equal(
|
|
result.sessions[0].messages[0].providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
undefined,
|
|
);
|
|
assert.equal(
|
|
result.sessions[0].messages[2].providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
ciphertext,
|
|
);
|
|
});
|
|
|
|
test('serializeSessionsForStorage drops compacted ciphertext before protecting the newest chat', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const ciphertext = 'gAAAA'.repeat(20 * 1024); // ~100 KB per reasoning turn
|
|
const compactedMessages = Array.from({ length: 17 }, (_, index) => ({
|
|
id: `compacted-${index}`,
|
|
role: 'assistant' as const,
|
|
content: `compacted turn ${index}`,
|
|
timestamp: index,
|
|
providerContinuation: {
|
|
reasoningParts: [{
|
|
text: '',
|
|
providerOptions: {
|
|
openai: { itemId: `rs_${index}`, reasoningEncryptedContent: ciphertext },
|
|
},
|
|
}],
|
|
},
|
|
}));
|
|
const newest = {
|
|
...makeSession('newest', 2, [
|
|
...compactedMessages,
|
|
{
|
|
id: 'recent',
|
|
role: 'assistant',
|
|
content: 'recent turn',
|
|
timestamp: 18,
|
|
providerContinuation: {
|
|
reasoningParts: [{
|
|
text: '',
|
|
providerOptions: {
|
|
openai: { itemId: 'rs_recent', reasoningEncryptedContent: ciphertext },
|
|
},
|
|
}],
|
|
},
|
|
},
|
|
]),
|
|
contextCompaction: {
|
|
summary: 'The first 17 turns were summarized.',
|
|
compactedMessageCount: 17,
|
|
},
|
|
};
|
|
const olderVisible = makeSession('older', 1, [{
|
|
id: 'older-visible',
|
|
role: 'user',
|
|
content: 'x'.repeat(600 * 1024),
|
|
timestamp: 1,
|
|
}]);
|
|
|
|
const result = serializeSessionsForStorage([olderVisible, newest]);
|
|
|
|
assert.deepEqual(result.sessions.map(session => session.id), ['newest', 'older']);
|
|
assert.ok(result.json.length <= 2 * 1024 * 1024);
|
|
const persistedNewest = result.sessions[0];
|
|
for (const message of persistedNewest.messages.slice(0, 17)) {
|
|
assert.equal(
|
|
message.providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
undefined,
|
|
);
|
|
}
|
|
assert.equal(
|
|
persistedNewest.messages[17].providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
ciphertext,
|
|
);
|
|
});
|
|
|
|
test('serializeSessionsForStorage shifts the compaction boundary when trimming old messages', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const ciphertext = 'enc'.repeat(100);
|
|
const messages = Array.from({ length: 250 }, (_, index) => ({
|
|
id: `message-${index}`,
|
|
role: 'assistant' as const,
|
|
content: `turn ${index}`,
|
|
timestamp: index,
|
|
providerContinuation: {
|
|
reasoningParts: [{
|
|
text: '',
|
|
providerOptions: {
|
|
openai: { itemId: `rs_${index}`, reasoningEncryptedContent: ciphertext },
|
|
},
|
|
}],
|
|
},
|
|
}));
|
|
const session = {
|
|
...makeSession('trimmed', 1, messages),
|
|
contextCompaction: {
|
|
summary: 'The first 100 messages were summarized.',
|
|
compactedMessageCount: 100,
|
|
},
|
|
};
|
|
|
|
const result = serializeSessionsForStorage([session]);
|
|
const persisted = result.sessions[0];
|
|
|
|
assert.equal(persisted.messages.length, 200);
|
|
assert.equal(persisted.messages[0].id, 'message-50');
|
|
assert.equal(persisted.contextCompaction?.compactedMessageCount, 50);
|
|
assert.equal(
|
|
persisted.messages[49].providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
undefined,
|
|
);
|
|
assert.equal(
|
|
persisted.messages[50].providerContinuation
|
|
?.reasoningParts?.[0].providerOptions?.openai?.reasoningEncryptedContent,
|
|
ciphertext,
|
|
);
|
|
});
|
|
|
|
test('serializeSessionsForStorage does not trim between a tool call and its result', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const messages = Array.from({ length: 250 }, (_, index) => ({
|
|
id: `message-${index}`,
|
|
role: 'user' as const,
|
|
content: `turn ${index}`,
|
|
timestamp: index,
|
|
}));
|
|
messages[49] = {
|
|
id: 'assistant-call',
|
|
role: 'assistant',
|
|
content: 'Running it.',
|
|
timestamp: 49,
|
|
toolCalls: [{ id: 'call-1', name: 'terminal_execute', arguments: { command: 'pwd' } }],
|
|
} as never;
|
|
messages[50] = {
|
|
id: 'tool-result',
|
|
role: 'tool',
|
|
content: '',
|
|
timestamp: 50,
|
|
toolResults: [{ toolCallId: 'call-1', content: '/tmp' }],
|
|
} as never;
|
|
const session = {
|
|
...makeSession('tool-boundary', 1, messages),
|
|
contextCompaction: {
|
|
summary: 'The first 10 messages were summarized.',
|
|
compactedMessageCount: 10,
|
|
},
|
|
};
|
|
|
|
const result = serializeSessionsForStorage([session]);
|
|
const persisted = result.sessions[0];
|
|
|
|
assert.equal(persisted.messages.length, 201);
|
|
assert.equal(persisted.messages[0].id, 'assistant-call');
|
|
assert.equal(persisted.messages[1].id, 'tool-result');
|
|
assert.equal(persisted.contextCompaction?.compactedMessageCount, 0);
|
|
});
|
|
|
|
test('writeSessionsForStorage retries below nominal budgets after a quota failure', async () => {
|
|
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const writes: string[] = [];
|
|
let stored: string | undefined;
|
|
const previousLocalStorage = globalThis.localStorage;
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: {
|
|
getItem: () => null,
|
|
setItem: (_key: string, value: string) => {
|
|
writes.push(value);
|
|
if (value.length > 350 * 1024) {
|
|
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
|
}
|
|
stored = value;
|
|
},
|
|
removeItem: () => {},
|
|
},
|
|
});
|
|
try {
|
|
// The retry loop must attempt progressively smaller payloads (here the
|
|
// ciphertext stripping at the tighter budget) before reporting failure.
|
|
const huge = 'x'.repeat(260 * 1024);
|
|
const ciphertext = 'gAAAA'.repeat(30 * 1024); // ~150 KB
|
|
const sessions = [makeSession('s', 1, [{
|
|
id: 'm',
|
|
role: 'user' as const,
|
|
content: huge,
|
|
timestamp: 0,
|
|
providerContinuation: {
|
|
reasoningParts: [{ text: '', providerOptions: { openai: { reasoningEncryptedContent: ciphertext } } }],
|
|
},
|
|
}])];
|
|
assert.equal(writeSessionsForStorage(sessions), true);
|
|
assert.equal(writes.length, 2);
|
|
assert.equal(stored, writes[1]);
|
|
assert.ok(writes[writes.length - 1].length < writes[0].length);
|
|
} finally {
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: previousLocalStorage,
|
|
});
|
|
}
|
|
});
|
|
|
|
test('writeSessionsForStorage reduces several small sessions to fit a sub-512 KB quota', async () => {
|
|
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const writes: string[] = [];
|
|
let stored: string | undefined;
|
|
const previousLocalStorage = globalThis.localStorage;
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: {
|
|
getItem: () => null,
|
|
setItem: (_key: string, value: string) => {
|
|
writes.push(value);
|
|
if (value.length > 300 * 1024) {
|
|
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
|
}
|
|
stored = value;
|
|
},
|
|
removeItem: () => {},
|
|
},
|
|
});
|
|
|
|
try {
|
|
const sessions = Array.from({ length: 10 }, (_, index) => makeSession(
|
|
`session-${index}`,
|
|
10 - index,
|
|
[{
|
|
id: `message-${index}`,
|
|
role: 'user' as const,
|
|
content: 'x'.repeat(40 * 1024),
|
|
timestamp: index,
|
|
}],
|
|
));
|
|
|
|
assert.equal(writeSessionsForStorage(sessions), true);
|
|
assert.ok(writes[0].length > 300 * 1024);
|
|
assert.ok(stored);
|
|
assert.ok(stored.length <= 300 * 1024);
|
|
assert.ok((JSON.parse(stored) as AISession[]).length < sessions.length);
|
|
} finally {
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: previousLocalStorage,
|
|
});
|
|
}
|
|
});
|
|
|
|
test('serializeSessionsForStorage truncates slightly-over-cap tool results to strictly smaller sizes', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
// Just over the 8 KiB cap: the truncation marker must not make the degraded
|
|
// copy larger than the original, or the ladder could evict a session whose
|
|
// unmodified JSON would have fit the budget.
|
|
for (const oversize of [8193, 8266, 20000]) {
|
|
const session = makeSession('near-cap', 1, [{
|
|
id: 'tool-message',
|
|
role: 'tool',
|
|
content: '',
|
|
timestamp: 1,
|
|
toolResults: [{ toolCallId: 'call-1', content: 'z'.repeat(oversize) }],
|
|
}]);
|
|
const fullJson = JSON.stringify([session]);
|
|
const result = serializeSessionsForStorage([session], fullJson.length - 10);
|
|
const content = result.sessions[0].messages[0].toolResults?.[0].content ?? '';
|
|
assert.ok(content.length <= 8 * 1024, `cap respected for ${oversize}`);
|
|
assert.ok(
|
|
JSON.stringify(result.sessions).length < fullJson.length,
|
|
`degraded copy smaller than original for ${oversize}`,
|
|
);
|
|
assert.ok(content.includes('truncated'));
|
|
}
|
|
});
|
|
|
|
test('serializeSessionsForStorage sheds oversized tool output before dropping visible sessions', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const newest = makeSession('newest', 2, [{
|
|
id: 'new-message',
|
|
role: 'assistant',
|
|
content: 'still-open chat',
|
|
timestamp: 2,
|
|
}]);
|
|
const toolBulk = makeSession('tool-bulk', 1, [{
|
|
id: 'tool-message',
|
|
role: 'tool',
|
|
content: '',
|
|
timestamp: 1,
|
|
toolResults: [{ toolCallId: 'call-1', content: 'z'.repeat(400 * 1024) }],
|
|
}]);
|
|
|
|
const result = serializeSessionsForStorage([toolBulk, newest], 100 * 1024);
|
|
|
|
// The bloated tool result must not evict the other visible chat.
|
|
assert.deepEqual(result.sessions.map(session => session.id), ['newest', 'tool-bulk']);
|
|
assert.ok(result.json.length <= 100 * 1024);
|
|
const persistedToolContent = result.sessions[1].messages[0].toolResults?.[0].content;
|
|
assert.ok(persistedToolContent);
|
|
assert.ok(persistedToolContent.length <= 9 * 1024);
|
|
assert.ok(persistedToolContent.includes('truncated'));
|
|
assert.ok(persistedToolContent.startsWith('zzz'));
|
|
assert.equal(result.sessions[0].messages[0].content, 'still-open chat');
|
|
});
|
|
|
|
test('writeSessionsForStorage keeps every chat by shedding tool output under quota pressure', async () => {
|
|
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
let stored: string | undefined;
|
|
const previousLocalStorage = globalThis.localStorage;
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: {
|
|
getItem: () => null,
|
|
setItem: (_key: string, value: string) => {
|
|
if (value.length > 300 * 1024) {
|
|
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
|
}
|
|
stored = value;
|
|
},
|
|
removeItem: () => {},
|
|
},
|
|
});
|
|
|
|
try {
|
|
const sessions = Array.from({ length: 10 }, (_, index) => makeSession(
|
|
`session-${index}`,
|
|
10 - index,
|
|
[{
|
|
id: `message-${index}`,
|
|
role: 'tool' as const,
|
|
content: '',
|
|
timestamp: index,
|
|
toolResults: [{ toolCallId: `call-${index}`, content: 'z'.repeat(40 * 1024) }],
|
|
}],
|
|
));
|
|
|
|
assert.equal(writeSessionsForStorage(sessions), true);
|
|
assert.ok(stored);
|
|
assert.ok(stored.length <= 300 * 1024);
|
|
const persisted = JSON.parse(stored) as AISession[];
|
|
assert.deepEqual(
|
|
persisted.map(session => session.id),
|
|
sessions.map(session => session.id),
|
|
);
|
|
// Degradation sheds only as many messages as the budget demands, so at
|
|
// least one chat keeps its full tool output while the persisted set stays
|
|
// complete. Assert completion first; truncation second.
|
|
const shedContents = persisted.map(
|
|
session => session.messages[0].toolResults?.[0].content ?? '',
|
|
);
|
|
assert.ok(shedContents.some(content => content.includes('truncated')));
|
|
assert.ok(shedContents.some(content => content.startsWith('zzz') && !content.includes('truncated')));
|
|
} finally {
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: previousLocalStorage,
|
|
});
|
|
}
|
|
});
|
|
|
|
test('writeSessionsForStorage makes a final attempt with only the newest session', async () => {
|
|
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const writes: string[] = [];
|
|
let stored: string | undefined;
|
|
const previousLocalStorage = globalThis.localStorage;
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: {
|
|
getItem: () => null,
|
|
setItem: (_key: string, value: string) => {
|
|
writes.push(value);
|
|
if (value.length > 50 * 1024) {
|
|
throw new DOMException('quota exceeded', 'QuotaExceededError');
|
|
}
|
|
stored = value;
|
|
},
|
|
removeItem: () => {},
|
|
},
|
|
});
|
|
|
|
try {
|
|
const sessions = Array.from({ length: 10 }, (_, index) => makeSession(
|
|
`session-${index}`,
|
|
10 - index,
|
|
[{
|
|
id: `message-${index}`,
|
|
role: 'user' as const,
|
|
content: 'x'.repeat(40 * 1024),
|
|
timestamp: index,
|
|
}],
|
|
));
|
|
|
|
assert.equal(writeSessionsForStorage(sessions), true);
|
|
assert.equal(writes.length, 6);
|
|
assert.ok(stored);
|
|
const persisted = JSON.parse(stored) as AISession[];
|
|
assert.deepEqual(persisted.map(session => session.id), ['session-0']);
|
|
assert.ok(stored.length <= 50 * 1024);
|
|
} finally {
|
|
Object.defineProperty(globalThis, 'localStorage', {
|
|
configurable: true,
|
|
value: previousLocalStorage,
|
|
});
|
|
}
|
|
});
|
|
|
|
function freezeHistory<T>(value: T): T {
|
|
if (value && typeof value === 'object') {
|
|
Object.values(value).forEach(freezeHistory);
|
|
Object.freeze(value);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function makePersistenceHistory(count: number, activeMessages = 6): AISession[] {
|
|
return Array.from({ length: count }, (_, index) => makeSession(
|
|
`session-${index}`,
|
|
count - index,
|
|
Array.from({ length: index === 0 ? activeMessages : 6 }, (_, messageIndex) => ({
|
|
id: `message-${index}-${messageIndex}`,
|
|
role: messageIndex % 2 ? 'assistant' : 'user',
|
|
content: 'ordinary text '.repeat(8),
|
|
timestamp: messageIndex,
|
|
...(messageIndex % 2 ? {
|
|
toolResults: [{ toolCallId: `tool-${messageIndex}`, content: 'sample output '.repeat(700) }],
|
|
providerContinuation: {
|
|
reasoningParts: [{
|
|
text: 'reasoning',
|
|
providerOptions: { openai: { reasoningEncryptedContent: 'x'.repeat(256) } },
|
|
}],
|
|
},
|
|
} : {}),
|
|
})),
|
|
));
|
|
}
|
|
|
|
for (const [count, activeMessages] of [[20, 6], [200, 6], [20, 200]]) {
|
|
test(`fitting history serializes only retained full sessions (${count} chats, ${activeMessages} active messages)`, async (t) => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const sessions = freezeHistory(makePersistenceHistory(count, activeMessages));
|
|
const expected = sessions.slice(0, 50);
|
|
const expectedJson = JSON.stringify(expected);
|
|
const stringify = t.mock.method(JSON, 'stringify');
|
|
|
|
const result = serializeSessionsForStorage(sessions);
|
|
|
|
assert.equal(stringify.mock.callCount(), expected.length);
|
|
assert.equal(result.json, expectedJson);
|
|
assert.deepEqual(result.sessions, expected);
|
|
assert.equal(result.sessions[0], sessions[0]);
|
|
});
|
|
}
|
|
|
|
test('fit-first budget keeps string-length units and exact-fit replay data without mutating input', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const sessions = makePersistenceHistory(1);
|
|
sessions[0].messages[0].content = '\u4e2d\u6587\ud83d\ude00'.repeat(100);
|
|
freezeHistory(sessions);
|
|
const fullJson = JSON.stringify(sessions);
|
|
assert.ok(Buffer.byteLength(fullJson) > fullJson.length);
|
|
for (const budget of [fullJson.length, fullJson.length + 1]) {
|
|
assert.equal(serializeSessionsForStorage(sessions, budget).json, fullJson);
|
|
}
|
|
const overflow = serializeSessionsForStorage(sessions, fullJson.length - 1);
|
|
assert.ok(overflow.json.length < fullJson.length);
|
|
assert.equal(JSON.stringify(sessions), fullJson);
|
|
});
|
|
|
|
test('fit-first empty history preserves output even below the minimum array budget', async () => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
for (const budget of [0, 1, 2, 3]) {
|
|
assert.deepEqual(serializeSessionsForStorage([], budget), { json: '[]', sessions: [] });
|
|
}
|
|
});
|
|
|
|
test('synced storage bypasses fit-first pruning and non-quota failures still propagate', async (t) => {
|
|
const { writeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const sessions = freezeHistory(makePersistenceHistory(51, 201));
|
|
const read = t.mock.method(localStorageAdapter, 'read', () => ({ enabled: true }));
|
|
const write = t.mock.method(localStorageAdapter, 'write', () => false);
|
|
const writeString = t.mock.method(localStorageAdapter, 'writeString', () => true);
|
|
assert.equal(writeSessionsForStorage(sessions), false);
|
|
assert.equal(write.mock.callCount(), 1);
|
|
assert.equal(write.mock.calls[0].arguments[1], sessions);
|
|
assert.equal(writeString.mock.callCount(), 0);
|
|
|
|
read.mock.mockImplementation(() => ({ enabled: false }));
|
|
const error = new Error('non-quota storage failure');
|
|
writeString.mock.mockImplementation(() => { throw error; });
|
|
assert.throws(() => writeSessionsForStorage(sessions), candidate => candidate === error);
|
|
assert.equal(writeString.mock.callCount(), 1);
|
|
});
|
|
|
|
for (const [budget, expectedCalls] of [[128 * 1024, 160], [0, 161]]) {
|
|
test(`overflow reuses prepared full JSON at budget ${budget}`, async (t) => {
|
|
const { serializeSessionsForStorage } = await import('./aiStateSnapshots');
|
|
const sessions = freezeHistory(makePersistenceHistory(20));
|
|
const stringify = t.mock.method(JSON, 'stringify');
|
|
const result = serializeSessionsForStorage(sessions, budget);
|
|
// Same work as the original ladder: no second full-session serialization
|
|
// after the fit check, even when a last-resort degraded chat is needed.
|
|
assert.equal(stringify.mock.callCount(), expectedCalls);
|
|
assert.equal(result.sessions.length, budget === 0 ? 1 : 4);
|
|
});
|
|
}
|