Skip to content

Commit 40a00b7

Browse files
dr0uleaucodex
andauthored
Expose Solo region state before a component mounts (#3296)
## Why A plugin can change a saved Solo region filter before its component mounts. It needs the same state that the host gives the component. ## What `SoloRegionHandle.state(binding)` exposes `get()`, `set(value)`, and `subscribe(listener)`. Component props use the same state path. ## How The API reuses the existing device record and its 16 KiB limit. Bindings include scope, viewer, and incarnation. Binding abort and source disposal remove subscriptions. The last write wins. No relay reads or writes are added. Closes #3295. ## Risk The region state path serves plugins in the sidebar. Reads throw for an ended binding or unreadable state without an accepted memory value. Existing saved keys and UI controls stay the same. ## Testing The shipping review finds one cache-order defect. The fix preserves a newer write from a subscriber and restores the prior cache when a write fails. The regression fails before the fix and passes after it. The human author explicitly waives the manual test for this API-only change. One new browser case checks real storage events between windows and restore after reload. Vitest covers the other state and lifetime cases. No browser cases are removed. ## Bigger picture Consumers must require a host release with this API before they depend on it. buzz-review-completed Generated with Codex --------- Signed-off-by: Daniel Rouleau <[email protected]> Co-authored-by: Codex <[email protected]>
1 parent a42ef62 commit 40a00b7

6 files changed

Lines changed: 295 additions & 20 deletions

File tree

‎docs/solo-regions.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,22 @@ unmount, disposal, and registration. It accepts at most 16 KiB. A failed or stal
4848
write returns false and does not update the memory value. Sources must keep their
4949
own accepted state unchanged when a write fails.
5050

51+
`handle.state(binding)` returns `get()`, `set(value)`, and
52+
`subscribe(listener)` for this same record. It works before the component mounts.
53+
The component's `state` has the same methods. `get()` returns `undefined` when
54+
the record is absent and preserves JSON `null`. It throws when the binding ends,
55+
the saved JSON is invalid, or storage is unavailable without an accepted memory
56+
value. `set()` returns false for a stale binding, an invalid value, an oversized
57+
value, or a failed storage write. Writes replace the whole record; the last write
58+
wins. This is device state, with no relay read or write.
59+
60+
Subscribers receive local writes and matching storage events from other windows.
61+
The listener reads the current value with `get()`; it receives no initial call.
62+
Unrelated keys do not notify it. The returned function ends the subscription.
63+
Binding abort and source disposal also remove it. `state(binding)` and
64+
`subscribe()` throw for an ended binding. Source disposal preserves saved bytes.
65+
Plugins must require a host release with `handle.state` before they use this API.
66+
5167
`openDraft` opens the host's New chat editor for the region, optionally in a
5268
workspace, with its own draft, files, model, and effort. Send works like an
5369
ordinary New chat: the create goes out unguarded with the region label before

‎src/features/channel-navigation/SoloRegions.test.tsx‎

Lines changed: 134 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,13 @@ import {
1111
} from "@testing-library/react";
1212
import { afterEach, assert, expect, it, vi } from "vitest";
1313
import userEvent from "@testing-library/user-event";
14-
import { type ReactNode, useCallback, useRef, useState } from "react";
14+
import {
15+
type ReactNode,
16+
useCallback,
17+
useEffect,
18+
useRef,
19+
useState,
20+
} from "react";
1521
import { SoloRegions } from "./SoloRegions";
1622
import { ChannelNavigationProvider } from "./ChannelNavigationState";
1723
import { conversationTarget, soloDraftTarget } from "./routes";
@@ -363,6 +369,133 @@ it("keeps header actions and every owned channel reachable through body failure
363369
expect(screen.queryByText("Must stay outside")).not.toBeInTheDocument();
364370
});
365371

372+
it("shares state before mount and notifies mounted and headless consumers", async () => {
373+
const h = fixture();
374+
let props: SoloRegionProps | undefined;
375+
function StateBody(value: SoloRegionProps) {
376+
props = value;
377+
const [state, setState] = useState(() => value.state.get());
378+
useEffect(
379+
() => value.state.subscribe(() => setState(value.state.get())),
380+
[value.state],
381+
);
382+
return <output aria-label="Saved filter">{JSON.stringify(state)}</output>;
383+
}
384+
const source = await h.register({ component: StateBody });
385+
const state = source.handle.state(source.binding());
386+
expect(state.get()).toBeUndefined();
387+
const listener = vi.fn(() => state.get());
388+
const stop = state.subscribe(listener);
389+
expect(state.set({ filter: "running" })).toBe(true);
390+
expect(listener).toHaveLastReturnedWith({ filter: "running" });
391+
const view = mount(h);
392+
expect(screen.getByLabelText("Saved filter")).toHaveTextContent('"running"');
393+
act(() => {
394+
state.set({ filter: "all-active" });
395+
});
396+
expect(screen.getByLabelText("Saved filter")).toHaveTextContent(
397+
'"all-active"',
398+
);
399+
act(() => {
400+
props?.state.set({ filter: "needs-you" });
401+
});
402+
expect(listener).toHaveLastReturnedWith({ filter: "needs-you" });
403+
view.unmount();
404+
stop();
405+
listener.mockClear();
406+
expect(state.set(null)).toBe(true);
407+
expect(listener).not.toHaveBeenCalled();
408+
expect(state.get()).toBeNull();
409+
});
410+
411+
it("scopes storage notifications and removes subscriptions when a binding or source ends", async () => {
412+
const h = fixture();
413+
const source = await h.register();
414+
const binding = source.binding();
415+
const state = source.handle.state(binding);
416+
const listener = vi.fn();
417+
const remove = vi.spyOn(window, "removeEventListener");
418+
state.subscribe(listener);
419+
const storageKey = `buzz-view.v1:${JSON.stringify([h.scope, `solo-region-state:${binding.viewer}:example/work`])}`;
420+
localStorage.setItem(storageKey, JSON.stringify({ filter: "running" }));
421+
window.dispatchEvent(
422+
new StorageEvent("storage", {
423+
key: `buzz-view.v1:${JSON.stringify([h.scope, "other"])}`,
424+
storageArea: localStorage,
425+
}),
426+
);
427+
expect(listener).not.toHaveBeenCalled();
428+
window.dispatchEvent(
429+
new StorageEvent("storage", { key: storageKey, storageArea: localStorage }),
430+
);
431+
expect(listener).toHaveBeenCalledOnce();
432+
expect(state.get()).toEqual({ filter: "running" });
433+
h.reconnect();
434+
expect(remove).toHaveBeenCalledWith("storage", expect.any(Function));
435+
expect(() => state.get()).toThrow("ended");
436+
expect(state.set(null)).toBe(false);
437+
expect(() => state.subscribe(listener)).toThrow("ended");
438+
expect(() => source.handle.state(binding)).toThrow("ended");
439+
listener.mockClear();
440+
const next = source.handle.state(source.binding());
441+
next.subscribe(listener);
442+
await source.fiber.dispose();
443+
window.dispatchEvent(
444+
new StorageEvent("storage", { key: storageKey, storageArea: localStorage }),
445+
);
446+
expect(listener).not.toHaveBeenCalled();
447+
expect(() => next.get()).toThrow("ended");
448+
const replacement = await h.register();
449+
expect(replacement.handle.state(replacement.binding()).get()).toEqual({
450+
filter: "running",
451+
});
452+
});
453+
454+
it("distinguishes missing state from unavailable storage and rejects invalid or oversized writes", async () => {
455+
const h = fixture();
456+
const source = await h.register();
457+
const state = source.handle.state(source.binding());
458+
expect(state.get()).toBeUndefined();
459+
const read = vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
460+
throw new Error("denied");
461+
});
462+
expect(() => state.get()).toThrow("unavailable");
463+
read.mockRestore();
464+
expect(state.set({ huge: "é".repeat(8192) })).toBe(false);
465+
const circular: { self?: unknown } = {};
466+
circular.self = circular;
467+
expect(state.set(circular as never)).toBe(false);
468+
expect(state.get()).toBeUndefined();
469+
const listener = vi.fn();
470+
state.subscribe(listener);
471+
vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
472+
throw new Error("full");
473+
});
474+
expect(state.set({ filter: "running" })).toBe(false);
475+
expect(listener).not.toHaveBeenCalled();
476+
expect(state.get()).toBeUndefined();
477+
});
478+
479+
it("retains the latest accepted subscriber write when storage becomes unavailable", async () => {
480+
const h = fixture();
481+
const source = await h.register();
482+
const state = source.handle.state(source.binding());
483+
const nested = vi.fn(() => state.set("second"));
484+
const stop = state.subscribe(() => {
485+
if (state.get() === "first") nested();
486+
});
487+
expect(state.set("first")).toBe(true);
488+
expect(nested).toHaveLastReturnedWith(true);
489+
expect(state.get()).toBe("second");
490+
stop();
491+
vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
492+
throw new Error("denied");
493+
});
494+
expect(state.get()).toBe("second");
495+
expect(state.set("rejected")).toBe(false);
496+
expect(state.get()).toBe("second");
497+
});
498+
366499
it("retains accepted presentation state across unmount, disposal and re-registration and refuses stale or failed writes", async () => {
367500
const h = fixture();
368501
let props: SoloRegionProps | undefined;

‎src/features/channel-navigation/solo-navigation-contract.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ export type SoloChatInput = Readonly<{
7070
}>;
7171
export type SoloRegionHandle = Readonly<{
7272
label: string;
73+
/** The same device state as component props, available before mount. */
74+
state(binding: SoloRegionBinding): SoloRegionProps["state"];
7375
/** Open New chat for this region. Its first send creates the chat with this
7476
* region's label; until then it is only a draft. With `lead`, the chat starts
7577
* as the workspace's lead while the draft still targets that workspace. */
@@ -97,6 +99,7 @@ export type SoloRegionProps = Readonly<{
9799
state: Readonly<{
98100
get(): JsonValue | undefined;
99101
set(value: JsonValue): boolean;
102+
subscribe(listener: () => void): () => void;
100103
}>;
101104
ui: Readonly<{
102105
Conversation: ComponentType<SoloConversationProps>;

‎src/features/channel-navigation/solo-navigation.ts‎

Lines changed: 77 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import { Service, type Context } from "@deepseek-ai/cordis";
22
import { createContributions } from "../../plugins/contributions";
3-
import { readView, viewRevision, writeView } from "../../shared/view-state";
3+
import {
4+
readView,
5+
subscribeView,
6+
viewRevision,
7+
writeView,
8+
} from "../../shared/view-state";
49
import type { RelayData, RelaySnapshot } from "../relay/service";
510
import type { RelaySession } from "../relay/session";
611
import type { JsonValue } from "../navigation/targets";
@@ -149,8 +154,6 @@ export class SoloNavigationService extends Service implements SoloNavigation {
149154
presentation(source: RegisteredSoloSource, binding: SoloRegionBinding) {
150155
const active = () =>
151156
sameBinding(this.binding, binding) && this.sources().includes(source);
152-
const key = `solo-region-state:${binding.viewer}:${source.key}`;
153-
const memoryKey = `${binding.scope}/${key}`;
154157
return {
155158
revealRequests: {
156159
subscribe: (listener: (channelId: string) => void) => {
@@ -172,30 +175,79 @@ export class SoloNavigationService extends Service implements SoloNavigation {
172175
return stop;
173176
},
174177
},
175-
state: {
176-
get: () => {
177-
const saved = viewRevision(binding.scope, key);
178-
if (saved === undefined && this.states.has(memoryKey))
178+
state: this.regionState(source, binding),
179+
};
180+
}
181+
private regionState(
182+
source: RegisteredSoloSource,
183+
binding: SoloRegionBinding,
184+
) {
185+
binding = Object.freeze({ ...binding });
186+
const active = () =>
187+
sameBinding(this.binding, binding) && this.sources().includes(source);
188+
const key = `solo-region-state:${binding.viewer}:${source.key}`;
189+
const memoryKey = `${binding.scope}/${key}`;
190+
const current = () => {
191+
if (!active()) throw new Error("This Solo region binding has ended");
192+
};
193+
return {
194+
get: () => {
195+
current();
196+
const saved = viewRevision(binding.scope, key);
197+
if (saved === undefined) {
198+
if (this.states.has(memoryKey))
179199
return structuredClone(this.states.get(memoryKey));
180-
try {
181-
return saved ? (JSON.parse(saved) as JsonValue) : undefined;
182-
} catch {
183-
return undefined;
184-
}
185-
},
186-
set: (value: JsonValue) => {
187-
if (!active()) return false;
200+
throw new Error("Solo region storage is unavailable");
201+
}
202+
try {
203+
return saved === null ? undefined : (JSON.parse(saved) as JsonValue);
204+
} catch {
205+
throw new Error("Solo region state is invalid");
206+
}
207+
},
208+
set: (value: JsonValue) => {
209+
if (!active()) return false;
210+
try {
188211
const json = JSON.stringify(value);
189212
if (
190213
json === undefined ||
191214
new TextEncoder().encode(json).length > 16 * 1024
192215
)
193216
return false;
194217
const copy = JSON.parse(json) as JsonValue;
195-
if (!writeView(binding.scope, key, copy)) return false;
218+
const previous = this.states.get(memoryKey);
219+
// writeView notifies synchronously; a listener can accept a newer value.
196220
this.states.set(memoryKey, copy);
221+
if (!writeView(binding.scope, key, copy)) {
222+
if (previous === undefined) this.states.delete(memoryKey);
223+
else this.states.set(memoryKey, previous);
224+
return false;
225+
}
197226
return true;
198-
},
227+
} catch {
228+
return false;
229+
}
230+
},
231+
subscribe: (listener: () => void) => {
232+
current();
233+
const signal = this.runtimes.get(source)?.controller.signal;
234+
if (!signal || signal.aborted)
235+
throw new Error("This Solo region binding has ended");
236+
const stopView = subscribeView(binding.scope, (changedKey) => {
237+
if (active() && (changedKey === undefined || changedKey === key)) {
238+
try {
239+
listener();
240+
} catch {
241+
/* A source listener cannot reject an accepted storage write. */
242+
}
243+
}
244+
});
245+
const stop = () => {
246+
stopView();
247+
signal.removeEventListener("abort", stop);
248+
};
249+
signal.addEventListener("abort", stop, { once: true });
250+
return stop;
199251
},
200252
};
201253
}
@@ -455,6 +507,14 @@ export class SoloNavigationService extends Service implements SoloNavigation {
455507
this.contributions.register(this.ctx, { ...source, identity });
456508
return Object.freeze({
457509
label,
510+
state(binding) {
511+
current(binding);
512+
const registered = host
513+
.sources()
514+
.find((entry) => entry.identity === identity);
515+
if (!registered) throw new Error("This Solo region binding has ended");
516+
return host.regionState(registered, binding);
517+
},
458518
openDraft(binding, input = {}) {
459519
current(binding);
460520
const { workspace } = input;

‎tests/browser/solo-region-fixture.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type {
99
declare global {
1010
interface Window {
1111
fixtureSoloRegion?: {
12+
state(): SoloRegionProps["state"];
1213
classify(id: string): Promise<void>;
1314
createWorkspace(): Promise<void>;
1415
present(removed: string[], hidden: string[]): void;
@@ -66,14 +67,28 @@ export const soloRegionFixture: BundledPlugin = {
6667
const composing = new URL(location.href).searchParams.has(
6768
"compose-workspaces",
6869
);
70+
const stateFixture = new URL(location.href).searchParams.has(
71+
"region-state-fixture",
72+
);
73+
function SavedState({ state }: Pick<SoloRegionProps, "state">) {
74+
const value = useSyncExternalStore(
75+
state.subscribe,
76+
() => JSON.stringify(state.get()) ?? "absent",
77+
);
78+
return <output aria-label="Region state">{value}</output>;
79+
}
6980
const handle = ctx.soloNavigation.registerSource({
7081
...(composing ? { composeWorkspaces: true } : {}),
7182
id: "work",
7283
title: "Solo",
7384
icon: null,
7485
bind(next) {
7586
binding = next;
76-
snapshot = { status: "ready", binding, revision: 1 };
87+
snapshot = {
88+
status: stateFixture ? "loading" : "ready",
89+
binding,
90+
revision: 1,
91+
};
7792
},
7893
read: () => snapshot,
7994
subscribe(listener) {
@@ -82,8 +97,9 @@ export const soloRegionFixture: BundledPlugin = {
8297
notify = () => {};
8398
};
8499
},
85-
component: ({ ui, live, binding }) => (
100+
component: ({ ui, live, binding, state }) => (
86101
<>
102+
{stateFixture && <SavedState state={state} />}
87103
{hitTargets && <Workspaces ui={ui} binding={binding} />}
88104
{[...live]
89105
.filter((id) => !removed.includes(id))
@@ -110,6 +126,7 @@ export const soloRegionFixture: BundledPlugin = {
110126
});
111127
let disposeTransient = async () => {};
112128
window.fixtureSoloRegion = {
129+
state: () => handle.state(binding),
113130
createWorkspace: () =>
114131
navigation.workspaces.create(binding, {
115132
id: "fixture-workspace",

0 commit comments

Comments
 (0)