Migrate mobile UI to Uniwind and sheet-based thread routing

- Replace NativeWind styling with Uniwind tokens and helpers
- Split thread and git flows into nested sheet routes
- Add shared git state hooks and project favicon rendering
This commit is contained in:
Julius Marminge committed 2026-04-13 14:44:02 -07:00
1 parent 87d12d72a1
commit db30cdd26b
86 files changed
+4973 -4632

No files matched your search

@@ -6,6 +6,10 @@ import type {
ServerLifecycleWelcomePayload,
TerminalEvent,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import * as Option from "effect/Option";
import { pipe } from "effect/Function";
import type { KnownEnvironment } from "./knownEnvironment";
import type { WsRpcClient } from "./wsRpcClient";
@@ -137,14 +141,20 @@ function createOrchestrationRecoveryCoordinator() {
markEventBatchApplied<T extends Readonly<{ sequence: number }>>(
events: ReadonlyArray<T>,
): ReadonlyArray<T> {
const nextEvents = events
.filter((event) => event.sequence > state.latestSequence)
.toSorted((left, right) => left.sequence - right.sequence);
const nextEvents = pipe(
events,
Arr.filter((event) => event.sequence > state.latestSequence),
Arr.sortWith((event) => event.sequence, Order.Number),
);
if (nextEvents.length === 0) {
return [];
}
const latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;
const latestSequence = Arr.last(nextEvents).pipe(
Option.map((event) => event.sequence),
Option.getOrElse(() => state.latestSequence),
);
state = {
...state,
latestSequence,
@@ -0,0 +1,264 @@
import type {
GitActionProgressEvent,
GitCreateBranchResult,
GitCreateWorktreeResult,
GitCheckoutResult,
GitPullResult,
GitRunStackedActionResult,
GitStatusResult,
} from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
type GitActionClient,
createGitActionManager,
EMPTY_GIT_ACTION_STATE,
} from "./gitActionState";
let atomRegistry = AtomRegistry.make();
function resetAtomRegistry() {
atomRegistry.dispose();
atomRegistry = AtomRegistry.make();
}
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/test",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
function createPhaseStartedEvent(): Extract<GitActionProgressEvent, { kind: "phase_started" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "phase_started",
phase: "commit",
label: "Committing...",
};
}
function createHookStartedEvent(): Extract<GitActionProgressEvent, { kind: "hook_started" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "hook_started",
hookName: "post-commit",
};
}
function createHookOutputEvent(): Extract<GitActionProgressEvent, { kind: "hook_output" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "hook_output",
hookName: "post-commit",
stream: "stdout",
text: "hook output",
};
}
function createHookFinishedEvent(): Extract<GitActionProgressEvent, { kind: "hook_finished" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "hook_finished",
hookName: "post-commit",
exitCode: 0,
durationMs: 12,
};
}
function createActionFinishedEvent(): Extract<GitActionProgressEvent, { kind: "action_finished" }> {
return {
actionId: "action-123",
cwd: "/repo",
action: "commit_push",
kind: "action_finished",
result: {
action: "commit_push",
branch: { status: "skipped_not_requested" },
commit: { status: "created", commitSha: "abc123", subject: "Test commit" },
push: {
status: "pushed",
branch: "feature/test",
upstreamBranch: "origin/feature/test",
},
pr: { status: "skipped_not_requested" },
toast: {
title: "Done",
description: "Action finished",
cta: { kind: "none" },
},
} satisfies GitRunStackedActionResult,
};
}
function createMockClient() {
const refreshDeferred = createDeferred<GitStatusResult>();
const pullDeferred = createDeferred<GitPullResult>();
const checkoutDeferred = createDeferred<GitCheckoutResult>();
const createBranchDeferred = createDeferred<GitCreateBranchResult>();
const createWorktreeDeferred = createDeferred<GitCreateWorktreeResult>();
const initDeferred = createDeferred<void>();
const runStackedActionDeferred = createDeferred<GitRunStackedActionResult>();
let runStackedActionProgressListener: ((event: GitActionProgressEvent) => void) | null = null;
const client: GitActionClient = {
refreshStatus: vi.fn(() => refreshDeferred.promise),
pull: vi.fn(() => pullDeferred.promise),
checkout: vi.fn(() => checkoutDeferred.promise),
createBranch: vi.fn(() => createBranchDeferred.promise),
createWorktree: vi.fn(() => createWorktreeDeferred.promise),
init: vi.fn(() => initDeferred.promise),
runStackedAction: vi.fn((_, options) => {
runStackedActionProgressListener = options?.onProgress ?? null;
return runStackedActionDeferred.promise;
}),
};
return {
client,
refreshDeferred,
pullDeferred,
checkoutDeferred,
createBranchDeferred,
createWorktreeDeferred,
initDeferred,
runStackedActionDeferred,
emitProgress(event: GitActionProgressEvent) {
runStackedActionProgressListener?.(event);
},
};
}
describe("createGitActionManager", () => {
afterEach(() => {
resetAtomRegistry();
});
it("tracks refreshStatus progress and clears state on success", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const promise = manager.refreshStatus(TARGET, mock.client);
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: true,
operation: "refresh_status",
currentLabel: "Refreshing git status",
error: null,
});
mock.refreshDeferred.resolve(BASE_STATUS);
await expect(promise).resolves.toEqual(BASE_STATUS);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
});
it("tracks runStackedAction progress events", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
getActionId: () => "action-123",
});
const promise = manager.runStackedAction(
TARGET,
{ action: "commit_push", commitMessage: "Test commit" },
{ client: mock.client, gitStatus: BASE_STATUS },
);
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: true,
operation: "run_stacked_action",
actionId: "action-123",
currentLabel: "Committing...",
error: null,
});
mock.emitProgress(createPhaseStartedEvent());
expect(manager.getSnapshot(TARGET).currentLabel).toBe("Committing...");
mock.emitProgress(createHookStartedEvent());
expect(manager.getSnapshot(TARGET)).toMatchObject({
currentLabel: "Running post-commit...",
hookName: "post-commit",
isRunning: true,
});
mock.emitProgress(createHookOutputEvent());
expect(manager.getSnapshot(TARGET).lastOutputLine).toBe("hook output");
mock.emitProgress(createHookFinishedEvent());
expect(manager.getSnapshot(TARGET)).toMatchObject({
currentLabel: "Committing...",
hookName: null,
lastOutputLine: null,
});
const result = createActionFinishedEvent().result;
mock.runStackedActionDeferred.resolve(result);
await expect(promise).resolves.toEqual(result);
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
});
it("stores the error when an operation fails", async () => {
const mock = createMockClient();
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const promise = manager.pull(TARGET, mock.client);
mock.pullDeferred.reject(new Error("Pull failed."));
await expect(promise).rejects.toThrow("Pull failed.");
expect(manager.getSnapshot(TARGET)).toMatchObject({
isRunning: false,
operation: "pull",
currentLabel: null,
error: "Pull failed.",
});
});
it("returns null when no client is available", async () => {
const manager = createGitActionManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
await expect(manager.checkout(TARGET, { branch: "main" })).resolves.toBeNull();
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_ACTION_STATE);
});
});
@@ -0,0 +1,444 @@
import type {
GitActionProgressEvent,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitCheckoutInput,
GitCheckoutResult,
GitPullInput,
GitPullResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
} from "@t3tools/contracts";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import { buildGitActionProgressStages } from "./gitActions";
import type { WsRpcClient } from "./wsRpcClient";
export type GitActionOperation =
| "refresh_status"
| "run_stacked_action"
| "pull"
| "checkout"
| "create_branch"
| "create_worktree"
| "init";
export interface GitActionState {
readonly isRunning: boolean;
readonly operation: GitActionOperation | null;
readonly actionId: string | null;
readonly action: GitStackedAction | null;
readonly currentLabel: string | null;
readonly currentPhaseLabel: string | null;
readonly hookName: string | null;
readonly lastOutputLine: string | null;
readonly phaseStartedAtMs: number | null;
readonly hookStartedAtMs: number | null;
readonly error: string | null;
}
export interface GitActionTarget {
readonly environmentId: string | null;
readonly cwd: string | null;
}
export type GitActionClient = Pick<
WsRpcClient["git"],
| "refreshStatus"
| "runStackedAction"
| "pull"
| "checkout"
| "createBranch"
| "createWorktree"
| "init"
>;
export const EMPTY_GIT_ACTION_STATE = Object.freeze<GitActionState>({
isRunning: false,
operation: null,
actionId: null,
action: null,
currentLabel: null,
currentPhaseLabel: null,
hookName: null,
lastOutputLine: null,
phaseStartedAtMs: null,
hookStartedAtMs: null,
error: null,
});
const knownGitActionKeys = new Set<string>();
export const gitActionStateAtom = Atom.family((key: string) => {
knownGitActionKeys.add(key);
return Atom.make(EMPTY_GIT_ACTION_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-action:${key}`),
);
});
export const EMPTY_GIT_ACTION_ATOM = Atom.make(EMPTY_GIT_ACTION_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-action:null"),
);
export function getGitActionTargetKey(target: GitActionTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
return `${target.environmentId}:${target.cwd}`;
}
export function applyGitActionProgressEvent(
current: GitActionState,
event: GitActionProgressEvent,
): GitActionState {
const now = Date.now();
switch (event.kind) {
case "action_started":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
phaseStartedAtMs: now,
hookStartedAtMs: null,
hookName: null,
lastOutputLine: null,
error: null,
};
case "phase_started":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
currentLabel: event.label,
currentPhaseLabel: event.label,
phaseStartedAtMs: now,
hookStartedAtMs: null,
hookName: null,
lastOutputLine: null,
error: null,
};
case "hook_started":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
currentLabel: `Running ${event.hookName}...`,
hookName: event.hookName,
hookStartedAtMs: now,
lastOutputLine: null,
error: null,
};
case "hook_output":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
lastOutputLine: event.text,
error: null,
};
case "hook_finished":
return {
...current,
isRunning: true,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
currentLabel: current.currentPhaseLabel,
hookName: null,
hookStartedAtMs: null,
lastOutputLine: null,
error: null,
};
case "action_finished":
return {
...current,
isRunning: false,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
error: null,
};
case "action_failed":
return {
...EMPTY_GIT_ACTION_STATE,
actionId: event.actionId,
action: event.action,
operation: "run_stacked_action",
error: event.message,
};
}
}
export interface GitActionManagerConfig {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (environmentId: string) => GitActionClient | null;
readonly getActionId?: () => string;
}
export function createGitActionManager(config: GitActionManagerConfig) {
function setState(targetKey: string, nextState: GitActionState): void {
config.getRegistry().set(gitActionStateAtom(targetKey), nextState);
}
function startOperation(
targetKey: string,
input: {
readonly operation: GitActionOperation;
readonly actionId?: string;
readonly action?: GitStackedAction;
readonly label: string;
},
): void {
setState(targetKey, {
isRunning: true,
operation: input.operation,
actionId: input.actionId ?? null,
action: input.action ?? null,
currentLabel: input.label,
currentPhaseLabel: input.label,
hookName: null,
lastOutputLine: null,
phaseStartedAtMs: Date.now(),
hookStartedAtMs: null,
error: null,
});
}
function finishOperation(targetKey: string): void {
setState(targetKey, EMPTY_GIT_ACTION_STATE);
}
function failOperation(
targetKey: string,
error: unknown,
input: {
readonly operation: GitActionOperation;
readonly actionId?: string;
readonly action?: GitStackedAction;
},
): void {
setState(targetKey, {
...EMPTY_GIT_ACTION_STATE,
operation: input.operation,
actionId: input.actionId ?? null,
action: input.action ?? null,
error: error instanceof Error ? error.message : "Git action failed.",
});
}
async function runOperation<TResult>(
target: GitActionTarget,
input: {
readonly operation: GitActionOperation;
readonly label: string;
readonly actionId?: string;
readonly action?: GitStackedAction;
readonly client?: GitActionClient | undefined;
readonly execute: (client: GitActionClient) => Promise<TResult>;
},
): Promise<TResult | null> {
const targetKey = getGitActionTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return null;
}
const resolved = input.client ?? config.getClient(target.environmentId);
if (!resolved) {
return null;
}
startOperation(targetKey, input);
try {
const result = await input.execute(resolved);
finishOperation(targetKey);
return result;
} catch (error) {
failOperation(targetKey, error, input);
throw error;
}
}
function getSnapshot(target: GitActionTarget): GitActionState {
const targetKey = getGitActionTargetKey(target);
if (targetKey === null) {
return EMPTY_GIT_ACTION_STATE;
}
return config.getRegistry().get(gitActionStateAtom(targetKey));
}
async function refreshStatus(
target: GitActionTarget,
client?: GitActionClient,
options?: { readonly quiet?: boolean },
): Promise<Awaited<ReturnType<GitActionClient["refreshStatus"]>> | null> {
if (options?.quiet) {
if (target.environmentId === null || target.cwd === null) {
return null;
}
const resolved = client ?? config.getClient(target.environmentId);
return resolved ? resolved.refreshStatus({ cwd: target.cwd }) : null;
}
return runOperation(target, {
operation: "refresh_status",
label: "Refreshing git status",
client,
execute: (resolved) => resolved.refreshStatus({ cwd: target.cwd! }),
});
}
async function pull(
target: GitActionTarget,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitPullResult | null> {
return runOperation(target, {
operation: "pull",
label: options?.label ?? "Pulling latest changes",
client,
execute: (resolved) => resolved.pull({ cwd: target.cwd! } satisfies GitPullInput),
});
}
async function checkout(
target: GitActionTarget,
input: Omit<GitCheckoutInput, "cwd">,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitCheckoutResult | null> {
return runOperation(target, {
operation: "checkout",
label: options?.label ?? "Checking out branch",
client,
execute: (resolved) => resolved.checkout({ cwd: target.cwd!, ...input }),
});
}
async function createBranch(
target: GitActionTarget,
input: Omit<GitCreateBranchInput, "cwd">,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitCreateBranchResult | null> {
return runOperation(target, {
operation: "create_branch",
label: options?.label ?? "Creating branch",
client,
execute: (resolved) => resolved.createBranch({ cwd: target.cwd!, ...input }),
});
}
async function createWorktree(
target: GitActionTarget,
input: Omit<GitCreateWorktreeInput, "cwd">,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<GitCreateWorktreeResult | null> {
return runOperation(target, {
operation: "create_worktree",
label: options?.label ?? "Creating worktree",
client,
execute: (resolved) => resolved.createWorktree({ cwd: target.cwd!, ...input }),
});
}
async function init(
target: GitActionTarget,
client?: GitActionClient,
options?: { readonly label?: string },
): Promise<Awaited<ReturnType<GitActionClient["init"]>> | null> {
return runOperation(target, {
operation: "init",
label: options?.label ?? "Initializing git repository",
client,
execute: (resolved) => resolved.init({ cwd: target.cwd! }),
});
}
async function runStackedAction(
target: GitActionTarget,
input: Omit<GitRunStackedActionInput, "cwd" | "actionId"> & { readonly actionId?: string },
options?: {
readonly client?: GitActionClient;
readonly gitStatus?: GitStatusResult | null;
readonly onProgress?: (event: GitActionProgressEvent) => void;
},
): Promise<GitRunStackedActionResult | null> {
const actionId =
input.actionId ??
config.getActionId?.() ??
`git-action-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const targetKey = getGitActionTargetKey(target);
return runOperation(target, {
operation: "run_stacked_action",
label:
buildGitActionProgressStages({
action: input.action,
hasCustomCommitMessage: Boolean(input.commitMessage?.trim()),
hasWorkingTreeChanges: options?.gitStatus?.hasWorkingTreeChanges ?? false,
featureBranch: input.featureBranch ?? false,
shouldPushBeforePr:
input.action === "create_pr" &&
(!(options?.gitStatus?.hasUpstream ?? false) ||
(options?.gitStatus?.aheadCount ?? 0) > 0),
})[0] ?? "Running git action",
actionId,
action: input.action,
client: options?.client,
execute: async (resolved) => {
const result = await resolved.runStackedAction(
{
cwd: target.cwd!,
actionId,
...input,
},
{
onProgress: (event) => {
if (targetKey !== null) {
const current = getSnapshot(target);
setState(targetKey, applyGitActionProgressEvent(current, event));
}
options?.onProgress?.(event);
},
},
);
return result;
},
});
}
function reset(): void {
for (const key of knownGitActionKeys) {
setState(key, EMPTY_GIT_ACTION_STATE);
}
}
return {
getSnapshot,
refreshStatus,
pull,
checkout,
createBranch,
createWorktree,
init,
runStackedAction,
reset,
};
}
@@ -0,0 +1,161 @@
import type { GitListBranchesResult } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
createGitBranchManager,
EMPTY_GIT_BRANCH_STATE,
gitBranchStateAtom,
type GitBranchClient,
} from "./gitBranchState";
let atomRegistry = AtomRegistry.make();
function resetAtomRegistry() {
atomRegistry.dispose();
atomRegistry = AtomRegistry.make();
}
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
const FIRST_PAGE: GitListBranchesResult = {
branches: [
{ name: "main", current: true, isDefault: true, worktreePath: null },
{ name: "feature/a", current: false, isDefault: false, worktreePath: null },
],
isRepo: true,
hasOriginRemote: true,
nextCursor: 2,
totalCount: 3,
};
const SECOND_PAGE: GitListBranchesResult = {
branches: [{ name: "feature/b", current: false, isDefault: false, worktreePath: null }],
isRepo: true,
hasOriginRemote: true,
nextCursor: null,
totalCount: 3,
};
function createMockClient() {
const listBranches = vi.fn(async (input: Parameters<GitBranchClient["listBranches"]>[0]) => {
if (input.query === "feature") {
return {
...FIRST_PAGE,
branches: FIRST_PAGE.branches.filter((branch) => branch.name.includes("feature")),
nextCursor: null,
totalCount: 2,
} satisfies GitListBranchesResult;
}
if (input.cursor === 2) {
return SECOND_PAGE;
}
return FIRST_PAGE;
});
return {
client: { listBranches } satisfies GitBranchClient,
listBranches,
};
}
describe("createGitBranchManager", () => {
afterEach(() => {
resetAtomRegistry();
});
it("loads the first page and stores it in atom state", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const promise = manager.load(TARGET, mock.client, { limit: 100 });
expect(manager.getSnapshot(TARGET)).toEqual({
data: null,
isPending: true,
error: null,
});
await expect(promise).resolves.toEqual(FIRST_PAGE);
expect(manager.getSnapshot(TARGET)).toEqual({
data: FIRST_PAGE,
isPending: false,
error: null,
});
expect(mock.listBranches).toHaveBeenCalledWith({ cwd: "/repo", limit: 100 });
});
it("loads the next page and appends branches", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
await manager.load(TARGET, mock.client);
const next = await manager.loadNext(TARGET, mock.client);
expect(next).toEqual({
...SECOND_PAGE,
branches: [...FIRST_PAGE.branches, ...SECOND_PAGE.branches],
});
expect(manager.getSnapshot(TARGET)).toEqual({
data: {
...SECOND_PAGE,
branches: [...FIRST_PAGE.branches, ...SECOND_PAGE.branches],
},
isPending: false,
error: null,
});
});
it("stores query-specific state independently", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
const queriedTarget = { ...TARGET, query: "feature" } as const;
const queried = await manager.load(queriedTarget, mock.client);
expect(queried?.branches.map((branch) => branch.name)).toEqual(["feature/a"]);
expect(manager.getSnapshot(TARGET).data).toBeNull();
expect(manager.getSnapshot(queriedTarget).data?.branches.map((branch) => branch.name)).toEqual([
"feature/a",
]);
});
it("returns cached data when no client is available", async () => {
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
atomRegistry.set(gitBranchStateAtom("env-local:/repo:"), {
data: FIRST_PAGE,
isPending: false,
error: null,
});
await expect(manager.load(TARGET)).resolves.toEqual(FIRST_PAGE);
});
it("resets state", async () => {
const mock = createMockClient();
const manager = createGitBranchManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
await manager.load(TARGET, mock.client);
manager.reset();
expect(manager.getSnapshot(TARGET)).toEqual(EMPTY_GIT_BRANCH_STATE);
});
});
@@ -0,0 +1,227 @@
import type { GitBranch, GitListBranchesInput, GitListBranchesResult } from "@t3tools/contracts";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import type { WsRpcClient } from "./wsRpcClient";
export interface GitBranchTarget {
readonly environmentId: string | null;
readonly cwd: string | null;
readonly query?: string | null;
}
export interface GitBranchState {
readonly data: GitListBranchesResult | null;
readonly isPending: boolean;
readonly error: string | null;
}
export type GitBranchClient = Pick<WsRpcClient["git"], "listBranches">;
export const EMPTY_GIT_BRANCH_STATE = Object.freeze<GitBranchState>({
data: null,
isPending: false,
error: null,
});
const INITIAL_GIT_BRANCH_STATE = Object.freeze<GitBranchState>({
data: null,
isPending: true,
error: null,
});
const knownGitBranchKeys = new Set<string>();
export const gitBranchStateAtom = Atom.family((key: string) => {
knownGitBranchKeys.add(key);
return Atom.make(EMPTY_GIT_BRANCH_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-branches:${key}`),
);
});
export const EMPTY_GIT_BRANCH_ATOM = Atom.make(EMPTY_GIT_BRANCH_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-branches:null"),
);
function normalizeQuery(query: string | null | undefined): string {
return query?.trim() ?? "";
}
export function getGitBranchTargetKey(target: GitBranchTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
return `${target.environmentId}:${target.cwd}:${normalizeQuery(target.query)}`;
}
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : "Failed to load branches.";
}
function mergeBranches(
previous: ReadonlyArray<GitBranch>,
next: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const merged = new Map<string, GitBranch>();
for (const branch of previous) {
merged.set(branch.name, branch);
}
for (const branch of next) {
merged.set(branch.name, branch);
}
return [...merged.values()];
}
export interface GitBranchManagerConfig {
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly getClient: (environmentId: string) => GitBranchClient | null;
}
export function createGitBranchManager(config: GitBranchManagerConfig) {
const inFlight = new Map<string, Promise<GitListBranchesResult | null>>();
function getSnapshot(target: GitBranchTarget): GitBranchState {
const targetKey = getGitBranchTargetKey(target);
if (targetKey === null) {
return EMPTY_GIT_BRANCH_STATE;
}
return config.getRegistry().get(gitBranchStateAtom(targetKey));
}
function setState(targetKey: string, nextState: GitBranchState): void {
config.getRegistry().set(gitBranchStateAtom(targetKey), nextState);
}
function markPending(targetKey: string): void {
const current = config.getRegistry().get(gitBranchStateAtom(targetKey));
setState(
targetKey,
current.data === null
? INITIAL_GIT_BRANCH_STATE
: { ...current, isPending: true, error: null },
);
}
function setData(targetKey: string, data: GitListBranchesResult): void {
setState(targetKey, {
data,
isPending: false,
error: null,
});
}
function setError(targetKey: string, error: unknown): void {
const current = config.getRegistry().get(gitBranchStateAtom(targetKey));
setState(targetKey, {
data: current.data,
isPending: false,
error: toErrorMessage(error),
});
}
async function load(
target: GitBranchTarget,
client?: GitBranchClient,
options?: {
readonly cursor?: number;
readonly limit?: number;
readonly append?: boolean;
},
): Promise<GitListBranchesResult | null> {
const targetKey = getGitBranchTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return null;
}
const resolved = client ?? config.getClient(target.environmentId);
if (!resolved) {
return getSnapshot(target).data;
}
const inFlightKey = `${targetKey}:${options?.cursor ?? "start"}:${options?.append ? "append" : "replace"}`;
const existing = inFlight.get(inFlightKey);
if (existing) {
return existing;
}
markPending(targetKey);
const current = getSnapshot(target).data;
const request: GitListBranchesInput = {
cwd: target.cwd,
...(normalizeQuery(target.query).length > 0 ? { query: normalizeQuery(target.query) } : {}),
...(options?.cursor !== undefined ? { cursor: options.cursor } : {}),
...(options?.limit !== undefined ? { limit: options.limit } : {}),
};
const promise = resolved.listBranches(request).then(
(result) => {
const nextData =
options?.append && current
? {
...result,
branches: mergeBranches(current.branches, result.branches),
}
: result;
setData(targetKey, nextData);
return nextData;
},
(error) => {
setError(targetKey, error);
throw error;
},
);
inFlight.set(inFlightKey, promise);
try {
return await promise;
} finally {
inFlight.delete(inFlightKey);
}
}
async function loadNext(
target: GitBranchTarget,
client?: GitBranchClient,
options?: { readonly limit?: number },
): Promise<GitListBranchesResult | null> {
const current = getSnapshot(target).data;
if (!current?.nextCursor && current?.nextCursor !== 0) {
return current ?? null;
}
return load(target, client, {
cursor: current.nextCursor,
append: true,
...(options?.limit !== undefined ? { limit: options.limit } : {}),
});
}
function invalidate(target?: GitBranchTarget): void {
if (target) {
const targetKey = getGitBranchTargetKey(target);
if (targetKey !== null) {
setState(targetKey, EMPTY_GIT_BRANCH_STATE);
}
return;
}
for (const key of knownGitBranchKeys) {
setState(key, EMPTY_GIT_BRANCH_STATE);
}
}
function reset(): void {
invalidate();
}
return {
getSnapshot,
load,
loadNext,
invalidate,
reset,
};
}
@@ -0,0 +1,330 @@
import type { GitStatusResult } from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, describe, expect, it, vi } from "vitest";
import { type GitStatusClient, createGitStatusManager } from "./gitStatusState";
/* ─── Test helpers ──────────────────────────────────────────────────── */
let atomRegistry = AtomRegistry.make();
function resetAtomRegistry() {
atomRegistry.dispose();
atomRegistry = AtomRegistry.make();
}
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const BASE_STATUS: GitStatusResult = {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/push-status",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
function createMockClient(): {
client: GitStatusClient;
listeners: Set<(event: GitStatusResult) => void>;
emit: (event: GitStatusResult) => void;
} {
const listeners = new Set<(event: GitStatusResult) => void>();
const client: GitStatusClient = {
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(listeners, listener),
),
};
return {
client,
listeners,
emit: (event) => {
for (const listener of listeners) listener(event);
},
};
}
const PENDING = { data: null, error: null, cause: null, isPending: true };
const EMPTY = { data: null, error: null, cause: null, isPending: false };
const TARGET = { environmentId: "env-local", cwd: "/repo" } as const;
const FRESH_TARGET = { environmentId: "env-local", cwd: "/fresh" } as const;
const OTHER_ENV_TARGET = { environmentId: "env-remote", cwd: "/repo" } as const;
/* ─── Tests ─────────────────────────────────────────────────────────── */
describe("createGitStatusManager", () => {
afterEach(() => {
resetAtomRegistry();
});
describe("with explicit client (no reconnection)", () => {
it("starts in a pending state when watching", () => {
const { client } = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
manager.watch(TARGET, client);
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
manager.reset();
});
it("shares one subscription per cwd and updates the snapshot", () => {
const { client, listeners, emit } = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const releaseA = manager.watch(TARGET, client);
const releaseB = manager.watch(TARGET, client);
expect(client.onStatus).toHaveBeenCalledOnce();
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
releaseA();
expect(listeners.size).toBe(1);
releaseB();
expect(listeners.size).toBe(0);
});
it("refreshes via unary RPC without restarting the stream", async () => {
const { client, emit } = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const release = manager.watch(TARGET, client);
emit(BASE_STATUS);
const refreshed = await manager.refresh(TARGET, client);
expect(client.onStatus).toHaveBeenCalledOnce();
expect(client.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
// Snapshot still reflects stream data, not the refresh response
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
it("keeps subscriptions isolated by environment when cwds match", () => {
const local = createMockClient();
const remote = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const releaseLocal = manager.watch(TARGET, local.client);
const releaseRemote = manager.watch(OTHER_ENV_TARGET, remote.client);
local.emit(BASE_STATUS);
remote.emit({ ...BASE_STATUS, branch: "remote-branch" });
expect(manager.getSnapshot(TARGET).data?.branch).toBe("feature/push-status");
expect(manager.getSnapshot(OTHER_ENV_TARGET).data?.branch).toBe("remote-branch");
releaseLocal();
releaseRemote();
});
it("returns null from refresh when no client is available", async () => {
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
await expect(manager.refresh(TARGET)).resolves.toBeNull();
});
it("returns empty state for null targets", () => {
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
expect(manager.getSnapshot({ environmentId: null, cwd: null })).toEqual(EMPTY);
});
});
describe("with subscribeClientChanges (reconnection)", () => {
it("waits for a delayed client registration", () => {
const connectionListeners = new Set<() => void>();
const clients = new Map<string, ReturnType<typeof createMockClient>>();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => clients.get(envId)?.client ?? null,
getClientIdentity: (envId) => (clients.has(envId) ? envId : null),
subscribeClientChanges: (listener) => {
connectionListeners.add(listener);
return () => connectionListeners.delete(listener);
},
});
const release = manager.watch(TARGET);
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
// Register the client
const mock = createMockClient();
clients.set("env-local", mock);
for (const listener of connectionListeners) listener();
mock.emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: false,
});
release();
});
it("resubscribes after client is removed and re-registered", () => {
const connectionListeners = new Set<() => void>();
const clients = new Map<string, ReturnType<typeof createMockClient>>();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => clients.get(envId)?.client ?? null,
getClientIdentity: (envId) =>
clients.get(envId) ? `identity:${envId}:${clients.size}` : null,
subscribeClientChanges: (listener) => {
connectionListeners.add(listener);
return () => connectionListeners.delete(listener);
},
});
// Register first client and watch
const first = createMockClient();
clients.set("env-local", first);
const release = manager.watch(TARGET);
first.emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET).data?.branch).toBe("feature/push-status");
// Remove client
clients.delete("env-local");
for (const listener of connectionListeners) listener();
expect(manager.getSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
cause: null,
isPending: true,
});
// Register new client (different identity)
const second = createMockClient();
clients.set("env-local", second);
for (const listener of connectionListeners) listener();
second.emit({ ...BASE_STATUS, branch: "reconnected-branch" });
expect(manager.getSnapshot(TARGET).data?.branch).toBe("reconnected-branch");
release();
});
it("cleans up connection listener on unwatch", () => {
const connectionListeners = new Set<() => void>();
const mock = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
getClientIdentity: () => "id",
subscribeClientChanges: (listener) => {
connectionListeners.add(listener);
return () => connectionListeners.delete(listener);
},
});
const release = manager.watch(TARGET);
expect(connectionListeners.size).toBe(1);
release();
expect(connectionListeners.size).toBe(0);
expect(mock.listeners.size).toBe(0);
});
});
describe("with getClient config (one-shot)", () => {
it("resolves client from config and subscribes", () => {
const mock = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: (envId) => (envId === "env-local" ? mock.client : null),
});
const release = manager.watch(TARGET);
expect(mock.client.onStatus).toHaveBeenCalledOnce();
mock.emit(BASE_STATUS);
expect(manager.getSnapshot(TARGET).data?.branch).toBe("feature/push-status");
release();
expect(mock.listeners.size).toBe(0);
});
it("returns noop when client is not available", () => {
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => null,
});
const release = manager.watch(TARGET);
expect(manager.getSnapshot(TARGET)).toEqual(PENDING);
release(); // should not throw
});
});
describe("reset", () => {
it("tears down all active subscriptions", () => {
const mock = createMockClient();
const manager = createGitStatusManager({
getRegistry: () => atomRegistry,
getClient: () => mock.client,
});
manager.watch(TARGET);
manager.watch(FRESH_TARGET);
expect(mock.listeners.size).toBe(2);
manager.reset();
expect(mock.listeners.size).toBe(0);
});
});
});
@@ -0,0 +1,289 @@
import type { GitManagerServiceError, GitStatusResult } from "@t3tools/contracts";
import type { Cause } from "effect";
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
import type { WsRpcClient } from "./wsRpcClient";
/* ─── Types ─────────────────────────────────────────────────────────── */
export interface GitStatusState {
readonly data: GitStatusResult | null;
readonly error: GitManagerServiceError | null;
readonly cause: Cause.Cause<GitManagerServiceError> | null;
readonly isPending: boolean;
}
export interface GitStatusTarget {
readonly environmentId: string | null;
readonly cwd: string | null;
}
export type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
interface WatchedEntry {
refCount: number;
teardown: () => void;
}
/* ─── Constants ─────────────────────────────────────────────────────── */
const NOOP: () => void = () => undefined;
export const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
data: null,
error: null,
cause: null,
isPending: true,
});
/* ─── Atoms ─────────────────────────────────────────────────────────── */
const knownGitStatusKeys = new Set<string>();
export const gitStatusStateAtom = Atom.family((key: string) => {
knownGitStatusKeys.add(key);
return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-status:${key}`),
);
});
export const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status:null"),
);
/* ─── Helpers ───────────────────────────────────────────────────────── */
export function getGitStatusTargetKey(target: GitStatusTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
return `${target.environmentId}:${target.cwd}`;
}
/* ─── Subscription manager ──────────────────────────────────────────── */
export interface GitStatusManagerConfig {
/**
* Get the atom registry to read/write git status atoms.
*/
readonly getRegistry: () => AtomRegistry.AtomRegistry;
/** Resolve a git client for an environment. */
readonly getClient: (environmentId: string) => GitStatusClient | null;
/**
* Optional: get a stable identity for the current client.
* Used to detect reconnections — when the identity changes the
* manager tears down the old `onStatus` stream and subscribes anew.
*/
readonly getClientIdentity?: (environmentId: string) => string | null;
/**
* Optional: subscribe to environment-connection changes.
* When provided the manager reacts to client appear / disappear /
* reconnect events instead of doing a one-shot resolution.
*/
readonly subscribeClientChanges?: (listener: () => void) => () => void;
}
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
export function createGitStatusManager(config: GitStatusManagerConfig) {
const watched = new Map<string, WatchedEntry>();
const refreshInFlight = new Map<string, Promise<GitStatusResult>>();
const lastRefreshAt = new Map<string, number>();
/* ── Atom helpers ───────────────────────────────────────────────── */
function markPending(targetKey: string): void {
const atom = gitStatusStateAtom(targetKey);
const current = config.getRegistry().get(atom);
const next: GitStatusState =
current.data === null
? INITIAL_GIT_STATUS_STATE
: { ...current, error: null, cause: null, isPending: true };
if (
current.data === next.data &&
current.error === next.error &&
current.cause === next.cause &&
current.isPending === next.isPending
) {
return;
}
config.getRegistry().set(atom, next);
}
function setData(targetKey: string, status: GitStatusResult): void {
config.getRegistry().set(gitStatusStateAtom(targetKey), {
data: status,
error: null,
cause: null,
isPending: false,
});
}
/* ── Core subscription ──────────────────────────────────────────── */
function subscribeStream(targetKey: string, cwd: string, client: GitStatusClient): () => void {
markPending(targetKey);
return client.onStatus({ cwd }, (status) => setData(targetKey, status), {
onResubscribe: () => markPending(targetKey),
});
}
/* ── Dynamic subscription (handles reconnection) ────────────────── */
function createDynamicSubscription(targetKey: string, target: GitStatusTarget): () => void {
const environmentId = target.environmentId!;
const cwd = target.cwd!;
let currentIdentity: string | null = null;
let currentUnsub = NOOP;
const sync = () => {
const client = config.getClient(environmentId);
const identity = client ? (config.getClientIdentity?.(environmentId) ?? environmentId) : null;
if (!client || identity === null) {
if (currentIdentity !== null) {
currentUnsub();
currentUnsub = NOOP;
currentIdentity = null;
}
markPending(targetKey);
return;
}
if (currentIdentity === identity) return;
currentUnsub();
currentIdentity = identity;
currentUnsub = subscribeStream(targetKey, cwd, client);
};
const unsubChanges = config.subscribeClientChanges!(sync);
sync();
return () => {
unsubChanges();
currentUnsub();
};
}
/* ── Public API ─────────────────────────────────────────────────── */
/**
* Begin watching git status for `target`.
*
* Multiple watchers sharing the same `environmentId:cwd` key share
* one `onStatus` WS subscription (ref-counted).
*
* @param target The environment + cwd to watch.
* @param client Optional pre-resolved client — skips `getClient`
* lookup and reconnection handling. Useful in tests.
* @returns An unwatch function.
*/
function watch(target: GitStatusTarget, client?: GitStatusClient): () => void {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null || target.environmentId === null || target.cwd === null) {
return NOOP;
}
const existing = watched.get(targetKey);
if (existing) {
existing.refCount += 1;
return () => unwatch(targetKey);
}
let teardown: () => void;
if (client) {
// Explicit client — direct subscription, no reconnection handling.
teardown = subscribeStream(targetKey, target.cwd, client);
} else if (config.subscribeClientChanges) {
// Dynamic client — subscribe to connection changes for reconnection.
teardown = createDynamicSubscription(targetKey, target);
} else {
// One-shot client resolution.
const resolved = config.getClient(target.environmentId);
if (!resolved) return NOOP;
teardown = subscribeStream(targetKey, target.cwd, resolved);
}
watched.set(targetKey, { refCount: 1, teardown });
return () => unwatch(targetKey);
}
function unwatch(targetKey: string): void {
const entry = watched.get(targetKey);
if (!entry) return;
entry.refCount -= 1;
if (entry.refCount > 0) return;
entry.teardown();
watched.delete(targetKey);
}
/**
* Trigger a one-shot `refreshStatus` RPC for a target.
* Debounced (1 s) and deduplicated (in-flight).
* The server-side refresh pushes a new event on the existing
* `onStatus` stream, so the subscription picks it up automatically.
*/
function refresh(
target: GitStatusTarget,
client?: GitStatusClient,
): Promise<GitStatusResult | null> {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null || target.cwd === null) {
return Promise.resolve(null);
}
const resolved =
client ?? (target.environmentId ? config.getClient(target.environmentId) : null);
if (!resolved) {
return Promise.resolve(getSnapshot(target).data);
}
const existing = refreshInFlight.get(targetKey);
if (existing) return existing;
const last = lastRefreshAt.get(targetKey) ?? 0;
if (Date.now() - last < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getSnapshot(target).data);
}
lastRefreshAt.set(targetKey, Date.now());
const promise = resolved
.refreshStatus({ cwd: target.cwd })
.finally(() => refreshInFlight.delete(targetKey));
refreshInFlight.set(targetKey, promise);
return promise;
}
function getSnapshot(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null) return EMPTY_GIT_STATUS_STATE;
return config.getRegistry().get(gitStatusStateAtom(targetKey));
}
function reset(): void {
for (const entry of watched.values()) {
entry.teardown();
}
watched.clear();
refreshInFlight.clear();
lastRefreshAt.clear();
for (const key of knownGitStatusKeys) {
config.getRegistry().set(gitStatusStateAtom(key), INITIAL_GIT_STATUS_STATE);
}
knownGitStatusKeys.clear();
}
return { watch, refresh, getSnapshot, reset };
}
+3
View File
@@ -1,6 +1,9 @@
export * from "./knownEnvironment";
export * from "./scoped";
export * from "./gitActions";
export * from "./gitActionState";
export * from "./gitBranchState";
export * from "./gitStatusState";
export * from "./wsRpcProtocol";
export * from "./wsTransport";
export * from "./wsRpcClient";