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
23 changed files with 324 additions and 577 deletions

No files matched your search

-2
View File
@@ -132,7 +132,6 @@ const buildCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
shell: process.platform === "win32",
})`bun tsdown`,
);
@@ -226,7 +225,6 @@ const publishCmd = Command.make(
cwd: serverDir,
stdout: config.verbose ? "inherit" : "ignore",
stderr: "inherit",
shell: process.platform === "win32",
}),
);
}),
@@ -103,7 +103,6 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd),
readRangeContext: (cwd, baseBranch) => core.readRangeContext(cwd, baseBranch),
readConfigValue: (cwd, key) => core.readConfigValue(cwd, key),
readRemoteUrl: (cwd, remoteName) => core.readRemoteUrl(cwd, remoteName),
listBranches: (input) => core.listBranches(input),
createWorktree: (input) => core.createWorktree(input),
removeWorktree: (input) => core.removeWorktree(input),
-7
View File
@@ -826,12 +826,6 @@ const makeGitCore = Effect.gen(function* () {
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
);
const readRemoteUrl: GitCoreShape["readRemoteUrl"] = (cwd, remoteName) =>
runGitStdout("GitCore.readRemoteUrl", cwd, ["remote", "get-url", remoteName], true).pipe(
Effect.map((stdout) => stdout.trim()),
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
);
const listBranches: GitCoreShape["listBranches"] = (input) =>
Effect.gen(function* () {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
@@ -1201,7 +1195,6 @@ const makeGitCore = Effect.gen(function* () {
pullCurrentBranch,
readRangeContext,
readConfigValue,
readRemoteUrl,
listBranches,
createWorktree,
removeWorktree,
+33 -96
View File
@@ -23,7 +23,6 @@ interface FakeGhScenario {
prListSequence?: string[];
createdPrUrl?: string;
defaultBranch?: string;
repoNameWithOwner?: string;
failWith?: GitHubCliError;
}
@@ -166,35 +165,6 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
};
}
function ghPr(
overrides: Partial<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
headRepository: { name: string };
headRepositoryOwner: { login: string };
state: "OPEN" | "CLOSED" | "MERGED";
mergedAt: string | null;
updatedAt: string | null;
}> = {},
) {
return {
number: 1,
title: "PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/1",
baseRefName: "main",
headRefName: "feature/test",
headRepository: { name: "codething-mvp" },
headRepositoryOwner: { login: "pingdotgg" },
state: "OPEN" as const,
updatedAt: "2026-02-01T10:00:00Z",
...overrides,
...(overrides.mergedAt !== undefined ? { mergedAt: overrides.mergedAt } : {}),
};
}
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
service: GitHubCliShape;
ghCalls: string[];
@@ -243,17 +213,6 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
}
if (args[0] === "repo" && args[1] === "view") {
const jqExpression = args[args.indexOf("--jq") + 1];
if (jqExpression === ".nameWithOwner") {
return Effect.succeed({
stdout: `${scenario.repoNameWithOwner ?? "pingdotgg/codething-mvp"}\n`,
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
}
return Effect.succeed({
stdout: `${scenario.defaultBranch ?? "main"}\n`,
stderr: "",
@@ -378,12 +337,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
JSON.stringify([
ghPr({
{
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseRefName: "main",
headRefName: "feature/status-open-pr",
}),
},
]),
],
},
@@ -402,35 +362,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status ignores fork PRs that only match by branch name", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
ghPr({
number: 99,
title: "Fork main PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/99",
headRefName: "main",
headRepositoryOwner: { login: "random-user" },
headRepository: { name: "t3code" },
}),
]),
],
repoNameWithOwner: "pingdotgg/t3code",
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("main");
expect(status.pr).toBeNull();
}),
);
it.effect("status returns merged PR state when latest PR was merged", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -441,15 +372,16 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
JSON.stringify([
ghPr({
{
number: 22,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
baseRefName: "main",
headRefName: "feature/status-merged-pr",
state: "MERGED",
mergedAt: "2026-01-30T10:00:00Z",
updatedAt: "2026-01-30T10:00:00Z",
}),
},
]),
],
},
@@ -478,23 +410,25 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
JSON.stringify([
ghPr({
{
number: 45,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
baseRefName: "main",
headRefName: "feature/status-open-over-merged",
state: "MERGED",
mergedAt: "2026-01-31T10:00:00Z",
updatedAt: "2026-02-01T10:00:00Z",
}),
ghPr({
},
{
number: 46,
title: "Open PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
baseRefName: "main",
headRefName: "feature/status-open-over-merged",
state: "OPEN",
updatedAt: "2026-01-30T10:00:00Z",
}),
},
]),
],
},
@@ -775,20 +709,21 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
ghPr({
number: 77,
title: "Add no-upstream PR flow",
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
headRefName: "feature/no-upstream-pr",
}),
]),
],
},
});
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 77,
title: "Add no-upstream PR flow",
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
baseRefName: "main",
headRefName: "feature/no-upstream-pr",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
@@ -847,12 +782,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
JSON.stringify([
ghPr({
{
number: 42,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/existing-pr",
}),
},
]),
],
},
@@ -887,12 +823,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
prListSequence: [
"[]",
JSON.stringify([
ghPr({
{
number: 88,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/88",
baseRefName: "main",
headRefName: "feature-create-pr",
}),
},
]),
],
},
+43 -145
View File
@@ -1,12 +1,7 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Path } from "effect";
import {
parseGitHubRepositoryFromRemoteUrl,
resolveAutoFeatureBranchName,
sanitizeFeatureBranchName,
type GitHubRepositoryIdentity,
} from "@t3tools/shared/git";
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
@@ -23,34 +18,10 @@ interface OpenPrInfo {
}
interface PullRequestInfo extends OpenPrInfo {
headRepositoryOwner: string | null;
headRepositoryName: string | null;
state: "open" | "closed" | "merged";
updatedAt: string | null;
}
function normalizeOptionalString(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function parsePullRequestHeadRepositoryOwner(value: unknown): string | null {
if (!value || typeof value !== "object") {
return normalizeOptionalString(value);
}
return normalizeOptionalString((value as Record<string, unknown>).login);
}
function parsePullRequestHeadRepositoryName(value: unknown): string | null {
if (!value || typeof value !== "object") {
return null;
}
return normalizeOptionalString((value as Record<string, unknown>).name);
}
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
if (!Array.isArray(raw)) return [];
@@ -63,8 +34,6 @@ function parsePullRequestList(raw: unknown): PullRequestInfo[] {
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
const headRepositoryOwner = parsePullRequestHeadRepositoryOwner(record.headRepositoryOwner);
const headRepositoryName = parsePullRequestHeadRepositoryName(record.headRepository);
const state = record.state;
const mergedAt = record.mergedAt;
const updatedAt = record.updatedAt;
@@ -97,8 +66,6 @@ function parsePullRequestList(raw: unknown): PullRequestInfo[] {
url,
baseRefName,
headRefName,
headRepositoryOwner,
headRepositoryName,
state: normalizedState,
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
});
@@ -190,49 +157,6 @@ function extractBranchFromRef(ref: string): string {
return normalized.slice(firstSlash + 1).trim();
}
function extractRemoteNameFromUpstreamRef(upstreamRef: string): string | null {
const trimmed = upstreamRef.trim();
const separatorIndex = trimmed.indexOf("/");
if (separatorIndex <= 0) {
return null;
}
const remoteName = trimmed.slice(0, separatorIndex).trim();
return remoteName.length > 0 ? remoteName : null;
}
function parseGitHubRepositoryIdentity(raw: string): GitHubRepositoryIdentity | null {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return null;
}
const [owner, name, ...rest] = trimmed.split("/").map((segment) => segment.trim());
if (!owner || !name || rest.length > 0) {
return null;
}
return { owner, name };
}
function matchesPullRequestHeadRepository(
pr: PullRequestInfo,
branch: string,
repository: GitHubRepositoryIdentity,
): boolean {
return (
pr.headRefName === branch &&
pr.headRepositoryOwner?.toLowerCase() === repository.owner.toLowerCase() &&
pr.headRepositoryName?.toLowerCase() === repository.name.toLowerCase()
);
}
function comparePullRequestsByUpdatedAt(a: PullRequestInfo, b: PullRequestInfo): number {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
}
function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
@@ -260,48 +184,33 @@ export const makeGitManager = Effect.gen(function* () {
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const resolveCurrentHeadRepository = (cwd: string, upstreamRef: string | null) =>
Effect.gen(function* () {
if (upstreamRef) {
const remoteName = extractRemoteNameFromUpstreamRef(upstreamRef);
if (remoteName) {
const remoteUrl = yield* gitCore
.readRemoteUrl(cwd, remoteName)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (remoteUrl) {
const parsedRemote = parseGitHubRepositoryFromRemoteUrl(remoteUrl);
if (parsedRemote) {
return parsedRemote;
}
const findOpenPr = (cwd: string, branch: string) =>
gitHubCli
.listOpenPullRequests({
cwd,
headBranch: branch,
limit: 1,
})
.pipe(
Effect.map((prs) => {
const [first] = prs;
if (!first) {
return null;
}
}
}
return {
number: first.number,
title: first.title,
url: first.url,
baseRefName: first.baseRefName,
headRefName: first.headRefName,
state: "open",
updatedAt: null,
} satisfies PullRequestInfo;
}),
);
const repoNameWithOwner = yield* gitHubCli
.execute({
cwd,
args: ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"],
})
.pipe(
Effect.map((result) => result.stdout.trim()),
Effect.catch(() => Effect.succeed("")),
);
return parseGitHubRepositoryIdentity(repoNameWithOwner);
});
const findMatchingPrs = (
cwd: string,
branch: string,
upstreamRef: string | null,
state: "open" | "all",
) =>
const findLatestPr = (cwd: string, branch: string) =>
Effect.gen(function* () {
const currentHeadRepository = yield* resolveCurrentHeadRepository(cwd, upstreamRef);
if (!currentHeadRepository) {
return [] as PullRequestInfo[];
}
const stdout = yield* gitHubCli
.execute({
cwd,
@@ -311,50 +220,39 @@ export const makeGitManager = Effect.gen(function* () {
"--head",
branch,
"--state",
state,
"all",
"--limit",
"20",
"--json",
"number,title,url,baseRefName,headRefName,headRepository,headRepositoryOwner,state,mergedAt,updatedAt",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
],
})
.pipe(Effect.map((result) => result.stdout));
const raw = stdout.trim();
if (raw.length === 0) {
return [] as PullRequestInfo[];
return null;
}
const parsedJson = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) =>
gitManagerError("findMatchingPrs", "GitHub CLI returned invalid PR list JSON.", cause),
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
});
return parsePullRequestList(parsedJson)
.filter((pr) => matchesPullRequestHeadRepository(pr, branch, currentHeadRepository))
.toSorted(comparePullRequestsByUpdatedAt);
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
});
const latestOpenPr = parsed.find((pr) => pr.state === "open");
if (latestOpenPr) {
return latestOpenPr;
}
return parsed[0] ?? null;
});
const findOpenPr = (cwd: string, branch: string, upstreamRef: string | null) =>
findMatchingPrs(cwd, branch, upstreamRef, "open").pipe(
Effect.map((prs) => {
const [first] = prs;
return first ?? null;
}),
);
const findLatestPr = (cwd: string, branch: string, upstreamRef: string | null) =>
findMatchingPrs(cwd, branch, upstreamRef, "all").pipe(
Effect.map((parsed) => {
const latestOpenPr = parsed.find((pr) => pr.state === "open");
if (latestOpenPr) {
return latestOpenPr;
}
return parsed[0] ?? null;
}),
);
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
Effect.gen(function* () {
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
@@ -463,7 +361,7 @@ export const makeGitManager = Effect.gen(function* () {
);
}
const existing = yield* findOpenPr(cwd, branch, details.upstreamRef);
const existing = yield* findOpenPr(cwd, branch);
if (existing) {
return {
status: "opened_existing" as const,
@@ -505,7 +403,7 @@ export const makeGitManager = Effect.gen(function* () {
})
.pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
const created = yield* findOpenPr(cwd, branch, details.upstreamRef);
const created = yield* findOpenPr(cwd, branch);
if (!created) {
return {
status: "created" as const,
@@ -530,7 +428,7 @@ export const makeGitManager = Effect.gen(function* () {
const pr =
details.branch !== null
? yield* findLatestPr(input.cwd, details.branch, details.upstreamRef).pipe(
? yield* findLatestPr(input.cwd, details.branch).pipe(
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
Effect.catch(() => Effect.succeed(null)),
)
-8
View File
@@ -110,14 +110,6 @@ export interface GitCoreShape {
key: string,
) => Effect.Effect<string | null, GitCommandError>;
/**
* Read a configured remote URL from the local repository.
*/
readonly readRemoteUrl: (
cwd: string,
remoteName: string,
) => Effect.Effect<string | null, GitCommandError>;
/**
* List local + remote branches and branch metadata.
*/
@@ -6,7 +6,6 @@ import {
type ProviderModelOptions,
type ProviderKind,
type ProviderServiceTier,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
type ProviderSession,
@@ -145,8 +144,6 @@ const make = Effect.gen(function* () {
),
);
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
readonly kind:
@@ -206,7 +203,6 @@ const make = Effect.gen(function* () {
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly serviceTier?: ProviderServiceTier | null;
readonly providerOptions?: ProviderStartOptions;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -243,7 +239,6 @@ const make = Effect.gen(function* () {
...(desiredModel ? { model: desiredModel } : {}),
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(options?.providerOptions !== undefined ? { providerOptions: options.providerOptions } : {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
@@ -330,7 +325,6 @@ const make = Effect.gen(function* () {
readonly model?: string;
readonly serviceTier?: ProviderServiceTier | null;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly interactionMode?: "default" | "plan";
readonly createdAt: string;
}) {
@@ -338,15 +332,11 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
@@ -482,7 +472,6 @@ const make = Effect.gen(function* () {
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.serviceTier !== undefined ? { serviceTier: event.payload.serviceTier } : {}),
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
...(event.payload.providerOptions !== undefined ? { providerOptions: event.payload.providerOptions } : {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
});
@@ -638,10 +627,7 @@ const make = Effect.gen(function* () {
if (!thread?.session || thread.session.status === "stopped") {
return;
}
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined ? { providerOptions: cachedProviderOptions } : {}),
});
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt);
return;
}
case "thread.turn-start-requested":
-1
View File
@@ -303,7 +303,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.model !== undefined ? { model: command.model } : {}),
...(command.serviceTier !== undefined ? { serviceTier: command.serviceTier } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
@@ -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;
}),
);
@@ -86,30 +86,15 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
}
}
function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: { readonly providerOptions?: unknown },
): Record<string, unknown> {
function toRuntimePayloadFromSession(session: ProviderSession): Record<string, unknown> {
return {
cwd: session.cwd ?? null,
model: session.model ?? null,
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
};
}
function readPersistedProviderOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "providerOptions" in runtimePayload ? runtimePayload.providerOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
}
function readPersistedCwd(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): string | undefined {
@@ -152,7 +137,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: { readonly providerOptions?: unknown },
) =>
directory.upsert({
threadId,
@@ -160,7 +144,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
runtimeMode: session.runtimeMode,
status: toRuntimeStatus(session),
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
runtimePayload: toRuntimePayloadFromSession(session, extra),
runtimePayload: toRuntimePayloadFromSession(session),
});
const providers = yield* registry.listProviders();
@@ -213,13 +197,11 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
@@ -291,9 +273,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
);
}
yield* upsertSessionBinding(session, threadId, {
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
yield* upsertSessionBinding(session, threadId);
yield* analytics.record("provider.session.started", {
provider: session.provider,
runtimeMode: input.runtimeMode,
+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,
};
@@ -2,11 +2,9 @@ import type { GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
getEnvModeButtonLabel,
deriveLocalBranchNameFromRemoteRef,
resolveDraftEnvModeAfterBranchChange,
resolveBranchToolbarValue,
resolveEnvToggleAction,
} from "./BranchToolbar.logic";
describe("resolveDraftEnvModeAfterBranchChange", () => {
@@ -76,71 +74,6 @@ describe("resolveBranchToolbarValue", () => {
});
});
describe("resolveEnvToggleAction", () => {
it("allows detaching an inherited worktree before the thread is locked", () => {
expect(
resolveEnvToggleAction({
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
effectiveEnvMode: "worktree",
envLocked: false,
}),
).toBe("detach-worktree");
});
it("keeps the toggle locked once the thread environment is immutable", () => {
expect(
resolveEnvToggleAction({
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
effectiveEnvMode: "worktree",
envLocked: true,
}),
).toBe("locked");
});
it("switches between local and new-worktree modes when no worktree is attached", () => {
expect(
resolveEnvToggleAction({
activeWorktreePath: null,
effectiveEnvMode: "local",
envLocked: false,
}),
).toBe("set-worktree");
expect(
resolveEnvToggleAction({
activeWorktreePath: null,
effectiveEnvMode: "worktree",
envLocked: false,
}),
).toBe("set-local");
});
});
describe("getEnvModeButtonLabel", () => {
it("shows the attached worktree label when a worktree is already bound", () => {
expect(
getEnvModeButtonLabel({
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
effectiveEnvMode: "worktree",
}),
).toBe("Worktree");
});
it("distinguishes between local mode and pending new-worktree mode", () => {
expect(
getEnvModeButtonLabel({
activeWorktreePath: null,
effectiveEnvMode: "local",
}),
).toBe("Local");
expect(
getEnvModeButtonLabel({
activeWorktreePath: null,
effectiveEnvMode: "worktree",
}),
).toBe("New worktree");
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
@@ -1,7 +1,6 @@
import type { GitBranch } from "@t3tools/contracts";
export type EnvMode = "local" | "worktree";
export type EnvToggleAction = "locked" | "set-worktree" | "set-local" | "detach-worktree";
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
@@ -29,32 +28,6 @@ export function resolveDraftEnvModeAfterBranchChange(input: {
return "local";
}
export function resolveEnvToggleAction(input: {
activeWorktreePath: string | null;
effectiveEnvMode: EnvMode;
envLocked: boolean;
}): EnvToggleAction {
const { activeWorktreePath, effectiveEnvMode, envLocked } = input;
if (envLocked) {
return "locked";
}
if (activeWorktreePath) {
return "detach-worktree";
}
return effectiveEnvMode === "worktree" ? "set-local" : "set-worktree";
}
export function getEnvModeButtonLabel(input: {
activeWorktreePath: string | null;
effectiveEnvMode: EnvMode;
}): string {
const { activeWorktreePath, effectiveEnvMode } = input;
if (activeWorktreePath) {
return "Worktree";
}
return effectiveEnvMode === "worktree" ? "New worktree" : "Local";
}
export function resolveBranchToolbarValue(input: {
envMode: EnvMode;
activeWorktreePath: string | null;
+3 -26
View File
@@ -7,10 +7,8 @@ import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import {
EnvMode,
getEnvModeButtonLabel,
resolveDraftEnvModeAfterBranchChange,
resolveEffectiveEnvMode,
resolveEnvToggleAction,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { Button } from "./ui/button";
@@ -47,11 +45,6 @@ export default function BranchToolbar({
hasServerThread,
draftThreadEnvMode: draftThread?.envMode,
});
const envToggleAction = resolveEnvToggleAction({
activeWorktreePath,
effectiveEnvMode,
envLocked,
});
const setThreadBranch = useCallback(
(branch: string | null, worktreePath: string | null) => {
@@ -105,25 +98,12 @@ export default function BranchToolbar({
],
);
const handleEnvToggle = useCallback(() => {
if (envToggleAction === "locked") {
return;
}
if (envToggleAction === "detach-worktree") {
setThreadBranch(null, null);
onComposerFocusRequest?.();
return;
}
onEnvModeChange(envToggleAction === "set-worktree" ? "worktree" : "local");
onComposerFocusRequest?.();
}, [envToggleAction, onComposerFocusRequest, onEnvModeChange, setThreadBranch]);
if (!activeThreadId || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
<div className="flex items-center gap-2">
{envToggleAction === "locked" ? (
{envLocked || activeWorktreePath ? (
<span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeWorktreePath ? "Worktree" : "Local"}
</span>
@@ -133,12 +113,9 @@ export default function BranchToolbar({
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
onClick={handleEnvToggle}
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
>
{getEnvModeButtonLabel({
activeWorktreePath,
effectiveEnvMode,
})}
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
</Button>
)}
</div>
@@ -409,16 +409,6 @@ async function waitForInteractionModeButton(expectedLabel: "Chat" | "Plan"): Pro
);
}
async function waitForEnvModeButton(expectedLabel: "Local" | "Worktree" | "New worktree") {
return waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.textContent?.trim() === expectedLabel,
) as HTMLButtonElement | null,
`Unable to find ${expectedLabel} environment mode button.`,
);
}
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
const images = Array.from(scope.querySelectorAll("img"));
if (images.length === 0) {
@@ -813,51 +803,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("lets a new draft thread detach an inherited worktree before the first message", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/demo",
worktreePath: "/repo/project/.t3/worktrees/feature-demo",
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createDraftOnlySnapshot(),
});
try {
const worktreeButton = await waitForEnvModeButton("Worktree");
worktreeButton.click();
await vi.waitFor(
() => {
const draftThread = useComposerDraftStore.getState().getDraftThread(THREAD_ID);
expect(draftThread).toMatchObject({
branch: null,
worktreePath: null,
envMode: "local",
});
},
{ timeout: 8_000, interval: 16 },
);
await waitForEnvModeButton("Local");
} finally {
await mounted.cleanup();
}
});
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
+4 -26
View File
@@ -830,17 +830,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
return Object.keys(codexOptions).length > 0 ? { codex: codexOptions } : undefined;
}, [selectedCodexFastModeEnabled, selectedEffort, selectedProvider, supportsReasoningEffort]);
const providerOptionsForDispatch = useMemo(() => {
if (!settings.codexBinaryPath && !settings.codexHomePath) {
return undefined;
}
return {
codex: {
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
},
};
}, [settings.codexBinaryPath, settings.codexHomePath]);
const selectedModelForPicker = selectedModel;
const modelOptionsByProvider = useMemo(
() => getCustomModelOptionsByProvider(settings),
@@ -2637,9 +2626,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
...(selectedModelOptionsForDispatch
? { modelOptions: selectedModelOptionsForDispatch }
: {}),
...(providerOptionsForDispatch
? { providerOptions: providerOptionsForDispatch }
: {}),
provider: selectedProvider,
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
runtimeMode,
@@ -2917,9 +2903,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
...(selectedModelOptionsForDispatch
? { modelOptions: selectedModelOptionsForDispatch }
: {}),
...(providerOptionsForDispatch
? { providerOptions: providerOptionsForDispatch }
: {}),
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
runtimeMode,
interactionMode: nextInteractionMode,
@@ -2950,7 +2933,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
runtimeMode,
selectedModel,
selectedModelOptionsForDispatch,
providerOptionsForDispatch,
selectedProvider,
setComposerDraftInteractionMode,
setThreadError,
@@ -3005,8 +2987,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: activeThread.worktreePath,
createdAt,
})
.then(() => {
return api.orchestration.dispatchCommand({
.then(() =>
api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: nextThreadId,
@@ -3021,15 +3003,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
...(selectedModelOptionsForDispatch
? { modelOptions: selectedModelOptionsForDispatch }
: {}),
...(providerOptionsForDispatch
? { providerOptions: providerOptionsForDispatch }
: {}),
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
runtimeMode,
interactionMode: "default",
createdAt,
});
})
}),
)
.then(() => api.orchestration.getSnapshot())
.then((snapshot) => {
syncServerReadModel(snapshot);
@@ -3073,7 +3052,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
runtimeMode,
selectedModel,
selectedModelOptionsForDispatch,
providerOptionsForDispatch,
selectedProvider,
settings.enableAssistantStreaming,
syncServerReadModel,
+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(() => {
-10
View File
@@ -45,13 +45,6 @@ export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
export const ProviderServiceTier = Schema.Literals(["fast", "flex"]);
export type ProviderServiceTier = typeof ProviderServiceTier.Type;
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
const CodexProviderStartOptions = Schema.Struct({
binaryPath: Schema.optional(TrimmedNonEmptyString),
homePath: Schema.optional(TrimmedNonEmptyString),
});
const ProviderStartOptions = Schema.Struct({
codex: Schema.optional(CodexProviderStartOptions),
});
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
export type RuntimeMode = typeof RuntimeMode.Type;
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
@@ -373,7 +366,6 @@ export const ThreadTurnStartCommand = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
@@ -396,7 +388,6 @@ const ClientThreadTurnStartCommand = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
@@ -677,7 +668,6 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
model: Schema.optional(TrimmedNonEmptyString),
serviceTier: Schema.optional(Schema.NullOr(ProviderServiceTier)),
modelOptions: Schema.optional(ProviderModelOptions),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
+1 -2
View File
@@ -53,10 +53,9 @@ const CodexProviderStartOptions = Schema.Struct({
homePath: Schema.optional(TrimmedNonEmptyStringSchema),
});
export const ProviderStartOptions = Schema.Struct({
const ProviderStartOptions = Schema.Struct({
codex: Schema.optional(CodexProviderStartOptions),
});
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
export const ProviderSessionStartInput = Schema.Struct({
threadId: ThreadId,
-49
View File
@@ -59,52 +59,3 @@ export function resolveAutoFeatureBranchName(
return `${resolvedBase}-${suffix}`;
}
export interface GitHubRepositoryIdentity {
owner: string;
name: string;
}
/**
* Parse a GitHub-style remote URL into `{ owner, name }`.
* Supports SSH scp syntax and URL-based remotes.
*/
export function parseGitHubRepositoryFromRemoteUrl(
remoteUrl: string,
): GitHubRepositoryIdentity | null {
const trimmed = remoteUrl.trim();
if (trimmed.length === 0) {
return null;
}
const scpMatch = trimmed.match(/^[^@]+@[^:]+:(.+)$/);
const rawPath = scpMatch?.[1] ?? (() => {
try {
return new URL(trimmed).pathname;
} catch {
return null;
}
})();
if (!rawPath) {
return null;
}
const segments = rawPath
.replace(/^\/+|\/+$/g, "")
.replace(/\.git$/i, "")
.split("/")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (segments.length !== 2) {
return null;
}
const owner = segments[0];
const name = segments[1];
if (!owner || !name) {
return null;
}
return { owner, name };
}