mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 23:08:36 +00:00
Chats: a damaged or older chat file with a missing date, title or message text no longer takes the whole chat page down
SOAK-APP found that a chat file saved without updatedAt blanked the page: recentChats sorted with b.updatedAt.localeCompare(...), a TypeError on the missing value, and the description of a chat read message.content.replace(...).trim() on a missing text. Two layers, no new text: - lib/recent-chats.ts tolerates a missing or odd field: a missing date is empty and sorts last, a message that is not an object or whose text is not a string is skipped or read as empty, so the list never throws. - lib/session-repair.ts (repairSession, applied in the store's fixSession to every chat read from the host or the browser's old copy) makes every field the lists read a string: a missing updatedAt takes createdAt (or stays empty), a missing or empty title is the existing "New conversation", a missing workspace is empty, messages that are not objects are dropped and their id, role, text and date made strings, a non-string model or reasoning is removed. A well-formed chat comes back exactly as it was. relTimeShort shows no time instead of "NaNm" for a date it cannot read. tests/damaged-chat-fields.test.mjs: a store with chats lacking updatedAt, title, workspace and message text beside good ones lists every chat (dated ones in activity order, the undated last), every description is read without throwing, repaired chats have string fields and well-formed ones are unchanged; on the base the same list throws TypeError (localeCompare, replace). Linux host suite 1930 passed / 0 failed; 34 chat-related test files on Windows 145 passed / 0 failed; live load in headless Chrome with five chats, three of them damaged (par/guie1117/live-damaged5-*): on the base code the chat page lists 0 chats, with this change all 6 are listed, the first opens, no page error.
This commit is contained in:
1 parent
27815281cc
commit
037be49479
5 files changed
+127
-5
No files matched your search
@@ -44,6 +44,8 @@ export function relTime(iso: string | number | Date): string {
|
||||
*/
|
||||
export function relTimeShort(iso: string | number | Date): string {
|
||||
const then = new Date(iso).getTime();
|
||||
if (!Number.isFinite(then))
|
||||
return ''; // a chat file without a usable date shows no time, not "NaNm"
|
||||
const diff = Date.now() - then;
|
||||
if (diff < 45000)
|
||||
return 'now';
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type { Session } from './types';
|
||||
|
||||
/** The time a chat was last used, as text that sorts: a missing or odd value is empty, which sorts last (a damaged or older chat file must never take the page down). */
|
||||
const activityOf = (session: Session) => (typeof session?.updatedAt === 'string' ? session.updatedAt : '');
|
||||
|
||||
export function recentChats(sessions: Session[], activeId?: string | null) {
|
||||
const ordered = sessions.filter(session => !session.archived)
|
||||
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
||||
const ordered = sessions.filter(session => session && !session.archived)
|
||||
.sort((a, b) => activityOf(b).localeCompare(activityOf(a)));
|
||||
const current = ordered.find(session => session.id === activeId);
|
||||
const latest = ordered.filter(session => session.id !== current?.id).slice(0, 5);
|
||||
const ids = new Set([...latest, ...(current ? [current] : [])].map(session => session.id));
|
||||
@@ -11,7 +14,8 @@ export function recentChats(sessions: Session[], activeId?: string | null) {
|
||||
}
|
||||
|
||||
export function recentChatDescription(session: Session) {
|
||||
const message = session.messages.filter(message => message.role === 'user').at(-1) ?? session.messages.at(-1);
|
||||
const text = message?.content.replace(/\s+/g, ' ').trim() || 'No messages yet';
|
||||
const messages = Array.isArray(session?.messages) ? session.messages.filter(message => !!message && typeof message === 'object') : [];
|
||||
const message = messages.filter(message => message.role === 'user').at(-1) ?? messages.at(-1);
|
||||
const text = (typeof message?.content === 'string' ? message.content : '').replace(/\s+/g, ' ').trim() || 'No messages yet';
|
||||
return text.length > 160 ? `${text.slice(0, 157).trimEnd()}…` : text;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Session } from './types';
|
||||
|
||||
/**
|
||||
* A chat read from a saved file or the browser's old copy, as the page can safely work with it. A damaged, hand-edited or older file may lack fields the lists read
|
||||
* (a missing `updatedAt` made `localeCompare` throw and blanked the whole chat page; a missing title or message text made a `.trim()` throw). Every text field is
|
||||
* made a string, a missing date takes the other date (or stays empty and sorts last), a missing title is the existing "New conversation", and a message that is
|
||||
* not an object is dropped. Whatever is well-formed is returned as it was.
|
||||
*/
|
||||
const text = (value: unknown) => (typeof value === 'string' ? value : '');
|
||||
const isObject = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
export function repairSession(session: Session): Session {
|
||||
const raw = session as unknown as Record<string, unknown>;
|
||||
const createdAt = text(raw.createdAt), updatedAt = text(raw.updatedAt) || createdAt;
|
||||
const hasTitle = typeof raw.title === 'string' && raw.title.trim() !== '';
|
||||
const messages = (Array.isArray(raw.messages) ? raw.messages : []).filter(isObject).map((message, i) => {
|
||||
const m = message as Record<string, unknown>;
|
||||
const fixed: Record<string, unknown> = { ...m, id: typeof m.id === 'string' ? m.id : `m${i}`, role: typeof m.role === 'string' ? m.role : 'assistant', content: text(m.content), at: text(m.at) };
|
||||
if (m.model !== undefined && typeof m.model !== 'string') delete fixed.model;
|
||||
if (m.reasoning !== undefined && typeof m.reasoning !== 'string') delete fixed.reasoning;
|
||||
return fixed;
|
||||
}) as unknown as Session['messages'];
|
||||
return {
|
||||
...session,
|
||||
title: hasTitle ? (raw.title as string) : 'New conversation',
|
||||
...(hasTitle ? {} : { defaultTitle: true }),
|
||||
createdAt: createdAt || updatedAt,
|
||||
updatedAt,
|
||||
workspace: text(raw.workspace),
|
||||
messages,
|
||||
...(isObject(raw.preferences) || raw.preferences === undefined ? {} : { preferences: undefined }),
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { DEFAULT_CONTENT_FS, DEFAULT_UI_SCALE, SIZE_DEFAULTS_VERSION, savedSizes
|
||||
import { detectLanguage } from './language-detect';
|
||||
import { validWhileBusy, type WhileBusy } from './while-busy';
|
||||
import { validReplyWidth, type ReplyWidth } from './reply-width';
|
||||
import { repairSession } from './session-repair';
|
||||
import { addToQuotes, takeQuoteSources, type Quote } from './quotes';
|
||||
import { readAsk, type AgentAnswer, type AgentAsk } from './agent-ask';
|
||||
import { chatFailure, plainFailureText } from './plain-errors';
|
||||
@@ -269,7 +270,8 @@ const browserStorage: StorageLike = {
|
||||
get length() { return localStorage.length; },
|
||||
};
|
||||
/** A chat as the page works with it: a reply that was streaming when the page went away is marked interrupted, not left running. */
|
||||
function fixSession(session: Session): Session {
|
||||
function fixSession(raw: Session): Session {
|
||||
const session = repairSession(raw); // a damaged or older chat file must never take the page down (missing date, title, message text)
|
||||
return {
|
||||
...session,
|
||||
...(session.showcase && !session.showcaseAgentStates ? {agents:SHOWCASE_AGENTS,showcaseAgentStates:true}:{}),
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// SOAK-APP: a chat file saved without `updatedAt` blanked the whole chat page (TypeError on localeCompare in recent-chats.ts), and a missing title or message text threw on
|
||||
// .trim(). A damaged or older chat file must never take the page down: the lists tolerate missing or odd fields and the chats are repaired where they are read.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { build, transform } from 'esbuild';
|
||||
|
||||
const src = name => readFileSync(new URL(`../src/${name}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
|
||||
const load = async name => {
|
||||
const { code } = await transform(src(name), { loader: 'ts', format: 'esm' });
|
||||
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
};
|
||||
const { recentChats, recentChatDescription } = await load('lib/recent-chats.ts');
|
||||
const { repairSession } = await load('lib/session-repair.ts');
|
||||
// format.ts reads the language through ./i18n (the catalogs): bundled here with a one-line stand-in for it
|
||||
const formatBundle = await build({ entryPoints: [new URL('../src/lib/format.ts', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')], bundle: true, write: false, format: 'esm', platform: 'node', plugins: [{ name: 'i18n-stub', setup(b) {
|
||||
b.onResolve({ filter: /^\.\/i18n$/ }, () => ({ path: 'i18n', namespace: 'stub' }));
|
||||
b.onLoad({ filter: /.*/, namespace: 'stub' }, () => ({ contents: 'export const tr = s => s; export const localeTag = () => "en"; export const currentLanguage = () => "en";', loader: 'js' }));
|
||||
} }] });
|
||||
const { relTimeShort } = await import(`data:text/javascript;base64,${Buffer.from(formatBundle.outputFiles[0].text).toString('base64')}`);
|
||||
|
||||
const good = (id, updatedAt) => ({ id, title: `Chat ${id}`, createdAt: updatedAt, updatedAt, workspace: 'C:\\Work', messages: [{ id: 'm1', role: 'user', content: `Hello from ${id}`, at: updatedAt }] });
|
||||
const store = () => [
|
||||
good('a', '2026-10-10T10:00:00.000Z'),
|
||||
{ id: 'no-date', title: 'No date', workspace: 'C:\\Work', messages: [{ id: 'm', role: 'user', content: 'x', at: '' }] }, // no updatedAt, no createdAt
|
||||
{ id: 'no-title', createdAt: '2026-10-09T10:00:00.000Z', updatedAt: '2026-10-09T10:00:00.000Z', messages: [] }, // no title, no workspace
|
||||
{ id: 'odd', title: 42, updatedAt: 1760000000000, workspace: null, messages: [null, 'junk', { role: 'user' }, { role: 'assistant', content: 7 }, { content: 'text only' }] },
|
||||
{ id: 'no-messages', title: 'No messages', updatedAt: '2026-10-08T10:00:00.000Z' },
|
||||
good('b', '2026-10-07T10:00:00.000Z'),
|
||||
];
|
||||
|
||||
test('the recent-chats list tolerates a chat without a date, title or message text, and lists every other chat', () => {
|
||||
const sessions = store();
|
||||
const before = structuredClone(sessions);
|
||||
assert.doesNotThrow(() => recentChats(sessions, 'a'));
|
||||
const ids = recentChats(sessions, 'a').map(s => s.id);
|
||||
assert.deepEqual(ids.slice(0, 2), ['a', 'no-title'], 'dated chats keep their activity order');
|
||||
assert.ok(ids.indexOf('b') > -1 && ids.indexOf('no-messages') > -1, 'the other chats are listed');
|
||||
const withMissing = recentChats([sessions[1], sessions[0], sessions[5]]);
|
||||
assert.deepEqual(withMissing.map(s => s.id), ['a', 'b', 'no-date'], 'a missing date sorts last');
|
||||
assert.deepEqual(sessions, before, 'the source list is left as it was');
|
||||
for (const s of sessions) assert.doesNotThrow(() => recentChatDescription(s), s.id);
|
||||
assert.equal(recentChatDescription(sessions[3]), 'No messages yet', 'odd messages are skipped; the last user message has no text');
|
||||
assert.equal(recentChatDescription({ messages: [null, { role: 'user', content: 5 }, { role: 'assistant', content: 'Welcome' }] }), 'No messages yet', 'a user message whose text is not a string reads as empty, never throws');
|
||||
assert.equal(recentChatDescription(sessions[4]), 'No messages yet');
|
||||
assert.equal(recentChatDescription({}), 'No messages yet');
|
||||
});
|
||||
|
||||
test('a chat read from a saved file is repaired: every text field a list reads is a string, well-formed chats are untouched', () => {
|
||||
const [a, noDate, noTitle, odd, noMessages, b] = store().map(repairSession);
|
||||
assert.deepEqual(a, good('a', '2026-10-10T10:00:00.000Z'), 'a well-formed chat comes back as it was');
|
||||
assert.deepEqual(b, good('b', '2026-10-07T10:00:00.000Z'));
|
||||
for (const s of [a, noDate, noTitle, odd, noMessages, b]) {
|
||||
for (const field of ['id', 'title', 'createdAt', 'updatedAt', 'workspace']) assert.equal(typeof s[field], 'string', `${s.id}.${field}`);
|
||||
assert.ok(Array.isArray(s.messages));
|
||||
for (const m of s.messages) { assert.equal(typeof m.content, 'string'); assert.equal(typeof m.role, 'string'); assert.equal(typeof m.id, 'string'); }
|
||||
}
|
||||
assert.equal(noDate.updatedAt, '', 'no date stays empty (sorts last)');
|
||||
assert.equal(noTitle.title, 'New conversation'); assert.equal(noTitle.defaultTitle, true);
|
||||
assert.equal(noTitle.workspace, '');
|
||||
assert.equal(noTitle.updatedAt, '2026-10-09T10:00:00.000Z');
|
||||
assert.equal(odd.title, 'New conversation');
|
||||
assert.deepEqual(odd.messages.map(m => [m.role, m.content]), [['user', ''], ['assistant', ''], ['assistant', 'text only']], 'only objects are kept, their text made a string');
|
||||
assert.deepEqual(noMessages.messages, []);
|
||||
const order = recentChats([noDate, a, noTitle, odd, noMessages, b].map(s => s), 'a').map(s => s.id);
|
||||
assert.equal(order.length, 6, 'every chat is listed');
|
||||
assert.equal(repairSession(odd).updatedAt, odd.updatedAt, 'repairing twice changes nothing');
|
||||
});
|
||||
|
||||
test('no usable date shows no time instead of "NaNm"', () => {
|
||||
assert.equal(relTimeShort(''), '');
|
||||
assert.equal(relTimeShort(undefined), '');
|
||||
assert.equal(relTimeShort('not a date'), '');
|
||||
assert.equal(relTimeShort(new Date(Date.now() - 5 * 60_000).toISOString()), '5m');
|
||||
});
|
||||
|
||||
test('the store repairs every chat it reads (fixSession)', () => {
|
||||
const store = src('lib/store.ts');
|
||||
assert.match(store, /import \{ repairSession \} from '\.\/session-repair';/);
|
||||
assert.match(store, /function fixSession\(raw: Session\): Session \{\n const session = repairSession\(raw\);/);
|
||||
});
|
||||
Reference in new issue
Block a user