Skip to content

Commit e50edba

Browse files
Maxwellimusclaude
andcommitted
fix(desktop): suspense-aware settle, StrictMode-safe abandon, log cap
Address the three findings from the 2026-08-24 review of #6455: - The lazy ChannelPane's Suspense fallback now carries the data-render-pending marker, so a switch trace can no longer settle while the pane chunk is suspended. New Playwright regression holds the chunk and asserts no measure lands until rows paint. - Route-exit trace abandonment is deferred one microtask and canceled by the effect re-setup, so StrictMode's dev-only effect replay no longer kills a just-opened trace. New jsdom regressions run the real react-dom dev replay; the settle spec also passes against the Vite dev runtime. - The perf-log 4 KiB cap is enforced on the final serialized line, and BUZZ_PERF_LOG_LABEL is truncated to 128 bytes at a char boundary, so a runaway label can neither inflate the sink nor kill every record. Also extracts the timeline-loading latch + trace marks from ChannelScreen into useChannelTimelineLoading (file-size ratchet). Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Max Lampert <[email protected]>
1 parent 4ef22c6 commit e50edba

9 files changed

Lines changed: 439 additions & 52 deletions

‎desktop/src-tauri/src/commands/perf_log.rs‎

Lines changed: 69 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,29 @@ use tauri::Manager;
1414
const PERF_LOG_FILENAME: &str = "switch-perf.jsonl";
1515

1616
/// Defensive cap: one record is a small trace object; anything larger is a
17-
/// caller bug and must not grow the log unbounded.
17+
/// caller bug and must not grow the log unbounded. Enforced on the input
18+
/// record and again on the final serialized line, so folded-in metadata can
19+
/// never defeat it.
1820
const MAX_RECORD_BYTES: usize = 4 * 1024;
1921

22+
/// Upper bound on the operator-supplied `BUZZ_PERF_LOG_LABEL` run label.
23+
/// Truncating (rather than erroring) keeps a fat-fingered label from
24+
/// silently dropping every trace for the whole run — the frontend swallows
25+
/// sink errors by design.
26+
const MAX_LABEL_BYTES: usize = 128;
27+
28+
/// Truncates to the last char boundary at or below `max_bytes`.
29+
fn truncate_at_char_boundary(text: &str, max_bytes: usize) -> &str {
30+
if text.len() <= max_bytes {
31+
return text;
32+
}
33+
let mut end = max_bytes;
34+
while !text.is_char_boundary(end) {
35+
end -= 1;
36+
}
37+
&text[..end]
38+
}
39+
2040
/// Rotation threshold. The sink is always on, so without a cap the JSONL
2141
/// grows for the life of the install; one rotated generation preserves
2242
/// enough history for before/after comparisons.
@@ -48,10 +68,18 @@ fn shape_perf_log_line(
4868
if let Some(label) = label {
4969
object.insert(
5070
"label".to_string(),
51-
serde_json::Value::String(label.to_string()),
71+
serde_json::Value::String(
72+
truncate_at_char_boundary(label, MAX_LABEL_BYTES).to_string(),
73+
),
5274
);
5375
}
54-
serde_json::to_string(&value).map_err(|e| e.to_string())
76+
let line = serde_json::to_string(&value).map_err(|e| e.to_string())?;
77+
// The cap must hold for what actually reaches the disk: gitSha and label
78+
// are folded in after the record-size check above.
79+
if line.len() > MAX_RECORD_BYTES {
80+
return Err("perf log line too large".to_string());
81+
}
82+
Ok(line)
5583
}
5684

5785
/// Serializes the whole metadata→rename→append transaction. Appends run on
@@ -151,6 +179,44 @@ mod tests {
151179
assert!(shape_perf_log_line(&oversized, None, None).is_err());
152180
}
153181

182+
#[test]
183+
fn shape_truncates_an_unbounded_label_and_keeps_the_line_capped() {
184+
// BUZZ_PERF_LOG_LABEL is operator-supplied; a runaway value must not
185+
// defeat the record cap by being folded in after the size check.
186+
let label = "l".repeat(1024 * 1024);
187+
let line =
188+
shape_perf_log_line(r#"{"totalMs":13}"#, Some("abc123"), Some(&label)).expect("shape");
189+
assert!(line.len() <= MAX_RECORD_BYTES, "line stays under the cap");
190+
let value: serde_json::Value = serde_json::from_str(&line).expect("parse");
191+
assert_eq!(
192+
value["label"].as_str().expect("label").len(),
193+
MAX_LABEL_BYTES
194+
);
195+
assert_eq!(value["totalMs"], 13);
196+
}
197+
198+
#[test]
199+
fn label_truncation_cuts_at_a_char_boundary() {
200+
// '€' is 3 bytes; MAX_LABEL_BYTES (128) is not a multiple of 3, so a
201+
// byte-index cut would split a char and panic (or emit invalid UTF-8).
202+
let label = "€".repeat(MAX_LABEL_BYTES);
203+
let line = shape_perf_log_line(r#"{"totalMs":1}"#, None, Some(&label)).expect("shape");
204+
let value: serde_json::Value = serde_json::from_str(&line).expect("parse");
205+
let stored = value["label"].as_str().expect("label");
206+
assert_eq!(stored.len(), MAX_LABEL_BYTES - (MAX_LABEL_BYTES % 3));
207+
assert!(stored.chars().all(|c| c == '€'));
208+
}
209+
210+
#[test]
211+
fn shape_rejects_a_line_that_outgrows_the_cap_after_metadata() {
212+
// The record alone passes the input check; the folded-in git sha
213+
// pushes the serialized line over the cap.
214+
let pad = "x".repeat(MAX_RECORD_BYTES - 20);
215+
let record = format!(r#"{{"pad":"{pad}"}}"#);
216+
assert!(record.len() <= MAX_RECORD_BYTES);
217+
assert!(shape_perf_log_line(&record, Some(&"s".repeat(64)), None).is_err());
218+
}
219+
154220
#[test]
155221
fn append_rotates_once_over_the_cap_and_keeps_one_generation() {
156222
let dir = std::env::temp_dir().join(format!("perf-log-test-{}", std::process::id()));

‎desktop/src/features/channels/ui/ChannelScreen.tsx‎

Lines changed: 5 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import * as React from "react";
2-
import { useQueryClient } from "@tanstack/react-query";
32
import { useAppShell } from "@/app/AppShellContext";
43
import { useAppNavigation } from "@/app/navigation/useAppNavigation";
54
import { useActiveChannelHeader } from "@/features/channels/useActiveChannelHeader";
@@ -48,11 +47,6 @@ import {
4847
getThreadReference,
4948
isThreadReply,
5049
} from "@/features/messages/lib/threading";
51-
import { hasPersistedHydratedChannel } from "@/features/messages/lib/channelHeadCache";
52-
import {
53-
resolveTimelineLoadingLatch,
54-
selectTimelineLoadingState,
55-
} from "@/features/messages/lib/timelineLoadingState";
5650
import { useFetchOlderMessages } from "@/features/messages/useFetchOlderMessages";
5751
import { useIndependentThreadPanel } from "@/features/messages/useIndependentThreadPanel";
5852
import { useThreadReplies } from "@/features/messages/useThreadReplies";
@@ -70,7 +64,7 @@ import { useHuddleReadMarker } from "@/features/channels/ui/useHuddleReadMarker"
7064
import { useHuddleThreadIsolation } from "@/features/channels/ui/useHuddleThreadIsolation";
7165
import { AgentSessionProvider } from "@/shared/context/AgentSessionContext";
7266
import { ProfilePanelProvider } from "@/shared/context/ProfilePanelContext";
73-
import { useChannelSwitchTraceMarks } from "@/features/channels/useChannelSwitchTraceMarks";
67+
import { useChannelTimelineLoading } from "@/features/channels/useChannelTimelineLoading";
7468
import { useMainInsetRef } from "@/shared/layout/MainInsetContext";
7569
import { channelContentTopPaddingMeasurement } from "@/shared/layout/chromeLayout";
7670
import { useMeasuredCssVariable } from "@/shared/layout/useMeasuredCssVariable";
@@ -103,7 +97,6 @@ export function ChannelScreen({
10397
targetMessageEvents,
10498
targetMessageId,
10599
}: ChannelScreenProps) {
106-
const queryClient = useQueryClient();
107100
const { goHome } = useAppNavigation();
108101
const { activeCommunity } = useCommunities();
109102
const {
@@ -620,38 +613,10 @@ export function ChannelScreen({
620613
setThreadReplyTargetId,
621614
setThreadScrollTargetId,
622615
});
623-
const settledChannelIdRef = React.useRef<string | null>(null);
624-
const hasSettledThisChannel =
625-
activeChannelId !== null && settledChannelIdRef.current === activeChannelId;
626-
const timelineLoadingNow =
627-
activeChannel !== null &&
628-
activeChannel.channelType !== "forum" &&
629-
selectTimelineLoadingState(
630-
{
631-
isPending: messagesQuery.isPending,
632-
isFetching: messagesQuery.isFetching,
633-
isPlaceholderData: messagesQuery.isPlaceholderData,
634-
dataLength: messagesQuery.data?.length ?? null,
635-
},
636-
// A persisted head only counts as hydrated when it has rows to paint
637-
// (channelHeadCache.ts), so this bypass never settles onto an empty
638-
// placeholder while the authoritative refresh is still in flight.
639-
hasSettledThisChannel ||
640-
(activeChannelId !== null &&
641-
hasPersistedHydratedChannel(queryClient, activeChannelId)),
642-
);
643-
const { settledChannelId, isLoading: isTimelineLoading } =
644-
resolveTimelineLoadingLatch(
645-
settledChannelIdRef.current,
646-
activeChannelId,
647-
timelineLoadingNow,
648-
);
649-
settledChannelIdRef.current = settledChannelId;
650-
useChannelSwitchTraceMarks({
651-
activeChannelId,
652-
activeChannelType: activeChannel?.channelType ?? null,
653-
isTimelineLoading,
654-
});
616+
const isTimelineLoading = useChannelTimelineLoading(
617+
activeChannel,
618+
messagesQuery,
619+
);
655620
const { welcomeKickoffStage, welcomeKickoffSettingUp } =
656621
useWelcomeKickoffStagePresence(
657622
activeChannel,

‎desktop/src/features/channels/ui/ChannelScreenLoadingFallback.tsx‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,18 @@ export function ChannelScreenLoadingFallback({
66
}: {
77
isHuddleTranscript: boolean;
88
}) {
9-
return isHuddleTranscript ? (
10-
<HuddleStartingView />
11-
) : (
12-
<ViewLoadingFallback includeHeader kind="channel" />
9+
return (
10+
// While the lazy ChannelPane chunk is suspended, the timeline — and its
11+
// own render-pending marker — is not mounted. The switch tracer polls
12+
// that marker to defer its settle, so the fallback itself must read as
13+
// pending or a settle could record before the pane ever painted.
14+
// `contents` keeps the wrapper out of layout.
15+
<div className="contents" data-render-pending="true">
16+
{isHuddleTranscript ? (
17+
<HuddleStartingView />
18+
) : (
19+
<ViewLoadingFallback includeHeader kind="channel" />
20+
)}
21+
</div>
1322
);
1423
}
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import assert from "node:assert/strict";
2+
import { afterEach, it } from "node:test";
3+
4+
import { JSDOM } from "jsdom";
5+
import React from "react";
6+
import { act } from "react";
7+
import { createRoot } from "react-dom/client";
8+
9+
import {
10+
CHANNEL_SWITCH_MEASURE,
11+
beginChannelSwitchTrace,
12+
resetChannelSwitchTrace,
13+
settleChannelSwitchTrace,
14+
} from "../../shared/lib/channelSwitchPerf.ts";
15+
import { useChannelSwitchTraceMarks } from "./useChannelSwitchTraceMarks.ts";
16+
17+
// These tests run the hook under the real react-dom development build, whose
18+
// StrictMode replays every effect (setup → cleanup → setup) on mount — the
19+
// exact dev-runtime lifecycle that used to abandon a just-opened trace and
20+
// break the Performance-panel workflow.
21+
22+
const originalDocument = globalThis.document;
23+
const originalWindow = globalThis.window;
24+
const originalActEnvironment = globalThis.IS_REACT_ACT_ENVIRONMENT;
25+
26+
afterEach(() => {
27+
resetChannelSwitchTrace();
28+
performance.clearMeasures?.(CHANNEL_SWITCH_MEASURE);
29+
if (originalDocument === undefined) delete globalThis.document;
30+
else globalThis.document = originalDocument;
31+
if (originalWindow === undefined) delete globalThis.window;
32+
else globalThis.window = originalWindow;
33+
if (originalActEnvironment === undefined)
34+
delete globalThis.IS_REACT_ACT_ENVIRONMENT;
35+
else globalThis.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment;
36+
});
37+
38+
function setupDom() {
39+
const dom = new JSDOM(
40+
"<!doctype html><html><body><div id='root'></div></body></html>",
41+
);
42+
const frames = [];
43+
dom.window.requestAnimationFrame = (cb) => frames.push(cb) && frames.length;
44+
dom.window.cancelAnimationFrame = () => {};
45+
Object.assign(globalThis, {
46+
document: dom.window.document,
47+
IS_REACT_ACT_ENVIRONMENT: true,
48+
window: dom.window,
49+
});
50+
const flushFrames = () => {
51+
// Drain chained rAFs until quiescent.
52+
for (let i = 0; i < 20 && frames.length > 0; i += 1) {
53+
for (const cb of frames.splice(0, frames.length)) cb();
54+
}
55+
};
56+
return { dom, flushFrames };
57+
}
58+
59+
function Harness({ channelId, isTimelineLoading }) {
60+
useChannelSwitchTraceMarks({
61+
activeChannelId: channelId,
62+
activeChannelType: "stream",
63+
isTimelineLoading,
64+
});
65+
return null;
66+
}
67+
68+
function renderHarness(root, props) {
69+
return act(async () =>
70+
root.render(
71+
React.createElement(
72+
React.StrictMode,
73+
null,
74+
React.createElement(Harness, props),
75+
),
76+
),
77+
);
78+
}
79+
80+
const measures = () =>
81+
performance
82+
.getEntriesByName(CHANNEL_SWITCH_MEASURE)
83+
.map((entry) => entry.detail?.channelId);
84+
85+
it("a trace survives StrictMode's effect replay and still settles", async () => {
86+
const { dom, flushFrames } = setupDom();
87+
performance.clearMeasures?.(CHANNEL_SWITCH_MEASURE);
88+
beginChannelSwitchTrace("chan-strict");
89+
const root = createRoot(document.getElementById("root"));
90+
await renderHarness(root, {
91+
channelId: "chan-strict",
92+
isTimelineLoading: true,
93+
});
94+
await renderHarness(root, {
95+
channelId: "chan-strict",
96+
isTimelineLoading: false,
97+
});
98+
flushFrames();
99+
assert.deepEqual(measures(), ["chan-strict"]);
100+
await act(async () => root.unmount());
101+
dom.window.close();
102+
});
103+
104+
it("a real route exit still abandons: a history-back settle records nothing", async () => {
105+
const { dom, flushFrames } = setupDom();
106+
performance.clearMeasures?.(CHANNEL_SWITCH_MEASURE);
107+
beginChannelSwitchTrace("chan-exit");
108+
const root = createRoot(document.getElementById("root"));
109+
await renderHarness(root, {
110+
channelId: "chan-exit",
111+
isTimelineLoading: true,
112+
});
113+
// Leaving the channel surface unmounts the hook; with no re-setup to
114+
// cancel it, the scheduled abandon must fire.
115+
await act(async () => root.unmount());
116+
await new Promise((resolve) => setImmediate(resolve));
117+
// History-back re-enters without goChannel; its settle must find no trace.
118+
settleChannelSwitchTrace("chan-exit");
119+
flushFrames();
120+
assert.deepEqual(measures(), []);
121+
dom.window.close();
122+
});
123+
124+
it("an A→B switch's deferred abandon of A never kills B's trace", async () => {
125+
const { dom, flushFrames } = setupDom();
126+
performance.clearMeasures?.(CHANNEL_SWITCH_MEASURE);
127+
beginChannelSwitchTrace("chan-a");
128+
const root = createRoot(document.getElementById("root"));
129+
await renderHarness(root, { channelId: "chan-a", isTimelineLoading: true });
130+
beginChannelSwitchTrace("chan-b");
131+
await renderHarness(root, { channelId: "chan-b", isTimelineLoading: true });
132+
await renderHarness(root, { channelId: "chan-b", isTimelineLoading: false });
133+
flushFrames();
134+
assert.deepEqual(measures(), ["chan-b"]);
135+
await act(async () => root.unmount());
136+
dom.window.close();
137+
});

‎desktop/src/features/channels/useChannelSwitchTraceMarks.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import * as React from "react";
22

33
import {
44
abandonChannelSwitchTrace,
5+
cancelRouteExitAbandon,
56
markChannelSwitchRouteCommit,
7+
scheduleRouteExitAbandon,
68
settleChannelSwitchTrace,
79
} from "@/shared/lib/channelSwitchPerf";
810
import type { ChannelType } from "@/shared/api/types";
@@ -33,12 +35,16 @@ export function useChannelSwitchTraceMarks({
3335
// timeout matches the stale singleton and records the time spent away as
3436
// switch latency. Keyed per channel id: on an A→B switch this cleanup runs
3537
// with A's id after B's trace already began, so it only ever abandons its
36-
// own channel's trace.
38+
// own channel's trace. The abandon is scheduled (one microtask) rather
39+
// than immediate so StrictMode's dev-only effect replay — whose re-setup
40+
// runs synchronously right after this cleanup — cancels it instead of
41+
// killing the just-opened trace.
3742
React.useEffect(() => {
3843
if (!activeChannelId) return;
3944
const channelId = activeChannelId;
45+
cancelRouteExitAbandon(channelId);
4046
return () => {
41-
abandonChannelSwitchTrace(channelId);
47+
scheduleRouteExitAbandon(channelId);
4248
};
4349
}, [activeChannelId]);
4450
React.useEffect(() => {

0 commit comments

Comments
 (0)