Skip to content

Commit 236989c

Browse files
chore: merge latest main into Claude usage limit fix
2 parents ed097b2 + caf4981 commit 236989c

11 files changed

Lines changed: 495 additions & 31 deletions

File tree

‎apps/server/src/provider/Layers/ClaudeAdapter.test.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3450,10 +3450,14 @@ describe("ClaudeAdapterLive", () => {
34503450
const harness = makeHarness();
34513451
return Effect.gen(function* () {
34523452
const adapter = yield* ClaudeAdapter;
3453-
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
3454-
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
3455-
Effect.sync(() => runtimeEvents.push(event)),
3456-
).pipe(Effect.forkChild);
3453+
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
3454+
Stream.takeUntil(
3455+
(event) =>
3456+
event.type === "session.state.changed" && event.payload.reason === "api_retry:3/10",
3457+
),
3458+
Stream.runCollect,
3459+
Effect.forkChild,
3460+
);
34573461

34583462
yield* adapter.startSession({
34593463
threadId: THREAD_ID,
@@ -3499,7 +3503,6 @@ describe("ClaudeAdapterLive", () => {
34993503
uuid: "tu",
35003504
},
35013505
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
3502-
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
35033506
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
35043507
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
35053508
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
@@ -3546,6 +3549,21 @@ describe("ClaudeAdapterLive", () => {
35463549
]) {
35473550
harness.query.emit(message as unknown as SDKMessage);
35483551
}
3552+
// Safety model-fallback notices DO surface as a warning row.
3553+
harness.query.emit({
3554+
type: "system",
3555+
subtype: "model_refusal_fallback",
3556+
trigger: "refusal",
3557+
direction: "retry",
3558+
original_model: "claude-fable-5",
3559+
fallback_model: "claude-opus-4-8",
3560+
request_id: "req_test",
3561+
api_refusal_category: "cyber",
3562+
api_refusal_explanation: null,
3563+
content: "Safeguards flagged this message. Switched to Opus 4.8.",
3564+
session_id: "session",
3565+
uuid: "mrf",
3566+
} as unknown as SDKMessage);
35493567
// High-priority notifications DO surface as a warning row.
35503568
harness.query.emit({
35513569
type: "system",
@@ -3603,15 +3621,15 @@ describe("ClaudeAdapterLive", () => {
36033621
session_id: "session",
36043622
uuid: "retry",
36053623
} as unknown as SDKMessage);
3606-
yield* Effect.yieldNow;
3607-
yield* Effect.yieldNow;
3624+
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
36083625

36093626
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
3610-
// Exactly three warnings: the high-priority notification, the
3627+
// Exactly four warnings: the fallback notice, high-priority notification,
36113628
// warning-level informational note, and the refusal. Nothing else.
36123629
assert.deepEqual(
36133630
warnings.map((event) => event.payload.message),
36143631
[
3632+
"Safeguards flagged this message. Switched to Opus 4.8.",
36153633
"context window nearly full",
36163634
"Stop hook prevented continuation",
36173635
"The request was declined by the API.",
@@ -3639,7 +3657,6 @@ describe("ClaudeAdapterLive", () => {
36393657
event.payload.reason.startsWith("api_retry:"),
36403658
);
36413659
assert.equal(heartbeat?.type, "session.state.changed");
3642-
runtimeEventsFiber.interruptUnsafe();
36433660
}).pipe(
36443661
Effect.provideService(Random.Random, makeDeterministicRandomService()),
36453662
Effect.provide(harness.layer),

‎apps/server/src/provider/Layers/ClaudeAdapter.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3707,6 +3707,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
37073707
yield* emitRuntimeWarning(context, message.text, message);
37083708
}
37093709
return;
3710+
case "model_refusal_fallback":
3711+
// A safety fallback switched the model mid-session (e.g. Fable 5
3712+
// retried on Opus 4.8 after a flagged request). The CLI ships the
3713+
// user-facing notice in `content`; surface it like high-priority
3714+
// notifications so the rest of the session isn't silently served
3715+
// by a different model.
3716+
yield* emitRuntimeWarning(context, message.content, message);
3717+
return;
37103718
// Inner protocol/UX details with no T3 surface today — consumed
37113719
// deliberately so they don't masquerade as unknown-subtype warnings.
37123720
// `background_tasks_changed` is a roster snapshot ({tasks: [...]}); the
@@ -3715,7 +3723,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
37153723
// source. `control_request_progress` is a liveness heartbeat for an
37163724
// in-flight control request. `worker_shutting_down` is a Remote
37173725
// Control worker notice; the session close path reports the outcome.
3718-
case "model_refusal_fallback":
37193726
case "local_command_output":
37203727
case "plugin_install":
37213728
case "commands_changed":

‎apps/web/src/components/Sidebar.tsx‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,11 @@ import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
111111
import { useLocalStorage } from "../hooks/useLocalStorage";
112112
import { useNowMinute } from "../hooks/useNowMinute";
113113
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
114-
import { useProjects, useThreadShells } from "../state/entities";
114+
import {
115+
useAllEnvironmentProjectSnapshotsReady,
116+
useProjects,
117+
useThreadShells,
118+
} from "../state/entities";
115119
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
116120
import { vcsEnvironment } from "../state/vcs";
117121
import { threadEnvironment } from "../state/threads";
@@ -2098,7 +2102,11 @@ export default function Sidebar() {
20982102

20992103
// Project scope: one menu above the list. Scoping filters the list without
21002104
// making the header width depend on the number or length of project names.
2101-
const [projectScopeKey, setProjectScopeKey] = useState<string | null>(null);
2105+
// The selection lives in the persisted UI store next to the other sidebar
2106+
// project preferences, so routes that unmount the sidebar (Settings) and
2107+
// app restarts keep it.
2108+
const projectScopeKey = useUiStateStore((store) => store.sidebarProjectScopeKey);
2109+
const setProjectScopeKey = useUiStateStore((store) => store.setSidebarProjectScopeKey);
21022110
// {value, label} items let Base UI drive the combobox selection contract
21032111
// while the popup search filters the same collection.
21042112
const projectScopeItems = useMemo(
@@ -2162,11 +2170,15 @@ export default function Sidebar() {
21622170
),
21632171
[scopedProjectGroup],
21642172
);
2173+
// A persisted scope whose project is gone falls back to all projects, but
2174+
// only after every catalog environment has a live project snapshot. Cached
2175+
// or disconnected environments cannot establish that the project is gone.
2176+
const allProjectSnapshotsReady = useAllEnvironmentProjectSnapshotsReady();
21652177
useEffect(() => {
2166-
if (projectScopeKey !== null && scopedProjectGroup === null) {
2178+
if (projectScopeKey !== null && allProjectSnapshotsReady && scopedProjectGroup === null) {
21672179
setProjectScopeKey(null);
21682180
}
2169-
}, [projectScopeKey, scopedProjectGroup]);
2181+
}, [allProjectSnapshotsReady, projectScopeKey, scopedProjectGroup, setProjectScopeKey]);
21702182
// Count-only subscription: the parent needs "are there draft rows" for the
21712183
// empty state, while SidebarDraftBlock owns the per-keystroke content
21722184
// subscription. Selecting a number keeps typing in a draft composer from
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
import type { ReactElement } from "react";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3+
4+
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
5+
import {
6+
getThemeDefinition,
7+
installCustomTheme,
8+
invalidateCustomThemes,
9+
parseThemeFile,
10+
removeCustomTheme,
11+
THEME_FILE_VERSION,
12+
themeColorToHex,
13+
updateCustomTheme,
14+
type ThemeDefinition,
15+
} from "../../themePalette";
16+
import type { ThemeEditorSession } from "./themeEditorStore";
17+
18+
const state = vi.hoisted(() => ({
19+
session: null as ThemeEditorSession | null,
20+
closeThemeEditor: vi.fn(),
21+
onStoreChange: vi.fn(),
22+
subscriptions: new Set<() => void>(),
23+
theme: {
24+
theme: "system",
25+
themeHalves: null,
26+
setTheme: vi.fn(),
27+
refreshTheme: vi.fn(),
28+
},
29+
}));
30+
31+
vi.mock("react", async (importOriginal) => {
32+
const actual = await importOriginal<typeof import("react")>();
33+
const { reactHookHarness } = await import("../../test/reactHookHarness");
34+
return {
35+
...actual,
36+
useCallback: reactHookHarness.useCallback,
37+
useSyncExternalStore: (
38+
subscribe: (listener: () => void) => () => void,
39+
getSnapshot: () => unknown,
40+
) => {
41+
const subscription = reactHookHarness.useRef<(() => void) | null>(null);
42+
if (!subscription.current) {
43+
subscription.current = subscribe(() => state.onStoreChange());
44+
state.subscriptions.add(subscription.current);
45+
}
46+
return getSnapshot();
47+
},
48+
};
49+
});
50+
51+
vi.mock("react/compiler-runtime", async () => {
52+
const { reactHookHarness } = await import("../../test/reactHookHarness");
53+
return { c: reactHookHarness.useMemoCache };
54+
});
55+
56+
vi.mock("../../hooks/useTheme", () => ({ useTheme: () => state.theme }));
57+
vi.mock("./themeEditorStore", () => ({
58+
useThemeEditorStore: (select: (store: typeof state) => unknown) => select(state),
59+
}));
60+
vi.mock("../ui/toast", () => ({
61+
toastManager: { add: vi.fn() },
62+
stackedThreadToast: (value: unknown) => value,
63+
}));
64+
65+
import { ThemeEditorHost } from "./ThemeEditorHost";
66+
67+
function renderEditor() {
68+
hooks.beginRender();
69+
const host = ThemeEditorHost() as ReactElement<{
70+
children: ReactElement<{
71+
editingTheme: ThemeDefinition | null;
72+
seedTheme: ThemeDefinition | null;
73+
}>;
74+
}> | null;
75+
return host?.props.children.props ?? null;
76+
}
77+
78+
describe("ThemeEditorHost", () => {
79+
beforeEach(() => {
80+
hooks.reset();
81+
state.session = null;
82+
state.onStoreChange.mockReset();
83+
const storage = new Map<string, string>();
84+
vi.stubGlobal("window", {
85+
localStorage: {
86+
getItem: (key: string) => storage.get(key) ?? null,
87+
setItem: (key: string, value: string) => storage.set(key, value),
88+
},
89+
addEventListener: vi.fn(),
90+
removeEventListener: vi.fn(),
91+
});
92+
invalidateCustomThemes();
93+
});
94+
95+
afterEach(() => {
96+
for (const unsubscribe of state.subscriptions) unsubscribe();
97+
state.subscriptions.clear();
98+
vi.unstubAllGlobals();
99+
invalidateCustomThemes();
100+
});
101+
102+
it.each(["editingTheme", "seedTheme"] as const)(
103+
"reopens the same %s with its saved colors",
104+
(field) => {
105+
const theme = installCustomTheme(
106+
parseThemeFile({
107+
version: THEME_FILE_VERSION,
108+
id: "saved-colors",
109+
name: "Saved colors",
110+
appearance: "dark",
111+
colors: { accent: "#1f6e4a" },
112+
}),
113+
);
114+
const session = {
115+
id: 1,
116+
editingThemeId: field === "editingTheme" ? theme.id : null,
117+
seedThemeId: field === "seedTheme" ? theme.id : null,
118+
seedName: null,
119+
initialAppearance: "dark" as const,
120+
};
121+
state.session = session;
122+
expect(themeColorToHex(renderEditor()?.[field]?.colors.accent ?? "")).toBe("#1f6e4a");
123+
124+
updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });
125+
expect(themeColorToHex(getThemeDefinition(theme.id)?.colors.accent ?? "")).toBe("#7241b8");
126+
state.session = null;
127+
expect(renderEditor()).toBeNull();
128+
state.session = { ...session, id: 2 };
129+
130+
expect(themeColorToHex(renderEditor()?.[field]?.colors.accent ?? "")).toBe("#7241b8");
131+
},
132+
);
133+
134+
it.each(["editingTheme", "seedTheme"] as const)(
135+
"refreshes an open %s when the library changes",
136+
(field) => {
137+
const theme = installCustomTheme(
138+
parseThemeFile({
139+
version: THEME_FILE_VERSION,
140+
id: "updated-theme",
141+
name: "Updated theme",
142+
appearance: "dark",
143+
colors: { accent: "#1f6e4a" },
144+
}),
145+
);
146+
state.session = {
147+
id: 1,
148+
editingThemeId: field === "editingTheme" ? theme.id : null,
149+
seedThemeId: field === "seedTheme" ? theme.id : null,
150+
seedName: null,
151+
initialAppearance: "dark",
152+
};
153+
let editor = renderEditor();
154+
state.onStoreChange.mockImplementation(() => {
155+
editor = renderEditor();
156+
});
157+
158+
updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });
159+
160+
expect(themeColorToHex(editor?.[field]?.colors.accent ?? "")).toBe("#7241b8");
161+
},
162+
);
163+
164+
it("does not keep editing a theme removed from the library", () => {
165+
const theme = installCustomTheme(
166+
parseThemeFile({
167+
version: THEME_FILE_VERSION,
168+
id: "removed-theme",
169+
name: "Removed theme",
170+
appearance: "dark",
171+
colors: { accent: "#1f6e4a" },
172+
}),
173+
);
174+
state.session = {
175+
id: 1,
176+
editingThemeId: theme.id,
177+
seedThemeId: null,
178+
seedName: null,
179+
initialAppearance: "dark",
180+
};
181+
let editor = renderEditor();
182+
expect(editor?.editingTheme?.id).toBe(theme.id);
183+
state.onStoreChange.mockImplementation(() => {
184+
editor = renderEditor();
185+
});
186+
187+
removeCustomTheme(theme.id);
188+
189+
expect(editor?.editingTheme).toBeNull();
190+
});
191+
});

‎apps/web/src/components/settings/ThemeEditorHost.tsx‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1-
import { lazy, Suspense, useCallback } from "react";
1+
import { lazy, Suspense, useCallback, useSyncExternalStore } from "react";
22

33
import { useTheme } from "../../hooks/useTheme";
4-
import { getThemeDefinition, type ThemeAppearance, type ThemeDefinition } from "../../themePalette";
4+
import {
5+
getThemeDefinition,
6+
subscribeToCustomThemes,
7+
type ThemeAppearance,
8+
type ThemeDefinition,
9+
} from "../../themePalette";
510
import { stackedThreadToast, toastManager } from "../ui/toast";
611
import { useThemeEditorStore } from "./themeEditorStore";
712

@@ -12,6 +17,14 @@ const ThemeEditorPanel = lazy(() =>
1217
import("./ThemeEditorPanel").then((module) => ({ default: module.ThemeEditorPanel })),
1318
);
1419

20+
function useThemeDefinition(id: string | null | undefined) {
21+
return useSyncExternalStore(
22+
subscribeToCustomThemes,
23+
() => (id ? (getThemeDefinition(id) ?? null) : null),
24+
() => null,
25+
);
26+
}
27+
1528
/**
1629
* Renders the theme editor above the router. The editor paints its draft on
1730
* the live app, so it has to outlive the settings route: the point is to walk
@@ -21,6 +34,9 @@ export function ThemeEditorHost() {
2134
const session = useThemeEditorStore((store) => store.session);
2235
const closeThemeEditor = useThemeEditorStore((store) => store.closeThemeEditor);
2336
const { theme, setTheme, themeHalves, refreshTheme } = useTheme();
37+
// A saved definition can change without its id changing between sessions.
38+
const editingTheme = useThemeDefinition(session?.editingThemeId);
39+
const seedTheme = useThemeDefinition(session?.seedThemeId);
2440

2541
// The panel reports which path it actually took: a theme removed while its
2642
// editor is open resolves to null there, so the save becomes a create even
@@ -95,13 +111,6 @@ export function ThemeEditorHost() {
95111

96112
if (!session) return null;
97113

98-
// Resolve on every render: an edit or import can change the stored
99-
// definitions while a session is open.
100-
const editingTheme = session.editingThemeId
101-
? (getThemeDefinition(session.editingThemeId) ?? null)
102-
: null;
103-
const seedTheme = session.seedThemeId ? (getThemeDefinition(session.seedThemeId) ?? null) : null;
104-
105114
return (
106115
<Suspense fallback={null}>
107116
<ThemeEditorPanel

0 commit comments

Comments
 (0)