Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(chat): preserve long-session branch path

XZH0b9de7eb40b6
diff --git a/web/lib/message-branches.ts b/web/lib/message-branches.ts
index 0f7f4e3ef..a9989d450 100644
--- a/web/lib/message-branches.ts
+++ b/web/lib/message-branches.ts
@@ -8,28 +8,29 @@
* The UI shows a single linear path at a time. ``buildVisiblePath`` picks
* that path from the flat list: starting at the root (parent = null), at
* every branch point it follows ``selectedBranches[parent_id]`` if set,
- * otherwise it falls back to the latest-created child (the one most
- * recently added — including the still-in-flight optimistic message which
- * uses a negative client-side id and is treated as newer than any
- * persisted positive id).
+ * otherwise it falls back to the child with the longest continuation. That
+ * keeps an accidental short branch at an old node from hiding the rest of a
+ * long conversation while still treating equally deep siblings as it did
+ * before: the latest-created child wins, including an in-flight optimistic
+ * message.
*/
export interface BranchMessage {
- id?: number;
- parentMessageId?: number | null;
+ id?: number
+ parentMessageId?: number | null
}
-const ROOT_KEY = "null";
+const ROOT_KEY = 'null'
function parentKey(id: number | null | undefined): string {
- return id == null ? ROOT_KEY : String(id);
+ return id == null ? ROOT_KEY : String(id)
}
// Large offset that pushes every optimistic (negative-id) sibling above
// every persisted (positive-id) sibling without overflowing safe-integer
// arithmetic. ``Date.now()`` lives around 1.7e12 today, so 1e15 leaves
// ample headroom and stays well under ``Number.MAX_SAFE_INTEGER``.
-const OPTIMISTIC_RANK_OFFSET = 1e15;
+const OPTIMISTIC_RANK_OFFSET = 1e15
function siblingRank(message: BranchMessage): number {
// Optimistic, in-flight messages get a negative ``id`` on the client
@@ -38,8 +39,8 @@ function siblingRank(message: BranchMessage): number {
// the *more recent* one (more negative id) must rank higher so that a
// second optimistic send doesn't get hidden by the first. Persisted
// messages keep their natural id-ordered rank.
- const id = message.id ?? 0;
- return id < 0 ? OPTIMISTIC_RANK_OFFSET - id : id;
+ const id = message.id ?? 0
+ return id < 0 ? OPTIMISTIC_RANK_OFFSET - id : id
}
/** Parent key the visible-path walk should start from.
@@ -52,121 +53,155 @@ function siblingRank(message: BranchMessage): number {
*/
function walkStartKey<T extends BranchMessage>(
allMessages: T[],
- childrenByParent: Map<string, T[]>,
+ childrenByParent: Map<string, T[]>
): string {
- if ((childrenByParent.get(ROOT_KEY)?.length ?? 0) > 0) return ROOT_KEY;
+ if ((childrenByParent.get(ROOT_KEY)?.length ?? 0) > 0) return ROOT_KEY
- const known = new Set<number>();
+ const known = new Set<number>()
for (const msg of allMessages) {
- if (msg.id !== undefined) known.add(msg.id);
+ if (msg.id !== undefined) known.add(msg.id)
}
const orphans = allMessages.filter(
- (m) =>
- m.id !== undefined &&
- m.parentMessageId != null &&
- !known.has(m.parentMessageId),
- );
+ m => m.id !== undefined && m.parentMessageId != null && !known.has(m.parentMessageId)
+ )
// A pure cycle has no orphan entry point; fall back to the oldest message.
- const seeds =
- orphans.length > 0
- ? orphans
- : allMessages.filter((m) => m.id !== undefined);
- if (seeds.length === 0) return ROOT_KEY;
-
- const oldest = seeds.reduce((a, b) =>
- siblingRank(b) < siblingRank(a) ? b : a,
- );
- return parentKey(oldest.parentMessageId);
+ const seeds = orphans.length > 0 ? orphans : allMessages.filter(m => m.id !== undefined)
+ if (seeds.length === 0) return ROOT_KEY
+
+ const oldest = seeds.reduce((a, b) => (siblingRank(b) < siblingRank(a) ? b : a))
+ return parentKey(oldest.parentMessageId)
}
export interface SiblingInfo {
/** Number of alternative branches at this point, including this one. */
- total: number;
+ total: number
/** 1-based index of the current branch in chronological order. */
- index: number;
+ index: number
/** All sibling message ids in chronological (creation) order. */
- siblingIds: number[];
+ siblingIds: number[]
/** Parent message id (``null`` if at the session root). */
- parentId: number | null;
+ parentId: number | null
}
export interface VisiblePathResult<T extends BranchMessage> {
/** The flat message list to render, in chronological order. */
- messages: T[];
+ messages: T[]
/** Sibling info keyed by message id. Only present for messages whose
* parent has more than one child (i.e. branching points). */
- siblingsByMessageId: Map<number, SiblingInfo>;
+ siblingsByMessageId: Map<number, SiblingInfo>
+}
+
+function downstreamDepth<T extends BranchMessage>(
+ parentKey: string,
+ childrenByParent: Map<string, T[]>,
+ depthByParent: Map<string, number>,
+ activeParents: Set<string>
+): number {
+ const cached = depthByParent.get(parentKey)
+ if (cached !== undefined) return cached
+ if (activeParents.has(parentKey)) return 0
+
+ activeParents.add(parentKey)
+ let depth = 0
+ for (const child of childrenByParent.get(parentKey) ?? []) {
+ if (child.id === undefined) {
+ depth = Math.max(depth, 1)
+ continue
+ }
+ depth = Math.max(
+ depth,
+ 1 + downstreamDepth(String(child.id), childrenByParent, depthByParent, activeParents)
+ )
+ }
+ activeParents.delete(parentKey)
+ depthByParent.set(parentKey, depth)
+ return depth
}
export function buildVisiblePath<T extends BranchMessage>(
allMessages: T[],
- selectedBranches: Record<string, number> | undefined,
+ selectedBranches: Record<string, number> | undefined
): VisiblePathResult<T> {
// Group by parent.
- const childrenByParent = new Map<string, T[]>();
+ const childrenByParent = new Map<string, T[]>()
for (const msg of allMessages) {
- if (msg.id === undefined) continue;
- const key = parentKey(msg.parentMessageId);
- const arr = childrenByParent.get(key);
- if (arr) arr.push(msg);
- else childrenByParent.set(key, [msg]);
+ if (msg.id === undefined) continue
+ const key = parentKey(msg.parentMessageId)
+ const arr = childrenByParent.get(key)
+ if (arr) arr.push(msg)
+ else childrenByParent.set(key, [msg])
}
for (const arr of childrenByParent.values()) {
- arr.sort((a, b) => siblingRank(a) - siblingRank(b));
+ arr.sort((a, b) => siblingRank(a) - siblingRank(b))
}
- const selection = selectedBranches ?? {};
- const visible: T[] = [];
- const siblingsByMessageId = new Map<number, SiblingInfo>();
- const guard = new Set<string>();
- let currentParent = walkStartKey(allMessages, childrenByParent);
+ const selection = selectedBranches ?? {}
+ const visible: T[] = []
+ const siblingsByMessageId = new Map<number, SiblingInfo>()
+ const depthByParent = new Map<string, number>()
+ const guard = new Set<string>()
+ let currentParent = walkStartKey(allMessages, childrenByParent)
// Bound the walk defensively against pathological data (loops).
- let safety = 10_000;
+ let safety = 10_000
while (safety > 0) {
- safety -= 1;
- if (guard.has(currentParent)) break;
- guard.add(currentParent);
- const children = childrenByParent.get(currentParent);
- if (!children || children.length === 0) break;
+ safety -= 1
+ if (guard.has(currentParent)) break
+ guard.add(currentParent)
+ const children = childrenByParent.get(currentParent)
+ if (!children || children.length === 0) break
- let chosen: T;
+ let chosen: T
if (children.length === 1) {
- chosen = children[0];
+ chosen = children[0]
} else {
- const selectedId = selection[currentParent];
- chosen =
- (selectedId !== undefined &&
- children.find((c) => c.id === selectedId)) ||
- children[children.length - 1];
+ const selectedId = selection[currentParent]
+ const selected =
+ selectedId !== undefined ? children.find(c => c.id === selectedId) : undefined
+ if (selected) {
+ chosen = selected
+ } else {
+ chosen = children[0]
+ let chosenDepth = -1
+ for (const child of children) {
+ const depth =
+ child.id === undefined
+ ? 1
+ : 1 + downstreamDepth(String(child.id), childrenByParent, depthByParent, new Set())
+ if (depth >= chosenDepth) {
+ chosen = child
+ chosenDepth = depth
+ }
+ }
+ }
}
- visible.push(chosen);
+ visible.push(chosen)
if (children.length > 1 && chosen.id !== undefined) {
- const idx = children.findIndex((c) => c.id === chosen.id);
+ const idx = children.findIndex(c => c.id === chosen.id)
siblingsByMessageId.set(chosen.id, {
total: children.length,
index: idx + 1,
- siblingIds: children.map((c) => c.id!).filter((id) => id !== undefined),
+ siblingIds: children.map(c => c.id!).filter(id => id !== undefined),
parentId: chosen.parentMessageId ?? null,
- });
+ })
}
- if (chosen.id === undefined) break;
- currentParent = String(chosen.id);
+ if (chosen.id === undefined) break
+ currentParent = String(chosen.id)
}
- return { messages: visible, siblingsByMessageId };
+ return { messages: visible, siblingsByMessageId }
}
/** Branch picks safe to persist — optimistic (negative) ids are client-only. */
export function persistedBranchSelections(
- selections: Record<string, number>,
+ selections: Record<string, number>
): Record<string, number> {
- const result: Record<string, number> = {};
+ const result: Record<string, number> = {}
for (const [key, id] of Object.entries(selections)) {
- if (Number.isInteger(id) && id > 0) result[key] = id;
+ if (Number.isInteger(id) && id > 0) result[key] = id
}
- return result;
+ return result
}
/** Select a freshly-created child at a branch point.
@@ -178,12 +213,12 @@ export function persistedBranchSelections(
export function selectChildBranch(
selectedBranches: Record<string, number>,
parentId: number | null,
- childId: number,
+ childId: number
): Record<string, number> {
return {
...selectedBranches,
[parentKey(parentId)]: childId,
- };
+ }
}
/**
@@ -194,20 +229,20 @@ export function selectChildBranch(
*/
export function latestChildId(
allMessages: BranchMessage[],
- parentId: number | null,
+ parentId: number | null
): number | null {
- const key = parentKey(parentId);
- let best: number | null = null;
- let bestId = 0;
+ const key = parentKey(parentId)
+ let best: number | null = null
+ let bestId = 0
for (const m of allMessages) {
- if (parentKey(m.parentMessageId) !== key) continue;
- if (m.id === undefined || m.id <= 0) continue;
+ if (parentKey(m.parentMessageId) !== key) continue
+ if (m.id === undefined || m.id <= 0) continue
if (m.id > bestId) {
- bestId = m.id;
- best = m.id;
+ bestId = m.id
+ best = m.id
}
}
- return best;
+ return best
}
/**
@@ -220,8 +255,8 @@ export function latestChildId(
*/
export function tipMessageId(visible: BranchMessage[]): number | null {
for (let i = visible.length - 1; i >= 0; i -= 1) {
- const id = visible[i].id;
- if (id !== undefined) return id;
+ const id = visible[i].id
+ if (id !== undefined) return id
}
- return null;
+ return null
}
diff --git a/web/tests/message-branches.test.ts b/web/tests/message-branches.test.ts
new file mode 100644
index 000000000..c67068966
--- /dev/null
+++ b/web/tests/message-branches.test.ts
@@ -0,0 +1,61 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { buildVisiblePath } from '../lib/message-branches'
+
+type TreeMessage = {
+ id: number
+ role: 'user' | 'assistant'
+ content: string
+ parentMessageId: number | null
+}
+
+function conversationWithShortBranch() {
+ const messages: TreeMessage[] = [
+ { id: 1, role: 'user', content: 'question 1', parentMessageId: null },
+ ]
+ for (let round = 1; round <= 310; round++) {
+ const previousId = messages[messages.length - 1].id!
+ messages.push({
+ id: round * 2,
+ role: 'assistant' as const,
+ content: `answer ${round}`,
+ parentMessageId: previousId,
+ })
+ if (round === 310) break
+ messages.push({
+ id: round * 2 + 1,
+ role: 'user' as const,
+ content: `question ${round + 1}`,
+ parentMessageId: round * 2,
+ })
+ }
+ messages.push({
+ id: 9000,
+ role: 'user' as const,
+ content: 'accidental branch',
+ parentMessageId: 249,
+ })
+ return messages
+}
+
+test('an unselected short branch does not hide the longest continuation', () => {
+ const messages = conversationWithShortBranch()
+ const visible = buildVisiblePath(messages, {})
+
+ assert.equal(visible.messages.length, 620)
+ assert.equal(visible.messages.at(-1)?.id, 620)
+ assert.equal(
+ visible.messages.some(message => message.id === 9000),
+ false
+ )
+ assert.deepEqual(visible.siblingsByMessageId.get(250)?.siblingIds, [250, 9000])
+})
+
+test('an explicit branch selection still overrides the deepest path', () => {
+ const messages = conversationWithShortBranch()
+ const visible = buildVisiblePath(messages, { '249': 9000 })
+
+ assert.equal(visible.messages.length, 250)
+ assert.equal(visible.messages.at(-1)?.content, 'accidental branch')
+ assert.deepEqual(visible.siblingsByMessageId.get(9000)?.siblingIds, [250, 9000])
+})