Compare commits

...
Author SHA1 Message Date
Julius Marminge eca89790d4 Use Debouncer for composer draft persistence writes
- Replace manual timeout/pending-value debounce logic with `@tanstack/react-pacer` `Debouncer`
- Keep `removeItem`/`flush` behavior while simplifying and standardizing persistence timing
2026-03-09 13:00:27 -07:00
Julius Marminge f9dab13472 Use React Pacer throttler for domain event snapshot sync
- Replace manual timeout-based domain event batching with `Throttler`
- Keep provider query invalidation batched with trailing 100ms flushes
- Cancel throttler and reset invalidation flag during EventRouter cleanup
2026-03-09 12:45:34 -07:00
Julius Marminge 4babb1a859 Use Debouncer for store state persistence
- Replace manual timeout debounce logic with `@tanstack/react-pacer`'s `Debouncer`
- Persist updates via `maybeExecute` to reduce localStorage write thrashing
- Flush pending persistence on `beforeunload` to avoid losing recent state
2026-03-09 12:28:26 -07:00
Julius Marminge 75533fbd40 Remove ProviderHealth onReady callback from service interface
- Drop the unused `onReady` hook from `ProviderHealthShape`
- Keep startup health status access focused on `getStatuses`
2026-03-09 12:23:33 -07:00
Tim SmartandClaude Opus 4.6 fd98835834 cleanup
Co-Authored-By: Claude Opus 4.6 <[email protected]>
2026-03-09 12:18:33 -07:00
Chukwudi Nwobodo c6dc7c6524 perf: run provider health checks in background, notify clients on ready
The ProviderHealth layer blocked server startup with two sequential CLI
spawns (codex --version + codex login status), each with a 4-second
timeout, delaying startup by up to 8 seconds.

Run health checks in the background via Effect.runPromise so the layer
resolves immediately with a placeholder status. Add an onReady callback
to ProviderHealthShape so wsServer can push the resolved statuses to
connected clients once checks complete, preventing early-connecting
clients from showing "Checking..." indefinitely.
2026-03-08 06:22:26 +00:00
Chukwudi Nwobodo a04e3561ed perf: throttle domain event processing with 100ms batch window
During active sessions, every domain event triggered a full
syncSnapshot (IPC fetch + state rebuild + React re-render cascade) and
sometimes a provider query invalidation. Events fire in rapid bursts
during AI turns.

Replace per-event processing with a throttle-first pattern: schedule a
flush on the first event, absorb subsequent events within a 100ms
window, then sync once. Provider query invalidation is batched via a
flag. Since syncSnapshot fetches the complete snapshot, no events are
lost by skipping intermediate syncs.
2026-03-08 06:22:14 +00:00
Chukwudi Nwobodo dd51d4faec perf: debounce Zustand store persistence and deduplicate legacy cleanup
The useStore subscriber called persistState on every state mutation,
triggering JSON.stringify + localStorage.setItem synchronously. It also
ran 8 localStorage.removeItem calls for legacy keys on every fire.

Wrap the subscriber with a 500ms debounce so rapid state changes batch
into a single write. Move legacy key cleanup behind a one-time flag so
it runs only once per page load. Add a beforeunload handler to flush
the final state.
2026-03-08 06:22:02 +00:00
Chukwudi Nwobodo e21687300e perf: debounce composer draft localStorage writes
Every keystroke triggered full JSON serialization of all composer drafts
(including base64 image attachments) and a synchronous localStorage
write. At normal typing speed this caused 5+ writes/sec, blocking the
main thread and creating noticeable input lag.

Wrap the Zustand persist storage with a 300ms debounce. In-memory state
updates remain immediate; only the serialization and storage write are
deferred. A beforeunload handler flushes pending writes to prevent data
loss. The removeItem method cancels any pending setItem to avoid
resurrecting cleared drafts.

Adds unit tests for the DebouncedStorage utility covering debounce
timing, rapid writes, removeItem cancellation, flush, and edge cases.
2026-03-08 06:21:52 +00:00
6 changed files with 236 additions and 17 deletions

No files matched your search

@@ -13,7 +13,7 @@ import type {
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Result, Stream } from "effect";
import { Array, Effect, Fiber, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
@@ -312,9 +312,13 @@ export const checkCodexProviderStatus: Effect.Effect<
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const codexStatus = yield* checkCodexProviderStatus;
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
Effect.map(Array.of),
Effect.forkScoped,
);
return {
getStatuses: Effect.succeed([codexStatus]),
getStatuses: Fiber.join(codexStatusFiber),
} satisfies ProviderHealthShape;
}),
);
+20 -4
View File
@@ -26,6 +26,7 @@ import {
WebSocketRequest,
WsPush,
WsResponse,
ServerProviderStatus,
} from "@t3tools/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import {
@@ -268,8 +269,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
),
);
const providerStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
@@ -617,6 +616,23 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const subscriptionsScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
// Push updated provider statuses to connected clients once background health checks finish.
let providers: ReadonlyArray<ServerProviderStatus> = [];
yield* providerHealth.getStatuses.pipe(
Effect.flatMap((statuses) => {
providers = statuses;
return broadcastPush({
type: "push",
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: [],
providers: statuses,
},
});
}),
Effect.forkIn(subscriptionsScope),
);
yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
broadcastPush({
type: "push",
@@ -631,7 +647,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: event.issues,
providers: providerStatuses,
providers,
},
}),
).pipe(Effect.forkIn(subscriptionsScope));
@@ -883,7 +899,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers: providerStatuses,
providers,
availableEditors,
};
+127 -1
View File
@@ -1,7 +1,11 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
import {
type ComposerImageAttachment,
createDebouncedStorage,
useComposerDraftStore,
} from "./composerDraftStore";
function makeImage(input: {
id: string;
@@ -451,3 +455,125 @@ describe("composerDraftStore runtime and interaction settings", () => {
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
});
// ---------------------------------------------------------------------------
// createDebouncedStorage
// ---------------------------------------------------------------------------
function createMockStorage() {
const store = new Map<string, string>();
return {
getItem: vi.fn((name: string) => store.get(name) ?? null),
setItem: vi.fn((name: string, value: string) => {
store.set(name, value);
}),
removeItem: vi.fn((name: string) => {
store.delete(name);
}),
};
}
describe("createDebouncedStorage", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("delegates getItem immediately", () => {
const base = createMockStorage();
base.getItem.mockReturnValueOnce("value");
const storage = createDebouncedStorage(base);
expect(storage.getItem("key")).toBe("value");
expect(base.getItem).toHaveBeenCalledWith("key");
});
it("does not write to base storage until the debounce fires", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(299);
expect(base.setItem).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
});
it("only writes the last value when setItem is called rapidly", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.setItem("key", "v2");
storage.setItem("key", "v3");
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v3");
});
it("removeItem cancels a pending setItem write", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.removeItem("key");
vi.advanceTimersByTime(300);
expect(base.setItem).not.toHaveBeenCalled();
expect(base.removeItem).toHaveBeenCalledWith("key");
});
it("flush writes the pending value immediately", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
expect(base.setItem).not.toHaveBeenCalled();
storage.flush();
expect(base.setItem).toHaveBeenCalledWith("key", "v1");
// Timer should be cancelled; no duplicate write.
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
});
it("flush is a no-op when nothing is pending", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.flush();
expect(base.setItem).not.toHaveBeenCalled();
});
it("flush after removeItem is a no-op", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.removeItem("key");
storage.flush();
expect(base.setItem).not.toHaveBeenCalled();
});
it("setItem works normally after removeItem cancels a pending write", () => {
const base = createMockStorage();
const storage = createDebouncedStorage(base);
storage.setItem("key", "v1");
storage.removeItem("key");
storage.setItem("key", "v2");
vi.advanceTimersByTime(300);
expect(base.setItem).toHaveBeenCalledTimes(1);
expect(base.setItem).toHaveBeenCalledWith("key", "v2");
});
});
+44 -2
View File
@@ -14,12 +14,54 @@ import {
DEFAULT_RUNTIME_MODE,
type ChatImageAttachment,
} from "./types";
import { Debouncer } from "@tanstack/react-pacer";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
export type DraftThreadEnvMode = "local" | "worktree";
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
interface DebouncedStorage extends StateStorage {
flush: () => void;
}
export function createDebouncedStorage(baseStorage: StateStorage): DebouncedStorage {
const debouncedSetItem = new Debouncer(
(name: string, value: string) => {
baseStorage.setItem(name, value);
},
{ wait: COMPOSER_PERSIST_DEBOUNCE_MS },
);
return {
getItem: (name) => baseStorage.getItem(name),
setItem: (name, value) => {
debouncedSetItem.maybeExecute(name, value);
},
removeItem: (name) => {
debouncedSetItem.cancel();
baseStorage.removeItem(name);
},
flush: () => {
debouncedSetItem.flush();
},
};
}
const composerDebouncedStorage: DebouncedStorage =
typeof localStorage !== "undefined"
? createDebouncedStorage(localStorage)
: { getItem: () => null, setItem: () => {}, removeItem: () => {}, flush: () => {} };
// Flush pending composer draft writes before page unload to prevent data loss.
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
composerDebouncedStorage.flush();
});
}
export interface PersistedComposerImageAttachment {
id: string;
name: string;
@@ -1169,7 +1211,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
{
name: COMPOSER_DRAFT_STORAGE_KEY,
version: 1,
storage: createJSONStorage(() => localStorage),
storage: createJSONStorage(() => composerDebouncedStorage),
partialize: (state) => {
const persistedDraftsByThreadId: PersistedComposerDraftStoreState["draftsByThreadId"] = {};
for (const [threadId, draft] of Object.entries(state.draftsByThreadId)) {
+20 -3
View File
@@ -8,6 +8,7 @@ import {
} from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { Throttler } from "@tanstack/react-pacer";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
@@ -150,6 +151,7 @@ function EventRouter() {
let latestSequence = 0;
let syncing = false;
let pending = false;
let needsProviderInvalidation = false;
const flushSnapshotSync = async (): Promise<void> => {
const snapshot = await api.orchestration.getSnapshot();
@@ -185,7 +187,20 @@ function EventRouter() {
syncing = false;
};
void syncSnapshot().catch(() => undefined);
const domainEventFlushThrottler = new Throttler(
() => {
if (needsProviderInvalidation) {
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
}
void syncSnapshot();
},
{
wait: 100,
leading: false,
trailing: true,
},
);
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
if (event.sequence <= latestSequence) {
@@ -193,9 +208,9 @@ function EventRouter() {
}
latestSequence = event.sequence;
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
needsProviderInvalidation = true;
}
void syncSnapshot();
domainEventFlushThrottler.maybeExecute();
});
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
@@ -280,6 +295,8 @@ function EventRouter() {
});
return () => {
disposed = true;
needsProviderInvalidation = false;
domainEventFlushThrottler.cancel();
unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome();
+18 -4
View File
@@ -14,6 +14,7 @@ import {
} from "@t3tools/shared/model";
import { create } from "zustand";
import { type ChatMessage, type Project, type Thread } from "./types";
import { Debouncer } from "@tanstack/react-pacer";
// ── State ────────────────────────────────────────────────────────────
@@ -62,6 +63,8 @@ function readPersistedState(): AppState {
}
}
let legacyKeysCleanedUp = false;
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
@@ -73,13 +76,17 @@ function persistState(state: AppState): void {
.map((project) => project.cwd),
}),
);
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
if (!legacyKeysCleanedUp) {
legacyKeysCleanedUp = true;
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
// ── Pure helpers ──────────────────────────────────────────────────────
@@ -394,8 +401,15 @@ export const useStore = create<AppStore>((set) => ({
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
}));
// Persist on every state change
useStore.subscribe((state) => persistState(state));
// Persist state changes with debouncing to avoid localStorage thrashing
useStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
// Flush pending writes synchronously before page unload to prevent data loss.
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
debouncedPersistState.flush();
});
}
export function StoreProvider({ children }: { children: ReactNode }) {
useEffect(() => {