Fold earlier process when assistant output begins

This commit is contained in:
QQ 2026-11-28 19:02:58 +08:00
parent 2020a6ebc3
commit 59c6e6e2f5
6 changed files with 105 additions and 145 deletions

View File

@ -50973,7 +50973,7 @@ ${trimmed}
continue;
}
const node = get(entry.nodeKey);
if (!node || node.visibility === "hidden" || node.kind === "turn-tail") continue;
if (!node || node.visibility === "hidden" || node.kind === "turn-tail" || node.kind === "turn-process") continue;
if (node.kind === "user" || node.kind === "steering") {
steps.push({
kind: "user",
@ -50989,84 +50989,57 @@ ${trimmed}
steps.push({
kind: "other",
key: entry.key,
nodeKey: entry.nodeKey
nodeKey: entry.nodeKey,
process: node.kind === "turn-trigger" || isProcessRecord(node)
});
}
return steps;
}
/** Only a run that contains real thinking/tool work is worth folding. */
function foldableRun(run) {
return run.some((step) => step.kind === "reasoning" || step.kind === "tool");
function isLiveProcess(step) {
return step.kind === "reasoning" || step.kind === "tool" || step.kind === "other" && step.process === true;
}
/**
* One live chain: narration stays visible, while every earlier reasoning/tool
* run collapses into its own box at its original position.
*/
/** Fold the preceding process at visible output or a newer reasoning step. */
function presentLiveTurn(steps, boundary, autoFold = true) {
const live = autoFold && liveFoldEnabled(boundary);
const items = [];
const open = (step) => items.push({
let segment = [];
const show = (step) => items.push({
kind: "open",
key: step.key,
step
});
const fold = (run) => {
if (!run.length) return;
if (live && foldableRun(run)) items.push({
kind: "fold",
key: `live-fold:${run[0].key}`,
steps: run,
summary: foldSummary(run)
});
else for (const step of run) open(step);
};
let run = [];
const flush = () => {
fold(run);
run = [];
};
const segments = [];
let segment = [];
for (const step of steps) if (step.kind === "user") {
segments.push(segment);
segments.push([step]);
segment = [];
} else segment.push(step);
segments.push(segment);
for (const part of segments) {
if (!part.length) continue;
const first = part[0];
if (part.length === 1 && first.kind === "user") {
items.push({
kind: "user",
key: first.key,
step: first
const lastReasoning = live ? segment.findLastIndex((step) => step.kind === "reasoning") : -1;
let run = [];
const finishRun = (fold) => {
if (fold && run.length) items.push({
kind: "fold",
key: `live-fold:${run[0].key}`,
steps: run,
summary: foldSummary(run)
});
continue;
}
if (!live) {
for (const step of part) open(step);
continue;
}
const lastReasoning = part.findLastIndex((step) => step.kind === "reasoning");
if (lastReasoning <= 0) {
for (const step of part) open(step);
continue;
}
for (let index = 0; index < part.length; index++) {
const step = part[index];
if (index < lastReasoning) {
if (step.kind === "body") {
flush();
open(step);
} else run.push(step);
} else {
if (index === lastReasoning) flush();
open(step);
}
else run.forEach(show);
run = [];
};
for (const [index, step] of segment.entries()) if (live && isLiveProcess(step)) {
if (index === lastReasoning) finishRun(true);
run.push(step);
} else {
finishRun(live && (step.kind === "body" || index < lastReasoning));
show(step);
}
finishRun(false);
segment = [];
};
for (const step of steps) if (step.kind === "user") {
flush();
}
items.push({
kind: "user",
key: step.key,
step
});
} else segment.push(step);
flush();
return items;
}
/**
@ -51507,7 +51480,10 @@ ${trimmed}
latest.current = frame;
const [visible, setVisible] = (0, react.useState)(() => !document.hidden);
const [state, setState] = (0, react.useState)(() => idle(frame));
if ((!motion || !enabled || urgent || !visible || !processOpen || state.phase !== "idle" && Object.values(open).some(Boolean) || containsNewUser(state.shown.items, frame.items)) && (state.phase !== "idle" || state.shown !== frame)) setState(idle(frame));
const bypass = !motion || !enabled || urgent || !visible || !processOpen || state.phase !== "idle" && Object.values(open).some(Boolean);
const shownKeys = state.shown !== frame ? new Set(state.shown.items.map((item) => item.key)) : void 0;
const outputArrived = shownKeys !== void 0 && frame.items.some((item) => item.kind === "open" && item.step.kind === "body" && !shownKeys.has(item.key));
if ((bypass || outputArrived || containsNewUser(state.shown.items, frame.items)) && (state.phase !== "idle" || state.shown !== frame)) setState(idle(frame));
else if (state.phase === "idle" && state.shown !== frame) {
const retiring = retiringKeys(state.shown.items, frame.items, open);
setState(retiring.length ? {
@ -51651,8 +51627,8 @@ ${trimmed}
};
const node = row.step.kind === "other" ? source.snapshot.nodes.get(row.step.nodeKey) : void 0;
const trigger = !!status && node?.kind === "turn-trigger";
const process = row.step.kind === "reasoning" || row.step.kind === "tool" || trigger || isProcessRecord(node);
const hidden = trigger && !processOpen || !!row.foldKey && (!processOpen || !open[row.foldKey]) || node?.kind === "turn-process" || blocked && state.phase !== "collapse" && !state.beforeKeys.has(row.key);
const process = row.step.kind === "reasoning" || row.step.kind === "tool" || trigger || row.step.kind === "other" && row.step.process === true && node?.kind !== "turn-trigger";
const hidden = trigger && !processOpen || !!row.foldKey && (!processOpen || !open[row.foldKey]) || blocked && state.phase !== "collapse" && !state.beforeKeys.has(row.key);
return {
row,
key: row.key,

File diff suppressed because one or more lines are too long

View File

@ -11,7 +11,6 @@ import { DiffStat } from './DiffPanel.js';
import { StreamMotionContext } from './streaming.js';
import css from './Reader.module.css';
import { useSummaryLane } from './StickyLane.js';
import { isProcessRecord } from './projection.js';
const FlowSnapshot = createContext<ChatSnapshot | null>(null);
/** Public projection only. Descendants cannot leak live data through a frozen frame. */
@ -112,8 +111,12 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
const [visible, setVisible] = useState(() => !document.hidden);
const [state, setState] = useState<Transaction>(() => idle(frame));
const bypass = !motion || !enabled || urgent || !visible || !processOpen || (state.phase !== 'idle' && Object.values(open).some(Boolean));
// Render-time adjustment prevents even one paint of the new authoritative layout.
if ((bypass || containsNewUser(state.shown.items, frame.items)) && (state.phase !== 'idle' || state.shown !== frame)) {
const shownKeys = state.shown !== frame ? new Set(state.shown.items.map(item => item.key)) : undefined;
const outputArrived = shownKeys !== undefined && frame.items.some(item =>
item.kind === 'open' && item.step.kind === 'body' && !shownKeys.has(item.key));
// Publish new prose with its folded process rather than buffering the first words.
// Render-time adjustment prevents even one paint of the stale layout.
if ((bypass || outputArrived || containsNewUser(state.shown.items, frame.items)) && (state.phase !== 'idle' || state.shown !== frame)) {
setState(idle(frame));
} else if (state.phase === 'idle' && state.shown !== frame) {
const retiring = retiringKeys(state.shown.items, frame.items, open);
@ -226,9 +229,9 @@ export function ChoreographedFlow({ frame, motion, enabled, urgent, open, onOpen
if (row.kind === 'summary') return { row, key: row.key, hidden: false, process: true };
const node = row.step.kind === 'other' ? source.snapshot.nodes.get(row.step.nodeKey) : undefined;
const trigger = !!status && node?.kind === 'turn-trigger';
const process = row.step.kind === 'reasoning' || row.step.kind === 'tool' || trigger || isProcessRecord(node);
const process = row.step.kind === 'reasoning' || row.step.kind === 'tool' || trigger
|| (row.step.kind === 'other' && row.step.process === true && node?.kind !== 'turn-trigger');
const hidden = (trigger && !processOpen) || !!row.foldKey && (!processOpen || !open[row.foldKey])
|| node?.kind === 'turn-process'
|| (blocked && state.phase !== 'collapse' && !state.beforeKeys.has(row.key));
return { row, key: row.key, hidden, process: processOpen && process };
});

View File

@ -1,6 +1,6 @@
import type { AssistantChatData, ChatConversationViewNode } from '@deepseek-ai/dsh-client-ui-chat/client';
import type { AssistantBlock } from '@deepseek-ai/dsh-client-ui-conversation/client';
import { assistantSegments, hasVisibleBody } from './projection.js';
import { assistantSegments, hasVisibleBody, isProcessRecord } from './projection.js';
import type { TurnBoundary } from './projection.js';
import type { ReaderFlowEntry, ToolActivityEntry } from './tool-activity.js';
@ -9,7 +9,7 @@ export type LiveStep =
| { kind: 'body'; key: string; nodeKey: string; start: number; blocks: AssistantBlock[]; step: number }
| { kind: 'tool'; key: string; entry: ToolActivityEntry }
| { kind: 'user'; key: string; nodeKey: string }
| { kind: 'other'; key: string; nodeKey: string };
| { kind: 'other'; key: string; nodeKey: string; process?: boolean };
export type LiveTurnItem =
| { kind: 'user'; key: string; step: Extract<LiveStep, { kind: 'user' }> }
@ -99,7 +99,7 @@ export function segmentLiveTurn(
continue;
}
const node = get(entry.nodeKey);
if (!node || node.visibility === 'hidden' || node.kind === 'turn-tail') continue;
if (!node || node.visibility === 'hidden' || (node.kind === 'turn-tail' || node.kind === 'turn-process')) continue;
if (node.kind === 'user' || node.kind === 'steering') {
steps.push({ kind: 'user', key: entry.key, nodeKey: entry.nodeKey });
continue;
@ -108,80 +108,53 @@ export function segmentLiveTurn(
steps.push(...stepsFromAssistant(entry.nodeKey, node.data as AssistantChatData, toolsByCallId, consumed));
continue;
}
steps.push({ kind: 'other', key: entry.key, nodeKey: entry.nodeKey });
steps.push({ kind: 'other', key: entry.key, nodeKey: entry.nodeKey, process: node.kind === 'turn-trigger' || isProcessRecord(node) });
}
return steps;
}
/** Only a run that contains real thinking/tool work is worth folding. */
function foldableRun(run: readonly LiveStep[]): boolean {
return run.some(step => step.kind === 'reasoning' || step.kind === 'tool');
function isLiveProcess(step: LiveStep): boolean {
return step.kind === 'reasoning' || step.kind === 'tool' || (step.kind === 'other' && step.process === true);
}
/**
* One live chain: narration stays visible, while every earlier reasoning/tool
* run collapses into its own box at its original position.
*/
/** Fold the preceding process at visible output or a newer reasoning step. */
export function presentLiveTurn(steps: readonly LiveStep[], boundary: TurnBoundary, autoFold = true): LiveTurnItem[] {
const live = autoFold && liveFoldEnabled(boundary);
const items: LiveTurnItem[] = [];
const open = (step: LiveStep) => items.push({ kind: 'open', key: step.key, step });
const fold = (run: readonly LiveStep[]) => {
if (!run.length) return;
if (live && foldableRun(run)) {
items.push({ kind: 'fold', key: `live-fold:${run[0]!.key}`, steps: run, summary: foldSummary(run) });
} else {
for (const step of run) open(step);
}
};
let run: LiveStep[] = [];
const flush = () => { fold(run); run = []; };
// A user insert resets the chain: steps before it are never folded by
// reasoning after it. Split into user-delimited segments and walk each one.
const segments: LiveStep[][] = [];
let segment: LiveStep[] = [];
const show = (step: LiveStep) => items.push({ kind: 'open', key: step.key, step });
const flush = () => {
const lastReasoning = live ? segment.findLastIndex(step => step.kind === 'reasoning') : -1;
let run: LiveStep[] = [];
const finishRun = (fold: boolean) => {
if (fold && run.length) {
items.push({ kind: 'fold', key: `live-fold:${run[0]!.key}`, steps: run, summary: foldSummary(run) });
} else {
run.forEach(show);
}
run = [];
};
for (const [index, step] of segment.entries()) {
if (live && isLiveProcess(step)) {
if (index === lastReasoning) finishRun(true);
run.push(step);
} else {
finishRun(live && (step.kind === 'body' || index < lastReasoning));
show(step);
}
}
finishRun(false);
segment = [];
};
for (const step of steps) {
if (step.kind === 'user') {
segments.push(segment); segments.push([step]); segment = [];
flush();
items.push({ kind: 'user', key: step.key, step });
} else {
segment.push(step);
}
}
segments.push(segment);
for (const part of segments) {
if (!part.length) continue;
const first = part[0]!;
if (part.length === 1 && first.kind === 'user') {
items.push({ kind: 'user', key: first.key, step: first });
continue;
}
if (!live) {
for (const step of part) open(step);
continue;
}
// Narration is never folded. Once a later reasoning step exists, every
// reasoning/tool run before it folds at its own position, so the latest
// thinking and everything after it stay open while earlier steps collapse —
// even across narration blocks, which the reader still renders in place.
const lastReasoning = part.findLastIndex(step => step.kind === 'reasoning');
if (lastReasoning <= 0) {
for (const step of part) open(step);
continue;
}
for (let index = 0; index < part.length; index++) {
const step = part[index]!;
if (index < lastReasoning) {
if (step.kind === 'body') { flush(); open(step); }
else run.push(step);
} else {
if (index === lastReasoning) flush();
open(step);
}
}
flush();
}
flush();
return items;
}

View File

@ -38,13 +38,13 @@ test('repeat fold retires only displayed open rows, retaining the same summary i
test('narration never enters a fold cell, so choreography never retires it', () => {
const before = presentLiveTurn([reasoning(1)], open);
const withNarration = presentLiveTurn([reasoning(1), body], open);
assert.deepEqual(retiringKeys(before, withNarration, {}), []);
assert.deepEqual(flowRows(withNarration).map(row => row.key), ['r1', 'b1']);
assert.deepEqual(retiringKeys(before, withNarration, {}), ['r1']);
assert.deepEqual(flowRows(withNarration).map(row => row.key), ['live-fold:r1', 'r1', 'b1']);
const after = presentLiveTurn([reasoning(1), body, tool, reasoning(2)], open);
assert.equal(after.some(item => item.kind === 'fold' && item.steps.some(step => step.kind === 'body')), false);
// The prior reasoning run folds (r1 retires), but narration itself never does.
assert.deepEqual(retiringKeys(withNarration, after, {}), ['r1']);
// The first run is already folded, and the next tool was never visible.
assert.deepEqual(retiringKeys(withNarration, after, {}), []);
assert.ok(!retiringKeys(withNarration, after, {}).includes('b1'));
});
test('user admission bypasses buffered choreography and preserves source ordering', () => {

View File

@ -24,7 +24,7 @@ function user(id: string): LiveStep {
return { kind: 'user', key: id, nodeKey: id };
}
function other(id: string): LiveStep {
return { kind: 'other', key: id, nodeKey: id };
return { kind: 'other', key: id, nodeKey: id, process: true };
}
function kinds(items: ReturnType<typeof presentLiveTurn>) {
@ -33,7 +33,7 @@ function kinds(items: ReturnType<typeof presentLiveTurn>) {
test('narration is never folded; earlier process runs collapse even across narration', () => {
const beforeSecondReasoning = presentLiveTurn([reasoning('1'), body('2')], open);
assert.deepEqual(kinds(beforeSecondReasoning), [['open', '1'], ['open', '2']]);
assert.deepEqual(kinds(beforeSecondReasoning), [['fold', '思考×1', ['1']], ['open', '2']]);
// The first reasoning run folds in place before the narration; the narration
// itself stays open, and the latest reasoning stays open.
@ -123,23 +123,23 @@ test('presentLiveTurn keeps one fold box per foldable run and never hides narrat
test('mid-turn user insert resets the chain; narration stays open across the reset', () => {
const before = presentLiveTurn([reasoning('1'), body('2'), tool('3'), user('insert'), body('4'), tool('5')], open);
assert.deepEqual(kinds(before), [
['open', '1'], ['open', '2'], ['open', '3'],
['fold', '思考×1', ['1']], ['open', '2'], ['open', '3'],
['user', 'insert'],
['open', '4'], ['open', '5'],
]);
const after = presentLiveTurn([reasoning('1'), body('2'), tool('3'), user('insert'), body('4'), tool('5'), reasoning('6')], open);
assert.deepEqual(kinds(after), [
['open', '1'], ['open', '2'], ['open', '3'],
['fold', '思考×1', ['1']], ['open', '2'], ['open', '3'],
['user', 'insert'],
['open', '4'],
['fold', '工具×1', ['5']],
['open', '6'],
]);
const folds = after.filter(item => item.kind === 'fold');
assert.equal(folds.length, 1);
if (folds[0]?.kind !== 'fold') throw new Error('missing insert fold');
assert.ok(!folds[0].steps.some(step => ['1', '2', '3', '4', 'insert'].includes(step.key)));
assert.equal(folds.length, 2);
if (folds[1]?.kind !== 'fold') throw new Error('missing insert fold');
assert.ok(!folds[1].steps.some(step => ['1', '2', '3', '4', 'insert'].includes(step.key)));
});
test('every prior process run folds in its own place; narration stays open between runs', () => {
@ -232,7 +232,7 @@ test('steering in the flow is a chain reset, same as a mid-turn user message', (
const flow = readerFlow({ key: 'turn:1', turn: 1, keys: ['a', 'steer', 'b'] }, undefined, key => nodes.get(key));
const items = presentLiveTurn(segmentLiveTurn(flow, key => nodes.get(key)), open);
assert.deepEqual(kinds(items), [
['open', 'a:reasoning:0'], ['open', 'a:body:1'],
['fold', '思考×1', ['a:reasoning:0']], ['open', 'a:body:1'],
['user', 'steer'],
['open', 'b:reasoning:0'],
]);
@ -287,3 +287,11 @@ test('closed turn keeps the seam between narration blocks and the previous body
assert.equal(expanded.before.size, 0);
assert.equal(expanded.after.size, 0);
});
test('the first output folds even a record-only process; subsequent work stays visible', () => {
const records = [other('context1'), other('context2')];
assert.deepEqual(kinds(presentLiveTurn(records, open)), [['open', 'context1'], ['open', 'context2']]);
assert.deepEqual(kinds(presentLiveTurn([...records, body('text'), tool('new-tool')], open)), [
['fold', '记录×2', ['context1', 'context2']], ['open', 'text'], ['open', 'new-tool'],
]);
});