Compare commits

..
Author SHA1 Message Date
Julius Marminge 4a42ee1ad0 fix(vcs): preserve branch PR state across checkout changes
- Reconcile VCS refreshes after mid-refresh checkouts
- Use branch-keyed PR lookups for thread indicators
- Keep git actions tied to the active checkout
2026-08-05 16:17:58 +02:00
Julius Marminge c7b1e2e6c4 feat(vcs): preserve branch PR status across checkouts
- Add branch-keyed PR lookup RPC and client query
- Serialize VCS refreshes to prevent stale status races
2026-08-05 15:18:06 +02:00
36 changed files with 719 additions and 622 deletions

No files matched your search

@@ -1,10 +1,6 @@
name: Mobile Showcase Screenshots
on:
push:
branches:
- t3bot/mobile-pending-card-glass
- t3bot/mobile-pending-card-glass-before
workflow_dispatch:
inputs:
platform:
@@ -35,7 +31,7 @@ env:
jobs:
ios:
name: iPhone 6.9, iPhone 6.5, and iPad 13
if: github.event_name == 'push' || inputs.platform == 'all' || inputs.platform == 'ios'
if: inputs.platform == 'all' || inputs.platform == 'ios'
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 60
steps:
@@ -66,10 +62,10 @@ jobs:
"$vp_pnpm_bin/pnpm" --version
- name: Capture iOS showcase
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance || 'dark' }}"
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
- name: Validate App Store Connect assets
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance || 'dark' }}" --validate-only
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload iOS screenshots
if: always()
@@ -1,11 +1,4 @@
import {
Platform,
ScrollView,
type StyleProp,
type TextStyle,
View,
useColorScheme,
} from "react-native";
import { Platform, ScrollView, View, useColorScheme } from "react-native";
import { AppText as Text } from "../../../../components/AppText";
import {
@@ -61,48 +54,14 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
fontSize: props.fontSize,
lineHeight,
} as const;
// AppText stamps the sans font on every node, so nested spans must
// re-apply the terminal font instead of relying on inheritance, exactly
// like the code preview's tokens below.
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
lineStyle,
{ color, ...extra },
];
return (
<View className="p-4">
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.palette[6])}>t3code </Text>
<Text style={span(theme.palette[4])}>git:(</Text>
<Text style={span(theme.palette[1])}>main</Text>
<Text style={span(theme.palette[4])}>)</Text>
<Text style={span(theme.palette[3])}> ✗</Text>
<Text style={span(theme.foreground)}> vpr dev</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
<Text style={span(theme.mutedForeground)}> ready in</Text>
<Text style={span(theme.foreground)}> 1.24s</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.mutedForeground)}>Local: </Text>
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
http://127.0.0.1:5173/
</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
{" READY "}
</Text>
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
<Text style={span(theme.cursorForeground)}>▏</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>
Local: http://localhost:3000{" "}
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
</Text>
</View>
);
@@ -3,7 +3,6 @@ import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import type { PendingApproval } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
@@ -16,7 +15,7 @@ export interface PendingApprovalCardProps {
export function PendingApprovalCard(props: PendingApprovalCardProps) {
return (
<PendingCardSurface>
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
@@ -53,6 +52,6 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
</Pressable>
</View>
</PendingCardSurface>
</View>
);
}
@@ -1,35 +0,0 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ReactNode } from "react";
import { useColorScheme, View, type ViewStyle } from "react-native";
const SURFACE_STYLE: ViewStyle = {
borderRadius: 20,
overflow: "hidden",
};
export function PendingCardSurface(props: { readonly children: ReactNode }) {
const isDarkMode = useColorScheme() === "dark";
const content = <View className="gap-2.5 p-4">{props.children}</View>;
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="regular"
interactive
colorScheme={isDarkMode ? "dark" : "light"}
style={SURFACE_STYLE}
>
{content}
</LiquidGlassView>
);
}
return (
<View
className="rounded-[20px] border border-neutral-200 bg-neutral-100 dark:border-white/6 dark:bg-neutral-900"
style={SURFACE_STYLE}
>
{content}
</View>
);
}
@@ -4,7 +4,6 @@ import { Pressable, View } from "react-native";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
@@ -26,7 +25,7 @@ export interface PendingUserInputCardProps {
export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<PendingCardSurface>
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
@@ -101,6 +100,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</PendingCardSurface>
</View>
);
}
+21 -5
View File
@@ -15,6 +15,10 @@ export {
* (environmentId, cwd) by the atom family, so many rows on the same worktree
* or project root share one stream — and virtualization means only visible
* rows subscribe at all.
*
* Keyed by the thread's recorded branch, not the current checkout: the
* streamed status is the fast path while the checkout matches, and a
* branch-keyed lookup keeps the badge alive once the checkout moves away.
*/
export function useThreadPr(
thread: EnvironmentThreadShell,
@@ -29,13 +33,25 @@ export function useThreadPr(
})
: null,
);
const branchPr = useEnvironmentQuery(
thread.branch !== null && cwd !== null
? vcsEnvironment.branchPr({
environmentId: thread.environmentId,
input: { cwd, branch: thread.branch },
})
: null,
);
const status = gitStatus.data;
if (status === null || thread.branch === null || status.refName !== thread.branch) {
// When the status describes the thread's own branch it is authoritative
// about that branch's PR — including when it reports none, so this must not
// fall through to a warm branch lookup that would resurrect a stale badge.
if (status !== null && thread.branch !== null && status.refName === thread.branch) {
return status.pr ? presentThreadPr(status.pr, status.sourceControlProvider) : null;
}
const pr = branchPr.data?.pr;
if (!pr) {
return null;
}
if (!status.pr) {
return null;
}
return presentThreadPr(status.pr, status.sourceControlProvider);
return presentThreadPr(pr, status?.sourceControlProvider);
}
+1
View File
@@ -64,6 +64,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
[WS_METHODS.vcsBranchPr]: AuthOrchestrationReadScope,
[WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,
[WS_METHODS.gitRunStackedAction]: AuthOrchestrationOperateScope,
[WS_METHODS.gitResolvePullRequest]: AuthOrchestrationOperateScope,
+43
View File
@@ -23,6 +23,8 @@ import {
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
type VcsBranchPrInput,
type VcsBranchPrResult,
VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
@@ -87,6 +89,9 @@ export class GitManager extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly branchPr: (
input: VcsBranchPrInput,
) => Effect.Effect<VcsBranchPrResult, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -1684,6 +1689,43 @@ export const make = Effect.gen(function* () {
});
return mergeGitStatusParts(local, remote);
});
// PR lookup for a branch that is not necessarily checked out. Threads keep
// a recorded branch, and their PR badge must survive the checkout moving
// elsewhere — so this derives the branch's upstream from git config instead
// of HEAD and funnels into the same cached lookup as status.
const branchPr: GitManager["Service"]["branchPr"] = Effect.fn("branchPr")(function* (input) {
const cwd = yield* normalizeStatusCacheKey(input.cwd);
const branch = input.branch;
const [remoteName, mergeRef, originHead] = yield* Effect.all(
[
readConfigValueNullable(cwd, `branch.${branch}.remote`),
readConfigValueNullable(cwd, `branch.${branch}.merge`),
gitCore
.execute({
operation: "GitManager.branchPr.defaultBranch",
cwd,
args: ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.orElseSucceed(() => null)),
],
{ concurrency: "unbounded" },
);
const upstreamRef =
remoteName !== null && mergeRef !== null && mergeRef.startsWith("refs/heads/")
? `${remoteName}/${mergeRef.slice("refs/heads/".length)}`
: null;
const originHeadBranch =
originHead !== null && originHead.exitCode === 0
? (originHead.stdout.trim().split("/").slice(1).join("/") ?? "")
: "";
const isDefaultBranch =
originHeadBranch.length > 0
? branch === originHeadBranch
: branch === "main" || branch === "master";
const pr = yield* lookupStatusPr(cwd, { branch, upstreamRef, isDefaultBranch });
return { branch, pr } satisfies VcsBranchPrResult;
});
const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
"invalidateLocalStatus",
)(function* (cwd) {
@@ -2136,6 +2178,7 @@ export const make = Effect.gen(function* () {
return GitManager.of({
localStatus,
remoteStatus,
branchPr,
status,
invalidateLocalStatus,
invalidateRemoteStatus,
+13
View File
@@ -22,6 +22,8 @@ import {
type GitResolvePullRequestResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type VcsBranchPrInput,
type VcsBranchPrResult,
type VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
@@ -45,6 +47,9 @@ export class GitWorkflowService extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly branchPr: (
input: VcsBranchPrInput,
) => Effect.Effect<VcsBranchPrResult, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -270,6 +275,14 @@ export const make = Effect.gen(function* () {
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
),
),
branchPr: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.branchPr", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository
? gitManager.branchPr(input)
: Effect.succeed({ branch: input.branch, pr: null }),
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
+2 -7
View File
@@ -583,13 +583,8 @@ export const makeServerLayer = Layer.unwrap(
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) return;
// No settling delay before the first attempt: routes are already
// serving by the time activation opens this gate (the startup
// sequence awaits routesReady), and the retry schedule below
// covers anything this sleep used to hedge against. Every
// millisecond here is dead time on the path to remote
// reachability after a restart.
yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
yield* Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
Effect.retry({
while: (error) =>
error._tag !== "EnvironmentHttpBadRequestError" &&
@@ -6,6 +6,7 @@ import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
@@ -208,7 +209,7 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
it.effect("keeps local progress and recovers the remote half after a failed refresh", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
@@ -273,14 +274,139 @@ describe("VcsStatusBroadcaster", () => {
state.failRemoteStatus = true;
const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.isTrue(Exit.isFailure(refreshExit));
assert.deepStrictEqual(cached, baseStatus);
// The local half landed even though the refresh failed. The remote half
// was computed for the previous checkout, so the refName change dropped
// it rather than pairing the old branch's data with the new branch; it
// repopulates on the next successful read.
state.failRemoteStatus = false;
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...state.currentRemoteStatus,
});
}).pipe(Effect.provide(testLayer));
});
it.effect("refreshes only the cached local snapshot when requested", () => {
it.effect("returns the new checkout when one lands mid-refresh", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const remoteEntered = yield* Deferred.make<void>();
const releaseRemote = yield* Deferred.make<void>();
// Armed only around the refresh under test, so neither the priming read
// nor the follow-up refresh that the checkout change kicks off blocks.
const gate = { armed: false };
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(makeBackgroundPolicyLayer(() => true)),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.suspend(() => {
state.remoteStatusCalls += 1;
if (!gate.armed) {
return Effect.succeed(state.currentRemoteStatus);
}
gate.armed = false;
return Deferred.succeed(remoteEntered, undefined).pipe(
Effect.andThen(Deferred.await(releaseRemote)),
Effect.as(state.currentRemoteStatus),
);
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
state.remoteInvalidationCalls += 1;
}),
}),
),
);
return yield* Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: "/repo" });
gate.armed = true;
const refreshFiber = yield* Effect.forkChild(broadcaster.refreshStatus("/repo"), {
startImmediately: true,
});
yield* Deferred.await(remoteEntered);
// A checkout lands while the slow remote read is still in flight.
state.currentLocalStatus = {
...baseLocalStatus,
refName: "feature/checked-out-mid-refresh",
};
yield* broadcaster.refreshLocalStatus("/repo");
yield* Deferred.succeed(releaseRemote, undefined);
const refreshed = yield* Fiber.join(refreshFiber);
// The refresh must not hand back the branch that was checked out when
// it started; its own remote result was discarded as superseded.
assert.equal(refreshed.refName, "feature/checked-out-mid-refresh");
}).pipe(Effect.provide(testLayer));
});
});
it.effect("refreshes only the cached local snapshot when the checkout is unchanged", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
hasWorkingTreeChanges: true,
};
const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(initial, baseStatus);
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...baseRemoteStatus,
});
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.localInvalidationCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("repopulates the remote half when a local refresh changes the checkout", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
@@ -299,20 +425,31 @@ describe("VcsStatusBroadcaster", () => {
refName: "feature/local-only-refresh",
hasWorkingTreeChanges: true,
};
state.currentRemoteStatus = {
...baseRemoteStatus,
aheadCount: 4,
};
const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo");
// The refName change drops the stale remote half and forks a remote
// refresh for the new branch; let that fiber settle.
for (let i = 0; i < 100 && state.remoteStatusCalls < 2; i++) {
yield* Effect.yieldNow;
}
const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
assert.deepStrictEqual(initial, baseStatus);
assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus);
assert.deepStrictEqual(cached, {
...state.currentLocalStatus,
...baseRemoteStatus,
...state.currentRemoteStatus,
});
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.localInvalidationCalls, 1);
assert.equal(state.remoteInvalidationCalls, 0);
assert.equal(state.remoteInvalidationCalls, 1);
}).pipe(Effect.provide(makeTestLayer(state)));
});
+156 -34
View File
@@ -10,6 +10,7 @@ import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import type {
@@ -194,6 +195,35 @@ export const make = Effect.gen(function* () {
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
// Serialize refreshes per cwd so a read that started before a mutation (a
// checkout, a pull) cannot finish after the post-mutation refresh and
// publish stale state on top of fresh state. Local and remote halves get
// separate locks: local reads are cheap and must never queue behind an
// in-flight remote read (PR lookups hit the network for seconds). The only
// path that holds both acquires remote before local.
interface CwdLocks {
readonly local: Semaphore.Semaphore;
readonly remote: Semaphore.Semaphore;
}
const locksRef = yield* SynchronizedRef.make(new Map<string, CwdLocks>());
const locksFor = (cwd: string) =>
SynchronizedRef.modifyEffect(locksRef, (locks) => {
const existing = locks.get(cwd);
if (existing) {
return Effect.succeed([existing, locks] as const);
}
return Effect.all([Semaphore.make(1), Semaphore.make(1)]).pipe(
Effect.map(([local, remote]) => {
const created: CwdLocks = { local, remote };
return [created, new Map(locks).set(cwd, created)] as const;
}),
);
});
const withLocalLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
locksFor(cwd).pipe(Effect.flatMap((locks) => locks.local.withPermits(1)(effect)));
const withRemoteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
locksFor(cwd).pipe(Effect.flatMap((locks) => locks.remote.withPermits(1)(effect)));
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
cwd: string,
) {
@@ -206,27 +236,45 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<VcsStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const { shouldPublish, checkoutChanged } = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const changedRefName =
previous.local !== null && previous.local.value.refName !== local.refName;
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
// The cached remote half (ahead/behind, PR) was computed for the
// previous checkout; carrying it across a refName change would pair
// the new branch with the old branch's PR. Drop it and let the
// remote refresh repopulate it for the new branch.
remote: changedRefName ? null : previous.remote,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
return [
{
shouldPublish: previous.local?.fingerprint !== nextLocal.fingerprint,
checkoutChanged: changedRefName,
},
nextCache,
] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
event: checkoutChanged
? {
_tag: "snapshot",
local,
remote: null,
}
: {
_tag: "localUpdated",
local,
},
});
}
return local;
return { local, checkoutChanged };
},
);
@@ -305,8 +353,13 @@ export const make = Effect.gen(function* () {
const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
cwd: string,
) {
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
return yield* withLocalLock(
cwd,
Effect.gen(function* () {
const local = yield* workflow.localStatus({ cwd });
return (yield* updateCachedLocalStatus(cwd, local)).local;
}),
);
});
const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
@@ -329,21 +382,52 @@ export const make = Effect.gen(function* () {
if (cached?.local && cached.remote) {
return mergeGitStatusParts(cached.local.value, cached.remote.value);
}
const [local, remote] = yield* Effect.all(
[
cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
],
{ concurrency: "unbounded" },
return yield* withRemoteLock(
cwd,
withLocalLock(
cwd,
Effect.gen(function* () {
// Re-check under the locks: a refresh may have populated the cache
// while this call was waiting for them.
const current = yield* getCachedStatus(cwd);
if (current?.local && current.remote) {
return mergeGitStatusParts(current.local.value, current.remote.value);
}
const [local, remote] = yield* Effect.all(
[
current?.local ? Effect.succeed(current.local.value) : workflow.localStatus({ cwd }),
current?.remote
? Effect.succeed(current.remote.value)
: workflow.remoteStatus({ cwd }),
],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote);
}),
),
);
return yield* updateCachedStatus(cwd, local, remote);
});
const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
function* (cwd: string) {
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
const result = yield* withLocalLock(
cwd,
Effect.gen(function* () {
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
}),
);
if (result.checkoutChanged) {
// The checkout moved (a switch, or a `git checkout` outside T3's
// commands). The remote half was dropped above; repopulate it for the
// new branch without waiting for the next poll tick.
yield* refreshRemoteStatus(cwd).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkIn(broadcasterScope),
);
}
return result.local;
},
);
@@ -356,27 +440,65 @@ export const make = Effect.gen(function* () {
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
cwd: string,
options?: { readonly refreshUpstream?: boolean },
options?: { readonly refreshUpstream?: boolean; readonly invalidate?: boolean },
) {
if (options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus({ cwd }, options);
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
return yield* withRemoteLock(
cwd,
Effect.gen(function* () {
const refNameBefore = (yield* getCachedStatus(cwd))?.local?.value.refName;
if (options?.invalidate !== false && options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus(
{ cwd },
options?.refreshUpstream === undefined
? undefined
: { refreshUpstream: options.refreshUpstream },
);
// A checkout that lands while the slow remote read is in flight makes
// this result describe the previous branch. Publishing it would
// attach the old branch's PR/divergence to the new refName — discard
// it; the refName change itself already kicked a follow-up refresh.
const refNameAfter = (yield* getCachedStatus(cwd))?.local?.value.refName;
if (refNameBefore !== undefined && refNameAfter !== refNameBefore) {
return (yield* getCachedStatus(cwd))?.remote?.value ?? null;
}
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
}),
);
});
const refreshStatusCore = Effect.fn("VcsStatusBroadcaster.refreshStatusCore")(function* (
cwd: string,
) {
// invalidateStatus (not the two partial invalidations) so an explicit
// refresh also bypasses GitManager's slow PR-lookup cache.
yield* workflow.invalidateStatus(cwd);
const local = yield* withLocalLock(
cwd,
Effect.gen(function* () {
const localResult = yield* workflow.localStatus({ cwd });
return (yield* updateCachedLocalStatus(cwd, localResult, { publish: true })).local;
}),
);
const remote = yield* refreshRemoteStatus(cwd, { invalidate: false });
// A checkout can land between the two reads. refreshRemoteStatus discards
// a superseded remote result, which would leave `local` describing the old
// branch — returning that pair would hand the caller a status the cache
// itself no longer agrees with. Prefer the cache's halves, which the
// concurrent refresh has already reconciled for the new branch.
const cached = yield* getCachedStatus(cwd);
return mergeGitStatusParts(
cached?.local?.value ?? local,
cached?.remote ? cached.remote.value : remote,
);
});
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshStatus",
)(function* (rawCwd) {
const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
// invalidateStatus (not the two partial invalidations) so an explicit
// refresh also bypasses GitManager's slow PR-lookup cache.
yield* workflow.invalidateStatus(cwd);
const [local, remote] = yield* Effect.all(
[workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
{ concurrency: "unbounded" },
);
return yield* updateCachedStatus(cwd, local, remote, { publish: true });
return yield* refreshStatusCore(cwd);
});
const makeRemoteRefreshLoop = (
+16 -1
View File
@@ -1763,6 +1763,10 @@ const makeWsRpcLayer = (
"rpc.aggregate": "vcs",
},
),
[WS_METHODS.vcsBranchPr]: (input) =>
observeRpcEffect(WS_METHODS.vcsBranchPr, gitWorkflow.branchPr(input), {
"rpc.aggregate": "vcs",
}),
[WS_METHODS.vcsPull]: (input) =>
observeRpcEffect(
WS_METHODS.vcsPull,
@@ -1839,7 +1843,18 @@ const makeWsRpcLayer = (
[WS_METHODS.vcsSwitchRef]: (input) =>
observeRpcEffect(
WS_METHODS.vcsSwitchRef,
gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
gitWorkflow.switchRef(input).pipe(
// Publish the new refName before the RPC resolves so a client
// that awaited the switch can never observe the old branch from
// the status stream afterwards. The full refresh (remote half,
// PR lookup) is slow and stays forked.
Effect.tap(() =>
vcsStatusBroadcaster
.refreshLocalStatus(input.cwd)
.pipe(Effect.ignoreCause({ log: true })),
),
Effect.tap(() => refreshGitStatus(input.cwd)),
),
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.vcsInit]: (input) =>
-43
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
areFontAdvancesMonospace,
clampCodeFontSize,
clampInterfaceFontSize,
clampPromptFontSize,
@@ -10,22 +9,8 @@ import {
appearanceFontStack,
cssFontFamilies,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
} from "./appearanceFonts";
describe("areFontAdvancesMonospace", () => {
it("accepts a fixed advance and rejects any proportional glyph", () => {
expect(areFontAdvancesMonospace([10, 10, 10, 10])).toBe(true);
expect(areFontAdvancesMonospace([10, 10, 7, 10])).toBe(false);
expect(areFontAdvancesMonospace([10, 10.02])).toBe(false);
});
it("fails open when canvas metrics are unavailable", () => {
expect(areFontAdvancesMonospace([])).toBe(true);
expect(areFontAdvancesMonospace([Number.NaN, Number.NaN])).toBe(true);
});
});
describe("cssFontFamilies", () => {
it("returns null for effectively empty input", () => {
expect(cssFontFamilies("")).toBeNull();
@@ -69,34 +54,6 @@ describe("appearanceFontStack", () => {
});
});
describe("resolveTerminalFontPreference", () => {
it("inherits the code font in simple mode", () => {
expect(
resolveTerminalFontPreference({ advanced: false, code: "Fira Code", terminal: "" }),
).toBe("Fira Code");
expect(
resolveTerminalFontPreference({
advanced: false,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Fira Code");
});
it("keeps code and terminal fonts independent in advanced mode", () => {
expect(resolveTerminalFontPreference({ advanced: true, code: "Fira Code", terminal: "" })).toBe(
"",
);
expect(
resolveTerminalFontPreference({
advanced: true,
code: "Fira Code",
terminal: "Berkeley Mono",
}),
).toBe("Berkeley Mono");
});
});
describe("font size clamping", () => {
it("keeps sizes inside the ranges the UI can absorb", () => {
expect(clampInterfaceFontSize(16)).toBe(16);
+5 -39
View File
@@ -25,22 +25,6 @@ export const DEFAULT_SANS_FONT_STACK =
export const DEFAULT_CODE_FONT_STACK =
'"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace';
export const TYPOGRAPHY_ADVANCED_STORAGE_KEY = "t3code:typography-advanced";
/**
* Simple typography treats the terminal as another monospace surface. In
* Advanced mode an empty terminal preference means the terminal default,
* keeping later code-font changes isolated to code surfaces.
*/
export function resolveTerminalFontPreference(input: {
readonly advanced: boolean;
readonly code: string;
readonly terminal: string;
}): string {
if (input.advanced) return input.terminal;
return input.code;
}
function quoteFontFamilyName(name: string): string {
const bare = name.trim();
if (bare.length === 0) return "";
@@ -181,22 +165,6 @@ export function isFontFamilyAvailable(family: string): boolean {
}
}
const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "italic 700"] as const;
const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const;
const MONOSPACE_ADVANCE_TOLERANCE = 0.01;
export function areFontAdvancesMonospace(advances: readonly number[]): boolean {
const reference = advances[0];
if (
reference === undefined ||
reference <= 0 ||
advances.some((advance) => !Number.isFinite(advance) || advance <= 0)
) {
return true;
}
return advances.every((advance) => Math.abs(advance - reference) < MONOSPACE_ADVANCE_TOLERANCE);
}
/**
* Whether a family renders every character on the same advance. Cell-grid
* surfaces (the terminal) require this: a proportional face draws its text
@@ -214,15 +182,13 @@ export function isMonospaceFamily(family: string): boolean {
fontProbeContext = document.createElement("canvas").getContext("2d");
}
if (fontProbeContext === null) return true;
const context = fontProbeContext;
// Fall back to a generic mono so an absent face measures as monospace and
// is left for the normal fallback chain to resolve.
for (const variant of MONOSPACE_PROBE_VARIANTS) {
context.font = `${variant} 32px ${families}, monospace`;
const advances = MONOSPACE_PROBE_GLYPHS.map((glyph) => context.measureText(glyph).width);
if (!areFontAdvancesMonospace(advances)) return false;
}
return true;
fontProbeContext.font = `32px ${families}, monospace`;
const narrow = fontProbeContext.measureText("i").width;
const wide = fontProbeContext.measureText("M").width;
if (!Number.isFinite(narrow) || !Number.isFinite(wide) || wide === 0) return true;
return Math.abs(wide - narrow) < 0.5;
} catch {
return true;
}
@@ -10,7 +10,6 @@ import {
resolveEffectiveEnvMode,
resolveEnvModeLabel,
resolveBranchTriggerLabel,
resolveBranchToolbarPrBranch,
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
resolveLocalCheckoutBranchMismatch,
@@ -270,35 +269,6 @@ describe("resolveBranchTriggerLabel", () => {
});
});
describe("resolveBranchToolbarPrBranch", () => {
it("uses the explicit thread branch when it matches the displayed branch", () => {
expect(
resolveBranchToolbarPrBranch({
activeThreadBranch: "feature/current",
resolvedActiveBranch: "feature/current",
}),
).toBe("feature/current");
});
it("hides PR state while an optimistic branch switch is in flight", () => {
expect(
resolveBranchToolbarPrBranch({
activeThreadBranch: "feature/current",
resolvedActiveBranch: "feature/next",
}),
).toBeNull();
});
it("does not infer PR state without an explicit thread branch", () => {
expect(
resolveBranchToolbarPrBranch({
activeThreadBranch: null,
resolvedActiveBranch: "feature/current",
}),
).toBeNull();
});
});
describe("resolveLocalCheckoutBranchMismatch", () => {
it("detects when a local thread is associated with a different branch than the checkout", () => {
expect(
@@ -183,13 +183,6 @@ export function resolveBranchTriggerLabel(input: {
return resolvedActiveBranch;
}
export function resolveBranchToolbarPrBranch(input: {
activeThreadBranch: string | null;
resolvedActiveBranch: string | null;
}): string | null {
return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
}
export function resolveLocalCheckoutBranchMismatch(input: {
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -37,7 +37,6 @@ import { getSourceControlPresentation } from "../sourceControlPresentation";
import {
deriveLocalBranchNameFromRemoteRef,
resolveBranchTriggerLabel,
resolveBranchToolbarPrBranch,
resolveBranchSelectionTarget,
resolveBranchToolbarValue,
resolveDraftEnvModeAfterBranchChange,
@@ -47,7 +46,7 @@ import {
import {
ChangeRequestStatusIcon,
prStatusIndicator,
resolveThreadPr,
selectBranchPr,
} from "./ThreadStatusIndicators";
import { Button } from "./ui/button";
import { Switch } from "./ui/switch";
@@ -601,13 +600,28 @@ export function BranchToolbarBranchSelector({
startFromOrigin,
});
// PR pill shown next to the branch selector when the active branch has one.
const branchPr = resolveThreadPr({
threadBranch: resolveBranchToolbarPrBranch({
activeThreadBranch,
resolvedActiveBranch,
}),
// PR pill shown next to the branch selector when the displayed ref has one.
// The stream-fed status is the fast path while the checkout matches; the
// branch-keyed query keeps the pill correct when the checkout has moved
// elsewhere. Draft "From <base>" selectors intentionally show none — the
// base branch's PR is not this thread's.
const branchPrLookupBranch =
(effectiveEnvMode === "worktree" && !activeWorktreePath) ||
resolvedActiveBranchIsRemote === true
? null
: resolvedActiveBranch;
const branchPrQuery = useEnvironmentQuery(
branchCwd !== null && branchPrLookupBranch !== null
? vcsEnvironment.branchPr({
environmentId,
input: { cwd: branchCwd, branch: branchPrLookupBranch },
})
: null,
);
const branchPr = selectBranchPr({
branch: branchPrLookupBranch,
gitStatus: branchStatusQuery.data ?? null,
branchPr: branchPrQuery.data?.pr,
});
const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider);
// Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's
+4 -2
View File
@@ -238,7 +238,7 @@ import {
shouldShowProviderStatusBanner,
} from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { useThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
import {
@@ -3964,7 +3964,9 @@ function ChatViewContent(props: ChatViewProps) {
// so the banner and the sidebar row never disagree.
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
const activeThreadPr = resolveThreadPr({
const activeThreadPr = useThreadPr({
environmentId,
cwd: gitStatusCwd,
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
});
@@ -1099,6 +1099,12 @@ export default function GitActionsControl({
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
// Deliberately the checkout's status, not the active thread's branch: every
// action here (commit, push, create) runs against whatever is checked out at
// `gitCwd`, so gating them on another branch's PR would offer "Create PR"
// for a branch that already has one — or hide it for one that doesn't.
// Thread-scoped PR state lives on the sidebar badge and the composer pill,
// which are branch-keyed; the branch-mismatch banner explains the split.
const gitStatusForActions = gitStatus;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
+4 -2
View File
@@ -16,8 +16,8 @@ import {
ChangeRequestStatusIcon,
prStatusIndicator,
PrStatusTooltipContent,
resolveThreadPr,
terminalStatusFromRunningIds,
useThreadPr,
ThreadStatusLabel,
ThreadWorktreeIndicator,
} from "./ThreadStatusIndicators";
@@ -449,7 +449,9 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
lastVisitedAt,
},
});
const pr = resolveThreadPr({
const pr = useThreadPr({
environmentId: thread.environmentId,
cwd: gitCwd,
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
+4 -2
View File
@@ -127,8 +127,8 @@ import {
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
import {
prStatusIndicator,
resolveThreadPr,
settledPrHoverColorClass,
useThreadPr,
terminalStatusFromRunningIds,
type TerminalStatusIndicator,
} from "./ThreadStatusIndicators";
@@ -543,7 +543,9 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
activeThreadBranch: thread.branch,
currentGitBranch: gitStatus.data?.refName ?? null,
});
const pr = resolveThreadPr({
const pr = useThreadPr({
environmentId: thread.environmentId,
cwd: gitCwd,
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
import {
prStatusIndicator,
resolveThreadPr,
selectBranchPr,
settledPrHoverColorClass,
} from "./ThreadStatusIndicators";
@@ -30,43 +30,54 @@ function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
};
}
describe("resolveThreadPr", () => {
it("keeps local-checkout PR indicators scoped to the stored thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "feature/other",
gitStatus: status(),
}),
).toBeNull();
});
const otherBranchPr = {
number: 7,
title: "Branch-keyed PR",
url: "https://github.com/pingdotgg/t3code/pull/7",
baseRef: "main",
headRef: "feature/other",
state: "open",
} as const;
it("hides PR indicators when a dedicated worktree has switched away from the thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "stack/base",
gitStatus: status(),
}),
).toBeNull();
});
it("hides PR indicators when thread branch metadata is missing", () => {
expect(
resolveThreadPr({
threadBranch: null,
gitStatus: status(),
}),
).toBeNull();
});
it("shows the PR when the live checkout matches the stored thread branch", () => {
describe("selectBranchPr", () => {
it("shows the PR when the live checkout matches the requested branch", () => {
const gitStatus = status();
expect(selectBranchPr({ branch: "feature/current", gitStatus, branchPr: undefined })).toBe(
gitStatus.pr,
);
});
it("falls back to the branch-keyed lookup when the checkout moved elsewhere", () => {
expect(
resolveThreadPr({
threadBranch: "feature/current",
gitStatus,
selectBranchPr({
branch: "feature/other",
gitStatus: status(),
branchPr: otherBranchPr,
}),
).toBe(gitStatus.pr);
).toBe(otherBranchPr);
});
it("treats an empty PR on the matching checkout as authoritative", () => {
// Regression: a warm branch-keyed result must not resurrect a badge the
// status stream just cleared (e.g. immediately after a merge).
expect(
selectBranchPr({
branch: "feature/current",
gitStatus: status({ pr: null }),
branchPr: otherBranchPr,
}),
).toBeNull();
});
it("returns nothing when the branch is unknown and no lookup resolved", () => {
expect(selectBranchPr({ branch: null, gitStatus: status(), branchPr: undefined })).toBeNull();
});
it("returns nothing while the branch-keyed lookup is unresolved", () => {
expect(
selectBranchPr({ branch: "feature/other", gitStatus: status(), branchPr: undefined }),
).toBeNull();
});
});
@@ -3,7 +3,7 @@ import {
scopedThreadKey,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import type { VcsStatusResult } from "@t3tools/contracts";
import type { EnvironmentId, VcsStatusResult } from "@t3tools/contracts";
import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
import { useMemo } from "react";
import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
@@ -110,20 +110,60 @@ export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }
);
}
export function resolveThreadPr(input: {
/**
* True when the streamed status describes the thread's own branch, and so is
* authoritative about that branch's PR — including when it reports none.
*/
function statusCoversBranch(
gitStatus: VcsStatusResult | null,
threadBranch: string | null,
): gitStatus is VcsStatusResult {
return gitStatus !== null && threadBranch !== null && gitStatus.refName === threadBranch;
}
/**
* Pick the PR for `branch` from the two available sources. The streamed
* status wins whenever it describes that branch — including when it reports
* no PR, which is why this short-circuits instead of falling through with
* `??`: a warm branch-keyed result must never resurrect a badge the
* authoritative status just cleared (e.g. right after a merge).
*/
export function selectBranchPr(input: {
branch: string | null;
gitStatus: VcsStatusResult | null;
branchPr: ThreadPr | null | undefined;
}): ThreadPr | null {
if (statusCoversBranch(input.gitStatus, input.branch)) {
return input.gitStatus.pr ?? null;
}
return input.branchPr ?? null;
}
/**
* PR state for a thread, keyed by the thread's recorded branch rather than
* the current checkout. The stream-fed status is the fast path while the
* checkout matches the thread's branch; the branch-keyed query keeps the
* badge alive when the checkout has moved elsewhere.
*/
export function useThreadPr(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
threadBranch: string | null;
gitStatus: VcsStatusResult | null;
}): ThreadPr | null {
const { threadBranch, gitStatus } = input;
if (gitStatus === null) {
return null;
}
if (threadBranch === null || gitStatus.refName !== threadBranch) {
return null;
}
return gitStatus.pr ?? null;
const branchPr = useEnvironmentQuery(
input.environmentId !== null && input.threadBranch !== null && input.cwd !== null
? vcsEnvironment.branchPr({
environmentId: input.environmentId,
input: { cwd: input.cwd, branch: input.threadBranch },
})
: null,
);
return selectBranchPr({
branch: input.threadBranch,
gitStatus: input.gitStatus,
branchPr: branchPr.data?.pr,
});
}
export function terminalStatusFromRunningIds(
@@ -250,7 +290,9 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
})
: null,
);
const pr = resolveThreadPr({
const pr = useThreadPr({
environmentId: thread.environmentId,
cwd: gitCwd,
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
@@ -18,7 +18,6 @@ import {
type ThreadId,
} from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as Schema from "effect/Schema";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
@@ -58,7 +57,6 @@ import {
} from "../types";
import { readLocalApi } from "~/localApi";
import { useClientSettings } from "../hooks/useSettings";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { useAttachedTerminalSession } from "../state/terminalSessions";
import { serverEnvironment } from "../state/server";
import { previewEnvironment } from "../state/preview";
@@ -66,7 +64,6 @@ import { terminalEnvironment } from "../state/terminal";
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
import { useAtomCommand } from "../state/use-atom-command";
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
import { resolveTerminalFontPreference, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../appearanceFonts";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -244,7 +241,6 @@ export function shouldHandleTerminalExit(
}
interface TerminalViewportProps {
advancedTypography: boolean;
threadRef: ScopedThreadRef;
threadId: ThreadId;
terminalId: string;
@@ -268,7 +264,6 @@ interface TerminalLaunchLocation {
}
export function TerminalViewport({
advancedTypography,
threadRef,
threadId,
terminalId,
@@ -317,12 +312,10 @@ export function TerminalViewport({
onAddTerminalContext(selection);
});
const readTerminalLabel = useEffectEvent(() => terminalLabel);
const terminalFontFamily = useClientSettings((settings) =>
resolveTerminalFontPreference({
advanced: advancedTypography,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
}),
// The terminal inherits the monospace (code) preference unless it has an
// override of its own, so one font choice drives every mono surface.
const terminalFontFamily = useClientSettings(
(settings) => settings.fontFamilyTerminal.trim() || settings.fontFamilyCode,
);
const terminalFontSize = useClientSettings((settings) => settings.fontSizeTerminal);
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
@@ -928,11 +921,6 @@ export default function ThreadTerminalDrawer({
terminalLaunchLocationsById,
}: ThreadTerminalDrawerProps) {
const isPanel = mode === "panel";
const [advancedTypography] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
Schema.Boolean,
);
const controlledDrawerHeight = clampDrawerHeight(height);
const [drawerHeightState, setDrawerHeightState] = useState(() => ({
threadId,
@@ -1369,7 +1357,6 @@ export default function ThreadTerminalDrawer({
>
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
@@ -1397,7 +1384,6 @@ export default function ThreadTerminalDrawer({
) : (
<div className="h-full p-1">
<TerminalViewport
advancedTypography={advancedTypography}
key={resolvedActiveTerminalId}
threadRef={threadRef}
threadId={threadId}
@@ -541,10 +541,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
}
return mapping.size > 0 ? mapping : EMPTY_MODEL_JUMP_LABELS;
}, [keybindings, modelJumpCommandByKey, modelJumpShortcutContext]);
const modelListExtraData = useMemo(
() => ({ favoritesSet, modelJumpLabelByKey }),
[favoritesSet, modelJumpLabelByKey],
);
useEffect(() => {
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
@@ -714,7 +710,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
<LegendList<string>
ref={modelListRef}
data={filteredItemKeys}
extraData={modelListExtraData}
extraData={favoritesSet}
keyExtractor={(modelKey) => modelKey}
renderItem={({ item: modelKey, index }) => {
if (legacySection?.key === modelKey) {
@@ -120,26 +120,11 @@ export function CodeFontPreview() {
);
}
// A zsh-style prompt: green arrow, cyan project, blue/red git segment,
// yellow dirty marker. It doubles as the echo loop's fresh-line prompt.
const TERMINAL_PROMPT =
"\x1b[1;32m→\x1b[0m \x1b[1;36mt3code\x1b[0m \x1b[1;34mgit:(\x1b[1;31mmain\x1b[1;34m)\x1b[0m \x1b[1;33m✗\x1b[0m ";
// A dev-server startup: brand line, addresses, a test summary, and a READY
// badge. Together the lines cover bold, dim, underline, the six accent
// colors, and a background cell, so a font choice shows every SGR the
// terminal actually renders.
const TERMINAL_PROMPT = "\x1b[2m$\x1b[0m ";
const TERMINAL_PREVIEW_TRANSCRIPT =
`${TERMINAL_PROMPT}vpr dev\r\n` +
"\r\n" +
" \x1b[1;32mVITE\x1b[0m \x1b[32mv7.1.1\x1b[0m \x1b[2mready in\x1b[0m \x1b[1m1.24s\x1b[0m\r\n" +
"\r\n" +
" \x1b[32m→\x1b[0m \x1b[2mLocal:\x1b[0m \x1b[4;36mhttp://127.0.0.1:5173/\x1b[0m\r\n" +
" \x1b[32m→\x1b[0m \x1b[2mNetwork:\x1b[0m \x1b[4;36mhttp://192.168.1.24:5173/\x1b[0m\r\n" +
"\r\n" +
" \x1b[32m✓ 85 passed\x1b[0m \x1b[33m△ 2 warnings\x1b[0m \x1b[31m✗ 0 failed\x1b[0m\r\n" +
"\r\n" +
" \x1b[42;30m READY \x1b[0m \x1b[2mwatching for changes — press\x1b[0m \x1b[1mq\x1b[0m \x1b[2mto quit\x1b[0m\r\n" +
"\r\n" +
`${TERMINAL_PROMPT}npm run dev\r\n` +
"\x1b[32m✓\x1b[0m Ready in 430ms\r\n" +
"\x1b[2mLocal:\x1b[0m \x1b[36mhttp://localhost:3000\x1b[0m\r\n" +
TERMINAL_PROMPT;
/** The surface treats an omitted family or size as "use the built-in default". */
@@ -240,7 +225,7 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
return (
<div
ref={mountRef}
className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
className="relative mt-1 mb-2 h-36 overflow-hidden rounded-lg border border-border"
aria-label="Terminal font preview"
/>
);
@@ -115,8 +115,6 @@ import {
isFontFamilyAvailable,
isMonospaceFamily,
resolveDefaultFamilyLabel,
resolveTerminalFontPreference,
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
} from "../../appearanceFonts";
import { CodeFontPreview, PromptFontPreview, TerminalFontPreview } from "./SettingsFontPreviews";
import { discoverInstalledFonts, FontFamilyPicker, useFontEnumeration } from "./FontFamilyPicker";
@@ -1153,8 +1151,10 @@ function useFontDefaultFamilies() {
return {
sans: defaults.sans,
code: defaults.code,
// The composer inherits whatever the interface preference resolves to.
// The composer inherits whatever the interface preference resolves to;
// the terminal inherits the monospace preference the same way.
interfaceFamily: settings.fontFamilySans.trim() || defaults.sans,
monoFamily: settings.fontFamilyCode.trim() || defaults.code,
};
}
@@ -1244,8 +1244,8 @@ function TerminalFontRow() {
return (
<FontFamilySettingsRow
{...searchableSetting("terminal-font")}
description="Terminal output, independent from code blocks and diffs."
defaultFamily={defaults.code}
description="Terminal output. Follows the monospace font unless set."
defaultFamily={defaults.monoFamily}
value={settings.fontFamilyTerminal}
onValueChange={(fontFamilyTerminal) => updateSettings({ fontFamilyTerminal })}
requireMonospace
@@ -1258,11 +1258,7 @@ function TerminalFontRow() {
}}
preview={
<TerminalFontPreview
family={resolveTerminalFontPreference({
advanced: true,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
size={settings.fontSizeTerminal}
/>
}
@@ -1354,11 +1350,7 @@ function SimpleFontRows() {
<>
<CodeFontPreview />
<TerminalFontPreview
family={resolveTerminalFontPreference({
advanced: false,
code: settings.fontFamilyCode,
terminal: settings.fontFamilyTerminal,
})}
family={settings.fontFamilyTerminal.trim() || settings.fontFamilyCode}
size={settings.fontSizeTerminal}
/>
</>
@@ -1378,6 +1370,8 @@ const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
: []),
]);
const TYPOGRAPHY_ADVANCED_KEY = "t3code:typography-advanced";
/**
* The two-font view by default - one sans, one monospace, each cascading to
* every surface it reaches - with an Advanced switch in the section header
@@ -1386,11 +1380,7 @@ const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
* target exists to scroll to.
*/
function TypographySection() {
const [advanced, setAdvanced] = useLocalStorage(
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
false,
Schema.Boolean,
);
const [advanced, setAdvanced] = useLocalStorage(TYPOGRAPHY_ADVANCED_KEY, false, Schema.Boolean);
const searchTargetId = useSettingsSearchTargetId();
// Flip Advanced on once per search jump so the hidden target can mount and
// scroll; tracking the handled id lets the user turn it back off without
+20 -23
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it } from "vite-plus/test";
import type { GhosttyCell, GhosttyRow } from "./core";
import {
@@ -11,7 +11,6 @@ import {
isTerminalCopyShortcut,
isTerminalLinkPointerGesture,
isTerminalPasteShortcut,
loadTerminalFontFamily,
shouldBlinkTerminalCursor,
shouldReportTerminalMouse,
shouldShowTerminalLinkHover,
@@ -23,6 +22,7 @@ import {
terminalLinkAtPositionWithRange,
terminalContentOriginY,
terminalFontFamily,
fittedTerminalFontSize,
terminalFontSize,
terminalWheelArrowData,
terminalWheelDeltaRows,
@@ -295,27 +295,6 @@ describe("application mouse reporting", () => {
});
describe("terminal font resolution", () => {
it("validates the requested face after its styles load", async () => {
let loaded = false;
const load = vi.fn(async () => {
loaded = true;
return [];
});
const resolve = vi.fn(() => {
expect(loaded).toBe(true);
return DEFAULT_TERMINAL_FONT_FAMILY;
});
await expect(
loadTerminalFontFamily("Proportional Test", 12, {
load,
resolve,
}),
).resolves.toBe(DEFAULT_TERMINAL_FONT_FAMILY);
expect(load).toHaveBeenCalledTimes(4);
expect(resolve).toHaveBeenCalledWith("Proportional Test");
});
it("keeps the glyph fallbacks behind a custom text face", () => {
expect(terminalFontFamily()).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
expect(terminalFontFamily(" ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
@@ -342,6 +321,24 @@ describe("terminal font resolution", () => {
expect(terminalFontFamily(" , ")).toBe(DEFAULT_TERMINAL_FONT_FAMILY);
});
it("slides the rendered size down until a full-width grid fits the canvas", () => {
// SF Mono-like advance: 0.6em per cell.
const cellWidthAt = (size: number) => size * 0.6;
// A wide drawer keeps the preference untouched.
expect(fittedTerminalFontSize(cellWidthAt, 20, 1140)).toBe(20);
// A split pane at the same preference shrinks until 80 columns fit.
const fitted = fittedTerminalFontSize(cellWidthAt, 20, 570);
expect(fitted).toBeLessThan(20);
expect(Math.floor((570 - 8) / cellWidthAt(fitted))).toBeGreaterThanOrEqual(80);
// A tiny pane stops at the legibility floor instead of vanishing.
expect(fittedTerminalFontSize(cellWidthAt, 20, 220)).toBe(8);
// A preference below the floor is honored as-is.
expect(fittedTerminalFontSize(cellWidthAt, 6, 220)).toBe(6);
// Unmeasured layouts leave the preference alone.
expect(fittedTerminalFontSize(cellWidthAt, 14, 0)).toBe(14);
expect(fittedTerminalFontSize(() => 0, 14, 600)).toBe(14);
});
it("clamps requested font sizes to the supported range", () => {
expect(terminalFontSize()).toBe(DEFAULT_TERMINAL_FONT_SIZE);
expect(terminalFontSize(Number.NaN)).toBe(DEFAULT_TERMINAL_FONT_SIZE);
+62 -63
View File
@@ -36,13 +36,6 @@ const CONTENT_PADDING = 4;
const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
/** Half a blink cycle: the visible and hidden phases are equally long. */
const CURSOR_BLINK_INTERVAL_MS = 500;
const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
const TERMINAL_FONT_LOAD_VARIANTS = [
"normal 400",
"normal 700",
"italic 400",
"italic 700",
] as const;
/** Requested terminal font; omitted fields fall back to the defaults. */
export interface GhosttyTerminalFont {
@@ -85,13 +78,6 @@ function quoteTerminalFontFamilies(list: string): string {
.join(", ");
}
function uncheckedTerminalFontFamily(family?: string): string {
const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
return custom.length === 0
? DEFAULT_TERMINAL_FONT_FAMILY
: `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
}
export function terminalFontFamily(family?: string): string {
// Quote non-ident names ("3270 Nerd Font", "M+ 1m"): an unquoted one makes
// the whole canvas font string invalid and the assignment silently no-ops.
@@ -102,31 +88,43 @@ export function terminalFontFamily(family?: string): string {
// it here rather than render a ragged grid with a stranded cursor.
if (!isMonospaceFamily(custom)) return DEFAULT_TERMINAL_FONT_FAMILY;
// A custom face keeps the glyph fallbacks so prompt symbols stay covered.
return uncheckedTerminalFontFamily(custom);
return `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
}
/** Load every style the renderer can request, then validate the actual face. */
export async function loadTerminalFontFamily(
family: string | undefined,
size: number,
environment?: {
readonly load: (font: string, text: string) => Promise<unknown>;
readonly resolve: (family: string | undefined) => string;
},
): Promise<string> {
const candidate = uncheckedTerminalFontFamily(family);
const load =
environment?.load ?? ((font: string, text: string) => document.fonts.load(font, text));
try {
await Promise.all(
TERMINAL_FONT_LOAD_VARIANTS.map((variant) =>
load(`${variant} ${size}px ${candidate}`, TERMINAL_FONT_LOAD_TEXT),
),
);
} catch {
// The fixed-width fallback stack remains available if a face cannot load.
/**
* Grids narrower than a classic 80-column terminal wrap command output hard,
* so the rendered font size follows the canvas width: the preference is the
* ceiling, and the size slides down (to a legibility floor) until a full-width
* grid fits. A widening pane slides it back up toward the preference.
*/
const MIN_TERMINAL_FIT_COLUMNS = 80;
const MIN_TERMINAL_FIT_FONT_SIZE = 8;
export function fittedTerminalFontSize(
cellWidthAt: (size: number) => number,
requested: number,
mountWidth: number,
): number {
const available = mountWidth - CONTENT_PADDING * 2;
if (available <= 0) return requested;
const floor = Math.min(requested, MIN_TERMINAL_FIT_FONT_SIZE);
const fits = (cellWidth: number) =>
cellWidth > 0 && Math.floor(available / cellWidth) >= MIN_TERMINAL_FIT_COLUMNS;
let cellWidth = cellWidthAt(requested);
if (cellWidth <= 0 || fits(cellWidth)) return requested;
// The advance scales linearly with size for monospace faces: jump close to
// the fitting size, then settle the remaining rounding one step at a time.
const targetCellWidth = available / MIN_TERMINAL_FIT_COLUMNS;
let size = Math.max(
floor,
Math.min(requested, Math.floor((requested * targetCellWidth) / cellWidth)),
);
while (size > floor) {
cellWidth = cellWidthAt(size);
if (cellWidth <= 0 || fits(cellWidth)) break;
size -= 1;
}
return (environment?.resolve ?? terminalFontFamily)(family);
return size;
}
export function terminalFontSize(size?: number): number {
@@ -481,10 +479,9 @@ export class GhosttyTerminalSurface {
private readonly options: GhosttyTerminalSurfaceOptions;
private metrics: GhosttyCellMetrics;
private fontFamily: string;
private requestedFontFamily: string | undefined;
private fontSize: number;
private requestedFontSize: number;
private fontEpoch = 0;
private pendingFontEpoch: number | null = null;
private readonly resizeObserver: ResizeObserver;
private readonly scrollbarThumb: HTMLDivElement;
private snapshot: GhosttySnapshot | null = null;
@@ -548,7 +545,6 @@ export class GhosttyTerminalSurface {
context: CanvasRenderingContext2D,
core: GhosttyTerminalCore,
metrics: GhosttyCellMetrics,
fontFamily: string,
options: GhosttyTerminalSurfaceOptions,
) {
this.mount = mount;
@@ -561,9 +557,9 @@ export class GhosttyTerminalSurface {
this.metrics = metrics;
this.options = options;
this.theme = options.theme;
this.fontFamily = fontFamily;
this.requestedFontFamily = options.font?.family;
this.fontFamily = terminalFontFamily(options.font?.family);
this.fontSize = terminalFontSize(options.font?.size);
this.requestedFontSize = this.fontSize;
this.resizeObserver = new ResizeObserver(() => this.fit());
this.installEvents();
this.watchDevicePixelRatio();
@@ -604,20 +600,16 @@ export class GhosttyTerminalSurface {
const context = canvas.getContext("2d", { alpha: false });
if (!context) throw new Error("Canvas 2D is unavailable");
// An opaque canvas backing store initializes to solid black, and the font
// and WASM loads below leave it on screen for the whole setup window; paint
// the theme background first so the mount never flashes a black box.
context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
context.fillRect(0, 0, canvas.width, canvas.height);
const fontFamily = terminalFontFamily(options.font?.family);
const fontSize = terminalFontSize(options.font?.size);
try {
// Cell metrics must come from the faces that will render; measuring before
// the bundled webfonts load would size the grid from a fallback font.
await ensureTerminalSymbolsFont();
await document.fonts.load(`${fontSize}px ${fontFamily}`);
} catch {
// Metrics fall back to whichever faces are already available.
}
const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
const metrics = measureGhosttyCell(context, fontSize, fontFamily);
const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
const core = await GhosttyTerminalCore.create(
@@ -637,7 +629,6 @@ export class GhosttyTerminalSurface {
context,
core,
metrics,
fontFamily,
options,
);
surface.fit();
@@ -676,16 +667,19 @@ export class GhosttyTerminalSurface {
async setFont(font: GhosttyTerminalFont): Promise<void> {
if (this.disposed) return;
const fontFamily = terminalFontFamily(font.family);
const fontSize = terminalFontSize(font.size);
// The fields only change together with their metrics after the load, and
// the epoch lets the newest overlapping call win regardless of load order.
const epoch = ++this.fontEpoch;
this.pendingFontEpoch = epoch;
const fontFamily = await loadTerminalFontFamily(font.family, fontSize);
try {
await document.fonts.load(`${fontSize}px ${fontFamily}`);
} catch {
// Metrics fall back to whichever faces are already available.
}
if (this.disposed || epoch !== this.fontEpoch) return;
this.pendingFontEpoch = null;
this.fontFamily = fontFamily;
this.requestedFontFamily = font.family;
this.requestedFontSize = fontSize;
this.fontSize = fontSize;
this.applyFontMetrics();
}
@@ -712,17 +706,6 @@ export class GhosttyTerminalSurface {
private readonly onFontsLoaded = () => {
if (this.disposed) return;
// The explicit load validates every style and applies the newest request.
// Its own loading events must not revalidate the previously applied face.
if (this.pendingFontEpoch !== null) return;
// A face may become available after an earlier fallback measurement. Run
// the fixed-width guard again before using its newly loaded metrics.
const fontFamily = terminalFontFamily(this.requestedFontFamily);
if (fontFamily !== this.fontFamily) {
this.fontFamily = fontFamily;
this.applyFontMetrics();
return;
}
// A face that finished loading after the initial measurement changes glyph
// advances; re-measure and refit so the grid matches what actually renders.
const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
@@ -741,6 +724,22 @@ export class GhosttyTerminalSurface {
const width = this.mount.clientWidth;
const height = this.mount.clientHeight;
if (width <= 0 || height <= 0) return false;
const fitted = fittedTerminalFontSize(
(size) => measureGhosttyCell(this.context, size, this.fontFamily).width,
this.requestedFontSize,
width,
);
if (fitted !== this.fontSize) {
this.fontSize = fitted;
this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
// The grid-change branch below resizes the core, but only when the
// column count moved; the cell geometry always did, so sync it here.
this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
this.inputLeft = -1;
this.inputTop = -1;
this.forceFullRender = true;
this.scrollbarDirty = true;
}
const ratio = window.devicePixelRatio || 1;
const pixelWidth = Math.max(1, Math.round(width * ratio));
const pixelHeight = Math.max(1, Math.round(height * ratio));
@@ -7,16 +7,12 @@ import {
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import { RpcClientError } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
@@ -34,7 +30,6 @@ import {
makeEnvironmentServerConfigState,
isLegacyUpdateHandoffLoss,
matchesServerUpdateReadyEvent,
nudgeReconnectDuringUpdateRestart,
projectServerWelcome,
resolveServerConfigValue,
resolveServerUpdateProgressResult,
@@ -76,56 +71,6 @@ function session(client: WsRpcProtocolClient): RpcSession {
};
}
describe("update restart reconnect nudges", () => {
it.effect("retries once per backoff entry instead of only the first", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const states = [
{ phase: "backoff" },
{ phase: "connecting" },
{ phase: "backoff" },
{ phase: "backoff" },
];
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable(states),
retryNow: Ref.update(retries, (count) => count + 1),
interval: Duration.zero,
});
// Three backoff entries, three nudges. The old one-shot behavior fired
// once and then let the supervisor's ladder stretch to 16-second gaps.
expect(yield* Ref.get(retries)).toBe(3);
}),
);
it.effect("paces nudges so a fast-failing connection cannot spin", () =>
Effect.gen(function* () {
const retries = yield* Ref.make(0);
const fiber = yield* Effect.forkChild(
nudgeReconnectDuringUpdateRestart({
stateChanges: Stream.fromIterable([{ phase: "backoff" }, { phase: "backoff" }]),
retryNow: Ref.update(retries, (count) => count + 1),
}),
{ startImmediately: true },
);
// Each nudge waits out the interval first, so nothing fires immediately.
yield* TestClock.adjust(Duration.millis(999));
expect(yield* Ref.get(retries)).toBe(0);
yield* TestClock.adjust(Duration.millis(1));
expect(yield* Ref.get(retries)).toBe(1);
yield* TestClock.adjust(Duration.seconds(1));
expect(yield* Ref.get(retries)).toBe(2);
yield* Fiber.join(fiber);
}).pipe(Effect.provide(TestClock.layer())),
);
});
describe("server state projection", () => {
it("only treats a legacy transport interruption as an unacknowledged handoff", () => {
expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);
+12 -36
View File
@@ -149,35 +149,6 @@ export function validateServerUpdateReadyEvent(
);
}
/**
* Keeps reconnect attempts ~1s apart for the whole update restart.
*
* A restart takes the server down for ~15 seconds, but the supervisor's normal
* backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
* at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
* 33-second "Resuming". Nudging on every backoff entry (not just the first)
* holds the retry cadence flat until the server answers again. The sleep before
* each nudge is the pacer: a connection that fails instantly re-enters backoff
* immediately and would otherwise spin a tight retry loop.
*
* Callers fork this as a child of the update command so it is interrupted as
* soon as the update settles, whether it succeeds, fails, or times out.
*/
export function nudgeReconnectDuringUpdateRestart(input: {
readonly stateChanges: Stream.Stream<{ readonly phase: string }, unknown>;
readonly retryNow: Effect.Effect<void>;
readonly interval?: Duration.Duration;
}): Effect.Effect<void> {
return input.stateChanges.pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.runForEach(() =>
Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
),
Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
Effect.ignore,
);
}
export function serverUpdateStateForProgressEvent(
fromVersion: string,
targetVersion: string,
@@ -618,13 +589,18 @@ export function createServerEnvironmentAtoms<R, E>(
}),
);
// The update restart is intentional and the server stays unreachable
// for the whole restart, so hold the retry cadence flat instead of
// letting the supervisor climb its backoff ladder.
yield* nudgeReconnectDuringUpdateRestart({
stateChanges: environmentRegistry.stateChanges(target.environmentId),
retryNow: environmentRegistry.retryNow(target.environmentId),
}).pipe(Effect.forkChild);
// The update restart is intentional. As soon as the supervisor sees
// that first failed connection, discard any prior backoff debt and
// retry immediately instead of carrying an old 16-second delay.
yield* environmentRegistry.stateChanges(target.environmentId).pipe(
Stream.filter((state) => state.phase === "backoff"),
Stream.take(1),
Stream.runDrain,
Effect.andThen(environmentRegistry.retryNow(target.environmentId)),
Effect.timeoutOption(Duration.seconds(30)),
Effect.ignore,
Effect.forkChild,
);
const resumed = yield* environmentRegistry
.followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
+15 -1
View File
@@ -15,7 +15,11 @@ import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { createEnvironmentRpcCommand, createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
import {
createEnvironmentRpcCommand,
createEnvironmentRpcQueryAtomFamily,
createEnvironmentSubscriptionAtomFamily,
} from "./runtime.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
import { EnvironmentSupervisor } from "../connection/supervisor.ts";
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
@@ -270,6 +274,16 @@ export function createVcsEnvironmentAtoms<R, E>(
return {
listRefs,
// PR state per (cwd, branch), independent of the current checkout. The
// server funnels this into the same cached PR lookup that feeds status,
// so a warm badge costs no extra provider calls.
branchPr: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:vcs:branch-pr",
tag: WS_METHODS.vcsBranchPr,
staleTimeMs: 60_000,
idleTtlMs: 5 * 60_000,
refreshIntervalMs: 5 * 60_000,
}),
status: createEnvironmentSubscriptionAtomFamily(runtime, {
label: "environment-data:vcs:status",
subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
+19 -1
View File
@@ -188,9 +188,15 @@ export const VcsInitInput = Schema.Struct({
});
export type VcsInitInput = typeof VcsInitInput.Type;
export const VcsBranchPrInput = Schema.Struct({
cwd: TrimmedNonEmptyStringSchema,
branch: TrimmedNonEmptyStringSchema,
});
export type VcsBranchPrInput = typeof VcsBranchPrInput.Type;
// RPC Results
const VcsStatusChangeRequest = Schema.Struct({
export const VcsStatusChangeRequest = Schema.Struct({
number: PositiveInt,
title: TrimmedNonEmptyStringSchema,
url: Schema.String,
@@ -198,6 +204,7 @@ const VcsStatusChangeRequest = Schema.Struct({
headRef: TrimmedNonEmptyStringSchema,
state: VcsStatusChangeRequestState,
});
export type VcsStatusChangeRequest = typeof VcsStatusChangeRequest.Type;
const VcsStatusLocalShape = {
isRepo: Schema.Boolean,
@@ -253,6 +260,17 @@ export const VcsStatusStreamEvent = Schema.Union([
]);
export type VcsStatusStreamEvent = typeof VcsStatusStreamEvent.Type;
/**
* PR/MR state for one branch of a repository, independent of what is
* currently checked out at the cwd. This is what lets a thread keep its PR
* badge after the user (or another thread) switches the checkout elsewhere.
*/
export const VcsBranchPrResult = Schema.Struct({
branch: TrimmedNonEmptyStringSchema,
pr: Schema.NullOr(VcsStatusChangeRequest),
});
export type VcsBranchPrResult = typeof VcsBranchPrResult.Type;
export const VcsListRefsResult = Schema.Struct({
refs: Schema.Array(VcsRef),
isRepo: Schema.Boolean,
+10
View File
@@ -21,6 +21,8 @@ import {
import { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts";
import {
GitActionProgressEvent,
VcsBranchPrInput,
VcsBranchPrResult,
VcsSwitchRefInput,
VcsSwitchRefResult,
GitCommandError,
@@ -191,6 +193,7 @@ export const WS_METHODS = {
vcsCreateRef: "vcs.createRef",
vcsSwitchRef: "vcs.switchRef",
vcsInit: "vcs.init",
vcsBranchPr: "vcs.branchPr",
// Git workflow methods
gitRunStackedAction: "git.runStackedAction",
@@ -558,6 +561,12 @@ export const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {
error: Schema.Union([VcsError, EnvironmentAuthorizationError]),
});
export const WsVcsBranchPrRpc = Rpc.make(WS_METHODS.vcsBranchPr, {
payload: VcsBranchPrInput,
success: VcsBranchPrResult,
error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),
});
/**
* Ephemeral live diff preview for compact/mobile surfaces.
* Not the persisted T3 Review model. Future review sessions should use
@@ -838,6 +847,7 @@ export const WsRpcGroup = RpcGroup.make(
WsVcsCreateRefRpc,
WsVcsSwitchRefRpc,
WsVcsInitRpc,
WsVcsBranchPrRpc,
WsReviewGetDiffPreviewRpc,
WsReviewGetDiffFileContentsRpc,
WsTerminalOpenRpc,
+7 -51
View File
@@ -44,27 +44,17 @@ const PROJECT_SCRIPTS = JSON.stringify([
},
]);
const SHOWCASE_TERMINAL_PROMPT =
"\u001b[1;32m→\u001b[0m \u001b[1;36mt3code\u001b[0m \u001b[1;34mgit:(\u001b[1;31mfeat/remote-command-center\u001b[1;34m)\u001b[0m \u001b[1;33m✗\u001b[0m ";
// A dev-server startup mirroring the web settings' terminal font preview:
// zsh-style prompt, brand line, addresses, the thread's 612-test summary,
// and a READY badge, so the scene exercises bold, dim, underline, the six
// accent colors, and a background cell.
export const SHOWCASE_TERMINAL_BUFFER = [
`${SHOWCASE_TERMINAL_PROMPT}vpr dev`,
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m",
"$ vp test run --changed",
"",
" \u001b[1;32mVITE\u001b[0m \u001b[32mv7.1.1\u001b[0m \u001b[2mready in\u001b[0m \u001b[1m1.24s\u001b[0m",
" \u001b[38;5;117mt3code-mobile\u001b[0m 184 passed",
" \u001b[38;5;213mclient-runtime\u001b[0m 263 passed",
" \u001b[38;5;221mserver\u001b[0m 165 passed",
"",
" \u001b[32m→\u001b[0m \u001b[2mLocal:\u001b[0m \u001b[4;36mhttp://127.0.0.1:5173/\u001b[0m",
" \u001b[32m→\u001b[0m \u001b[2mNetwork:\u001b[0m \u001b[4;36mhttp://192.168.1.24:5173/\u001b[0m",
" \u001b[32m→\u001b[0m \u001b[2mProject:\u001b[0m \u001b[1mt3code\u001b[0m \u001b[2m— ~/Code/t3code\u001b[0m",
"\u001b[32m✨ 612 tests passed\u001b[0m · 3 environments online",
"",
" \u001b[32m✓ 612 passed\u001b[0m \u001b[33m△ 2 warnings\u001b[0m \u001b[31m✗ 0 failed\u001b[0m",
"",
" \u001b[42;30m READY \u001b[0m \u001b[2mwatching for changes — press\u001b[0m \u001b[1mq\u001b[0m \u001b[2mto quit\u001b[0m",
"",
SHOWCASE_TERMINAL_PROMPT,
"\u001b[38;5;75m~/Code/t3code\u001b[0m \u001b[38;5;212mfeat/remote-command-center\u001b[0m $ ",
].join("\r\n");
const BASE_ENVIRONMENT_PRESENCE = `export function environmentLabel(count: number): string {
@@ -571,40 +561,6 @@ function seedDatabase(
3,
minutesBefore(now, 4),
);
database
.prepare(
`INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, sequence, created_at
) VALUES (?, ?, ?, 'info', 'user-input.requested', ?, ?, ?, ?)`,
)
.run(
"choose-remote-environment",
SHOWCASE_THREAD_ID,
turnId,
"User input requested",
JSON.stringify({
requestId: "showcase-user-input",
questions: [
{
id: "environment",
header: "Environment",
question: "Which environment should receive the first remote handoff?",
options: [
{
label: "Moonbase",
description: "Use the primary T3 Code workspace.",
},
{
label: "Suspense Station",
description: "Use the React workspace.",
},
],
},
],
}),
4,
minutesBefore(now, 2),
);
for (const [index, projector] of PROJECTOR_NAMES.entries()) {
database