@devries-cameron20 / t3code Mirror · read-only / commits / cb931fcbe2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 19:45 UTC

fix(web): a save in one tab no longer erases what another tab saved (#35110)

Julius Marminge committed Nov 12, 2026 at 02:47 UTC cb931fcbe2fcc6d539e0ede7d71f212f3552524e
7 files changed +239 -14
apps/web/src/clientPersistenceStorage.ts
+15
@@ -23,3 +23,18 @@ export function writeBrowserClientSettings(settings: ClientSettings): void {
23
24 setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema);
25 }
26 +
27 +/** Storage events fire only for other tabs' writes; a null key means storage was cleared. */
28 +export function subscribeBrowserClientSettingsWrites(onChange: () => void): () => void {
29 + if (!hasWindow()) {
30 + return () => undefined;
31 + }
32 + const handleStorage = (event: StorageEvent) => {
33 + if (event.key === CLIENT_SETTINGS_STORAGE_KEY || event.key === null) {
34 + onChange();
35 + }
36 + };
37 + const target = window;
38 + target.addEventListener("storage", handleStorage);
39 + return () => target.removeEventListener("storage", handleStorage);
40 +}
apps/web/src/composerDraftStore.test.ts
+33
@@ -73,6 +73,7 @@ function selectionsByProvider(
73 return result;
74 }
75 import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test";
76 +import { createMemoryStorage } from "./lib/storage";
77
78 import {
79 COMPOSER_DRAFT_STORAGE_KEY,
@@ -722,6 +723,38 @@ describe("composerDraftStore context persistence", () => {
723 expect(draft?.previewAnnotations).toEqual([annotation]);
724 }
725 });
726 +
727 + // regression: #35010 typing a draft in one tab erased drafts another tab saved after it loaded
728 + it("keeps a draft another tab saved after this tab loaded", async () => {
729 + const sharedStorage = createMemoryStorage();
730 + vi.stubGlobal("localStorage", sharedStorage);
731 + vi.stubGlobal("window", new EventTarget());
732 + vi.useFakeTimers();
733 + vi.resetModules();
734 + try {
735 + const thisTab = await import("./composerDraftStore");
736 + vi.resetModules();
737 + const otherTab = await import("./composerDraftStore");
738 + const betaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("beta-new-thread"));
739 + const alphaRef = scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("alpha-new-thread"));
740 +
741 + otherTab.useComposerDraftStore.getState().setPrompt(betaRef, "beta draft");
742 + await vi.advanceTimersByTimeAsync(300);
743 + window.dispatchEvent(
744 + Object.assign(new Event("storage"), { key: COMPOSER_DRAFT_STORAGE_KEY }),
745 + );
746 + thisTab.useComposerDraftStore.getState().setPrompt(alphaRef, "alpha draft");
747 + await vi.advanceTimersByTimeAsync(300);
748 +
749 + const saved = JSON.parse(sharedStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) as string);
750 + expect(saved.state.draftsByThreadKey[scopedThreadKey(betaRef)]?.prompt).toBe("beta draft");
751 + expect(saved.state.draftsByThreadKey[scopedThreadKey(alphaRef)]?.prompt).toBe("alpha draft");
752 + } finally {
753 + vi.useRealTimers();
754 + vi.unstubAllGlobals();
755 + vi.resetModules();
756 + }
757 + });
758 });
759
760 describe("composerDraftStore thread contexts", () => {
apps/web/src/composerDraftStore.ts
+101 -9
@@ -126,16 +126,106 @@ type ComposerPersistState =
126 | { capturedState: ComposerDraftStoreState }
127 | PersistedComposerDraftStoreState;
128
129 +const composerDraftBaseStorage =
130 + typeof localStorage !== "undefined" ? localStorage : createMemoryStorage();
131 +
132 +interface ComposerDraftWrite {
133 + readonly text: string;
134 + /** This tab's own state as of the write; entries it still matches were not edited here. */
135 + readonly local: PersistedComposerDraftStoreState;
136 + readonly merged: PersistedComposerDraftStoreState;
137 +}
138 +let composerDraftLoadedState: PersistedComposerDraftStoreState | null = null;
139 +let composerDraftLastWrite: ComposerDraftWrite | null = null;
140 +let composerDraftPendingWrite: ComposerDraftWrite | null = null;
141 +
142 +function readStoredComposerDraftState(): PersistedComposerDraftStoreState | null {
143 + const text = composerDraftBaseStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY);
144 + if (typeof text !== "string") return null;
145 + if (text === composerDraftLastWrite?.text) return composerDraftLastWrite.merged;
146 + try {
147 + const parsed = JSON.parse(text) as StorageValue<PersistedComposerDraftStoreState>;
148 + return parsed.version === COMPOSER_DRAFT_STORAGE_VERSION ? parsed.state : null;
149 + } catch {
150 + return null;
151 + }
152 +}
153 +
154 +function mergeDraftRecord<V>(
155 + stored: Readonly<Record<string, V>> | undefined,
156 + local: Readonly<Record<string, V>>,
157 + baseline: Readonly<Record<string, V>>,
158 +): Record<string, V> {
159 + const merged = { ...stored };
160 + for (const key of new Set([...Object.keys(local), ...Object.keys(baseline)])) {
161 + if (Equal.equals(local[key], baseline[key])) continue;
162 + const value = local[key];
163 + if (value === undefined) delete merged[key];
164 + else merged[key] = value;
165 + }
166 + return merged;
167 +}
168 +
169 +/** Writes only what this tab changed since its last write over what other tabs saved since. */
170 +function mergeComposerDraftStates(
171 + stored: PersistedComposerDraftStoreState,
172 + local: PersistedComposerDraftStoreState,
173 + baseline: PersistedComposerDraftStoreState,
174 +): PersistedComposerDraftStoreState {
175 + const pick = <K extends keyof PersistedComposerDraftStoreState>(key: K) => {
176 + const value = Equal.equals(local[key], baseline[key]) ? stored[key] : local[key];
177 + return value === undefined ? {} : { [key]: value };
178 + };
179 + return {
180 + draftsByThreadKey: mergeDraftRecord(
181 + stored.draftsByThreadKey,
182 + local.draftsByThreadKey,
183 + baseline.draftsByThreadKey,
184 + ),
185 + draftThreadsByThreadKey: mergeDraftRecord(
186 + stored.draftThreadsByThreadKey,
187 + local.draftThreadsByThreadKey,
188 + baseline.draftThreadsByThreadKey,
189 + ),
190 + logicalProjectDraftThreadKeyByLogicalProjectKey: mergeDraftRecord(
191 + stored.logicalProjectDraftThreadKeyByLogicalProjectKey,
192 + local.logicalProjectDraftThreadKeyByLogicalProjectKey,
193 + baseline.logicalProjectDraftThreadKeyByLogicalProjectKey,
194 + ),
195 + ...pick("stickyModelSelectionByProvider"),
196 + ...pick("stickyOptionsByModelByProvider"),
197 + ...pick("stickyActiveProvider"),
198 + };
199 +}
200 +
201 +function serializeComposerDraftState(value: StorageValue<ComposerPersistState>): string {
202 + if (!("capturedState" in value.state)) {
203 + return JSON.stringify({ state: value.state, version: value.version });
204 + }
205 + const local = partializeComposerDraftStoreState(value.state.capturedState);
206 + const baseline = composerDraftLastWrite?.local ?? composerDraftLoadedState;
207 + const stored = baseline ? readStoredComposerDraftState() : null;
208 + const merged = stored && baseline ? mergeComposerDraftStates(stored, local, baseline) : local;
209 + const text = JSON.stringify({ state: merged, version: value.version });
210 + composerDraftPendingWrite = { text, local, merged };
211 + return text;
212 +}
213 +
214 const composerDebouncedStorage = createDeferredStorage<StorageValue<ComposerPersistState>>(
130 - typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),
131 - (value) =>
132 - JSON.stringify({
133 - state:
134 - "capturedState" in value.state
135 - ? partializeComposerDraftStoreState(value.state.capturedState)
136 - : value.state,
137 - version: value.version,
138 - }),
215 + {
216 + getItem: (name) => composerDraftBaseStorage.getItem(name),
217 + setItem: (name, text) => {
218 + composerDraftBaseStorage.setItem(name, text);
219 + if (composerDraftPendingWrite?.text === text)
220 + composerDraftLastWrite = composerDraftPendingWrite;
221 + },
222 + removeItem: (name) => {
223 + composerDraftBaseStorage.removeItem(name);
224 + composerDraftLoadedState = null;
225 + composerDraftLastWrite = null;
226 + },
227 + },
228 + serializeComposerDraftState,
229 COMPOSER_PERSIST_DEBOUNCE_MS,
230 );
231
@@ -4359,6 +4449,8 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
4449 ),
4450 );
4451
4452 +composerDraftLoadedState = partializeComposerDraftStoreState(composerDraftStore.getState());
4453 +
4454 export const useComposerDraftStore = composerDraftStore;
4455
4456 export function subscribeComposerDraftModelReconciliation(input: {
apps/web/src/hooks/useSettings.test.ts
+22
@@ -195,6 +195,28 @@ describe("persistClientSettingsPatch", () => {
195 expect(persistenceMocks.setClientSettings).toHaveBeenNthCalledWith(1, firstSettings);
196 expect(persistenceMocks.setClientSettings).toHaveBeenNthCalledWith(2, secondSettings);
197 });
198 +
199 + // regression: #35010 a save in one tab reverted settings another tab saved after it loaded
200 + it("keeps a setting another tab saved after this tab loaded", async () => {
201 + vi.stubGlobal("window", new EventTarget());
202 + try {
203 + await ensureClientSettingsHydrated();
204 + const otherTabSettings = { ...DEFAULT_CLIENT_SETTINGS, timestampFormat: "12-hour" as const };
205 + persistenceMocks.getClientSettings.mockResolvedValue(otherTabSettings);
206 + window.dispatchEvent(
207 + Object.assign(new Event("storage"), { key: "t3code:client-settings:v1" }),
208 + );
209 +
210 + await persistClientSettingsPatch({ wordWrap: false });
211 +
212 + expect(persistenceMocks.setClientSettings).toHaveBeenLastCalledWith({
213 + ...otherTabSettings,
214 + wordWrap: false,
215 + });
216 + } finally {
217 + vi.unstubAllGlobals();
218 + }
219 + });
220 });
221
222 describe("persistClientSettingsUpdate", () => {
apps/web/src/hooks/useSettings.ts
+28 -1
@@ -31,6 +31,7 @@ import {
31 supportsSharedSettingsSync,
32 } from "@t3tools/client-runtime/state/shared-settings";
33 import { ensureLocalApi } from "~/localApi";
34 +import { subscribeBrowserClientSettingsWrites } from "~/clientPersistenceStorage";
35 import {
36 getThemeDefinition,
37 getThemePreviewSidebarArtwork,
@@ -75,6 +76,7 @@ let clientSettingsHydrationPromise: Promise<void> | null = null;
76 let clientSettingsHydrationGeneration = 0;
77 let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
78 let deferredClientSettingsPatchCount = 0;
79 +let unsubscribeOtherTabClientSettings: (() => void) | null = null;
80
81 function emitClientSettingsChange() {
82 for (const listener of clientSettingsListeners) {
@@ -152,6 +154,9 @@ async function hydrateClientSettings(): Promise<void> {
154 if (persistedSettings) {
155 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
156 }
157 + unsubscribeOtherTabClientSettings ??= subscribeBrowserClientSettingsWrites(
158 + refreshClientSettingsFromOtherTab,
159 + );
160 setClientSettingsHydrationStatus("ready");
161 } catch (error) {
162 if (hydrationGeneration === clientSettingsHydrationGeneration) {
@@ -175,6 +180,20 @@ async function hydrateClientSettings(): Promise<void> {
180 return clientSettingsHydrationPromise;
181 }
182
183 +function refreshClientSettingsFromOtherTab(): void {
184 + void enqueueClientSettingsPersistence(async () => {
185 + const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
186 + if (persistedSettings) {
187 + replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
188 + }
189 + }).catch((error) => {
190 + console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} refresh failed`, {
191 + operation: "refresh",
192 + ...safeErrorLogAttributes(error),
193 + });
194 + });
195 +}
196 +
197 const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
198 ensureLocalApi().persistence.setClientSettings(settings);
199
@@ -205,11 +224,17 @@ export function persistClientSettingsPatch(
224 if (clientSettingsHydrationStatus !== "ready") {
225 await hydrateClientSettings();
226 }
208 - replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
227 } finally {
228 deferredClientSettingsPatchCount -= 1;
229 }
230 }
231 + // Also reapplies an optimistic patch that a refresh from another tab replaced.
232 + const current = getClientSettingsSnapshot();
233 + if (
234 + !Object.entries(patch).every(([key, value]) => current[key as keyof ClientSettings] === value)
235 + ) {
236 + replaceClientSettingsSnapshot({ ...current, ...patch });
237 + }
238 await persist(getClientSettingsSnapshot());
239 }).catch((error) => {
240 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
@@ -755,6 +780,8 @@ export function __resetClientSettingsPersistenceForTests(): void {
780 clientSettingsHydrationPromise = null;
781 clientSettingsPersistenceQueue = Promise.resolve();
782 deferredClientSettingsPatchCount = 0;
783 + unsubscribeOtherTabClientSettings?.();
784 + unsubscribeOtherTabClientSettings = null;
785 clientSettingsListeners.clear();
786 clientSettingsHydrationListeners.clear();
787 }
apps/web/src/promptStashStore.test.ts
+29 -1
@@ -1,4 +1,4 @@
1 -import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";
1 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
3 import {
4 collectAssistantCitations,
@@ -6,6 +6,7 @@ import {
6 } from "@t3tools/shared/assistantCitations";
7
8 import { removeLocalStorageItem } from "./hooks/useLocalStorage";
9 +import { createMemoryStorage } from "./lib/storage";
10
11 import {
12 MAX_STASH_ENTRIES,
@@ -236,6 +237,33 @@ describe("promptStashStore", () => {
237 );
238 expect(usePromptStashStore.getState().entries).toEqual([]);
239 });
240 +
241 + // regression: #35010 stashing in one tab erased what another tab stashed after it loaded
242 + it("keeps an entry another tab stashed after this tab loaded", async () => {
243 + const sharedStorage = createMemoryStorage();
244 + vi.stubGlobal("localStorage", sharedStorage);
245 + vi.stubGlobal("window", new EventTarget());
246 + vi.resetModules();
247 + try {
248 + const thisTab = await import("./promptStashStore");
249 + sharedStorage.setItem(
250 + PROMPT_STASH_STORAGE_KEY,
251 + JSON.stringify({ version: 2, state: { entries: [makeEntry({ id: "other-tab" })] } }),
252 + );
253 + window.dispatchEvent(Object.assign(new Event("storage"), { key: PROMPT_STASH_STORAGE_KEY }));
254 +
255 + thisTab.usePromptStashStore.getState().stashEntry(makeEntry({ id: "this-tab" }));
256 +
257 + const saved = JSON.parse(sharedStorage.getItem(PROMPT_STASH_STORAGE_KEY) as string);
258 + expect(saved.state.entries.map((entry: PromptStashEntry) => entry.id)).toEqual([
259 + "this-tab",
260 + "other-tab",
261 + ]);
262 + } finally {
263 + vi.unstubAllGlobals();
264 + vi.resetModules();
265 + }
266 + });
267 });
268
269 describe("prompt stash context records", () => {
apps/web/src/promptStashStore.ts
+11 -3
@@ -122,6 +122,14 @@ function readPersistedEntries(): ReadonlyArray<PromptStashEntry> | null {
122 }
123 }
124
125 +/** Starts each write from storage so entries other tabs stashed or took are not overwritten. */
126 +function latestEntries(memory: ReadonlyArray<PromptStashEntry>): ReadonlyArray<PromptStashEntry> {
127 + const stored = readPersistedEntries();
128 + if (!stored) return memory;
129 + const memoryById = new Map(memory.map((entry) => [entry.id, entry]));
130 + return stored.map((entry) => memoryById.get(entry.id) ?? entry);
131 +}
132 +
133 interface PromptStashStoreState {
134 entries: ReadonlyArray<PromptStashEntry>;
135 stashEntry: (entry: PromptStashEntry) => {
@@ -147,7 +155,7 @@ interface PromptStashStoreState {
155 export const usePromptStashStore = create<PromptStashStoreState>()((set, get) => ({
156 entries: [],
157 stashEntry: (entry) => {
150 - const nextEntries = [entry, ...get().entries];
158 + const nextEntries = [entry, ...latestEntries(get().entries)];
159 const evicted = nextEntries.length > MAX_STASH_ENTRIES ? (nextEntries.pop() ?? null) : null;
160 const { written, durable } = persistEntries(nextEntries);
161 // Failed writes must not duplicate the intact composer; eviction also commits only on success.
@@ -158,7 +166,7 @@ export const usePromptStashStore = create<PromptStashStoreState>()((set, get) =>
166 return { evicted, written: true, durable };
167 },
168 takeEntry: (entryId) => {
161 - const entries = get().entries;
169 + const entries = latestEntries(get().entries);
170 const entry = entries.find((candidate) => candidate.id === entryId) ?? null;
171 if (!entry) return { entry: null, durable: true };
172 const nextEntries = entries.filter((candidate) => candidate.id !== entryId);
@@ -167,7 +175,7 @@ export const usePromptStashStore = create<PromptStashStoreState>()((set, get) =>
175 return { entry, durable };
176 },
177 finalizeEntryImages: (entryId, images) => {
170 - const entries = get().entries;
178 + const entries = latestEntries(get().entries);
179 const index = entries.findIndex((candidate) => candidate.id === entryId);
180 const existing = index === -1 ? undefined : entries[index];
181 if (!existing) return { attached: false, durable: true };