Compare commits

..
Author SHA1 Message Date
Julius Marminge fd4c354212 Route environment RPC through shared atom registry
- Reuse the app atom registry for environment RPC atoms
- Add a fallback path for server settings updates when the runtime is unavailable
- Remove per-runtime registry ownership from the client runtime
2026-05-05 21:00:42 -07:00
Julius Marminge 8c48db4409 Extract shared RPC atom runtime helpers
- Move environment RPC setup into `packages/client-runtime`
- Replace web-side server atom indirection with shared helpers
- Remove obsolete `serverAtomRpc` wrapper
2026-05-05 20:47:50 -07:00
Julius Marminge 6f585399bd Wire environment runtime through atom RPC
- Add environment and server atom RPC clients
- Split websocket lifecycle handlers for primary and saved environments
- Reset and dispose atom registries alongside websocket reconnects
2026-05-05 20:40:10 -07:00
15 changed files with 465 additions and 199 deletions

No files matched your search

+1 -2
View File
@@ -72,7 +72,6 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import * as Effect from "effect/Effect";
import {
selectProjectsAcrossEnvironments,
selectThreadsAcrossEnvironments,
@@ -2846,7 +2845,7 @@ export default function ChatView(props: ChatViewProps) {
prepareWorktree: {
projectCwd: activeProject.cwd,
baseBranch: baseBranchForWorktree,
branch: Effect.runSync(buildTemporaryWorktreeBranchName),
branch: buildTemporaryWorktreeBranchName(),
},
runSetupScript: true,
}
@@ -9,12 +9,14 @@ import type {
import type { KnownEnvironment } from "@t3tools/client-runtime";
import type { WsRpcClient } from "~/rpc/wsRpcClient";
import type { EnvironmentAtomRpcClient } from "~/rpc/environmentAtomRpc";
export interface EnvironmentConnection {
readonly kind: "primary" | "saved";
readonly environmentId: EnvironmentId;
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly atomRpc?: EnvironmentAtomRpcClient;
readonly ensureBootstrapped: () => Promise<void>;
readonly reconnect: () => Promise<void>;
readonly dispose: () => Promise<void>;
@@ -36,6 +38,7 @@ interface EnvironmentConnectionInput extends OrchestrationHandlers {
readonly kind: "primary" | "saved";
readonly knownEnvironment: KnownEnvironment;
readonly client: WsRpcClient;
readonly atomRpc?: EnvironmentAtomRpcClient;
readonly refreshMetadata?: () => Promise<void>;
readonly onConfigSnapshot?: (config: ServerConfig) => void;
readonly onWelcome?: (payload: ServerLifecycleWelcomePayload) => void;
@@ -162,9 +165,11 @@ export function createEnvironmentConnection(
environmentId,
knownEnvironment: input.knownEnvironment,
client: input.client,
...(input.atomRpc ? { atomRpc: input.atomRpc } : {}),
ensureBootstrapped: () => bootstrapGate.wait(),
reconnect: async () => {
bootstrapGate.reset();
input.atomRpc?.reset();
try {
await input.client.reconnect();
await input.refreshMetadata?.();
@@ -176,7 +181,11 @@ export function createEnvironmentConnection(
},
dispose: async () => {
cleanup();
await input.client.dispose();
try {
await input.client.dispose();
} finally {
input.atomRpc?.dispose();
}
},
};
}
@@ -28,3 +28,4 @@ export {
startEnvironmentConnectionService,
subscribeEnvironmentConnections,
} from "./service";
export type { EnvironmentConnection } from "./connection";
+121 -64
View File
@@ -63,10 +63,15 @@ import {
} from "~/store";
import { useTerminalStateStore } from "~/terminalStateStore";
import { useUiStateStore } from "~/uiStateStore";
import type { WsProtocolCloseContext } from "../../rpc/protocol";
import type {
WsProtocolCloseContext,
WsProtocolLifecycleHandlers,
WsRpcProtocolSocketUrlProvider,
} from "../../rpc/protocol";
import { getServerConfig } from "../../rpc/serverState";
import { WsTransport } from "../../rpc/wsTransport";
import { createWsRpcClient, type WsRpcClient } from "../../rpc/wsRpcClient";
import { createEnvironmentAtomRpcClient } from "../../rpc/environmentAtomRpc";
import { appendVersionMismatchHint, resolveServerConfigVersionMismatch } from "../../versionSkew";
import {
deriveLogicalProjectKeyFromSettings,
@@ -1130,17 +1135,40 @@ function createPrimaryEnvironmentClient(
`Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
);
}
const connectionLabel = knownEnvironment?.label ?? null;
return createWsRpcClient(
new WsTransport(wsBaseUrl, {
getConnectionLabel: () => connectionLabel,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(getServerConfig())?.hint ?? null,
}),
new WsTransport(wsBaseUrl, createPrimaryEnvironmentLifecycleHandlers(knownEnvironment)),
);
}
function createPrimaryEnvironmentAtomRpcClient(
knownEnvironment: ReturnType<typeof getPrimaryKnownEnvironment>,
) {
const wsBaseUrl = getKnownEnvironmentWsBaseUrl(knownEnvironment);
if (!wsBaseUrl || !knownEnvironment?.environmentId) {
throw new Error(
`Unable to resolve websocket URL for ${knownEnvironment?.label ?? "primary environment"}.`,
);
}
return createEnvironmentAtomRpcClient({
environmentId: knownEnvironment.environmentId,
url: wsBaseUrl,
lifecycleHandlers: createPrimaryEnvironmentLifecycleHandlers(knownEnvironment),
});
}
function createPrimaryEnvironmentLifecycleHandlers(
knownEnvironment: ReturnType<typeof getPrimaryKnownEnvironment>,
): WsProtocolLifecycleHandlers {
const connectionLabel = knownEnvironment?.label ?? null;
return {
getConnectionLabel: () => connectionLabel,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(getServerConfig())?.hint ?? null,
};
}
function createSavedEnvironmentClient(
environmentId: EnvironmentId,
bearerToken: string,
@@ -1149,67 +1177,90 @@ function createSavedEnvironmentClient(
return createWsRpcClient(
new WsTransport(
async () => {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
return record.desktopSsh
? await resolveDesktopSshWebSocketConnectionUrl(
record.wsBaseUrl,
record.httpBaseUrl,
bearerToken,
)
: await resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
});
},
{
getConnectionLabel: () => getSavedEnvironmentRecord(environmentId)?.label ?? null,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
)?.hint ?? null,
onAttempt: () => {
setRuntimeConnecting(environmentId);
},
onOpen: () => {
setRuntimeConnected(environmentId);
},
onError: (message: string) => {
const mismatch = resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
);
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "error",
lastError: appendVersionMismatchHint(message, mismatch),
lastErrorAt: isoNow(),
});
},
onClose: (
details: { readonly code: number; readonly reason: string },
context: WsProtocolCloseContext,
) => {
if (context.intentional) {
return;
}
setRuntimeDisconnected(
environmentId,
appendVersionMismatchHint(
details.reason,
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
),
),
);
},
},
createSavedEnvironmentSocketUrlProvider(environmentId, bearerToken),
createSavedEnvironmentLifecycleHandlers(environmentId),
),
);
}
function createSavedEnvironmentAtomRpcClient(environmentId: EnvironmentId, bearerToken: string) {
useSavedEnvironmentRuntimeStore.getState().ensure(environmentId);
return createEnvironmentAtomRpcClient({
environmentId,
url: createSavedEnvironmentSocketUrlProvider(environmentId, bearerToken),
lifecycleHandlers: createSavedEnvironmentLifecycleHandlers(environmentId),
});
}
function createSavedEnvironmentSocketUrlProvider(
environmentId: EnvironmentId,
bearerToken: string,
): WsRpcProtocolSocketUrlProvider {
return async () => {
const record = getSavedEnvironmentRecord(environmentId);
if (!record) {
throw new Error(`Saved environment ${environmentId} not found.`);
}
return record.desktopSsh
? await resolveDesktopSshWebSocketConnectionUrl(
record.wsBaseUrl,
record.httpBaseUrl,
bearerToken,
)
: await resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken,
});
};
}
function createSavedEnvironmentLifecycleHandlers(
environmentId: EnvironmentId,
): WsProtocolLifecycleHandlers {
return {
getConnectionLabel: () => getSavedEnvironmentRecord(environmentId)?.label ?? null,
getVersionMismatchHint: () =>
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
)?.hint ?? null,
onAttempt: () => {
setRuntimeConnecting(environmentId);
},
onOpen: () => {
setRuntimeConnected(environmentId);
},
onError: (message: string) => {
const mismatch = resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
);
useSavedEnvironmentRuntimeStore.getState().patch(environmentId, {
connectionState: "error",
lastError: appendVersionMismatchHint(message, mismatch),
lastErrorAt: isoNow(),
});
},
onClose: (
details: { readonly code: number; readonly reason: string },
context: WsProtocolCloseContext,
) => {
if (context.intentional) {
return;
}
setRuntimeDisconnected(
environmentId,
appendVersionMismatchHint(
details.reason,
resolveServerConfigVersionMismatch(
useSavedEnvironmentRuntimeStore.getState().byId[environmentId]?.serverConfig,
),
),
);
},
};
}
async function refreshSavedEnvironmentMetadata(
environmentId: EnvironmentId,
bearerToken: string,
@@ -1284,6 +1335,7 @@ function createPrimaryEnvironmentConnection(): EnvironmentConnection {
kind: "primary",
knownEnvironment,
client: createPrimaryEnvironmentClient(knownEnvironment),
atomRpc: createPrimaryEnvironmentAtomRpcClient(knownEnvironment),
...createEnvironmentConnectionHandlers(),
}),
);
@@ -1344,6 +1396,10 @@ async function ensureSavedEnvironmentConnection(
const client =
options?.client ??
createSavedEnvironmentClient(activeRecord.environmentId, activeBearerToken);
const atomRpc =
options?.client === undefined
? createSavedEnvironmentAtomRpcClient(activeRecord.environmentId, activeBearerToken)
: undefined;
const initialConfigSnapshot = createDeferredPromise<ServerConfig>();
const knownEnvironment = createKnownEnvironment({
id: activeRecord.environmentId,
@@ -1361,6 +1417,7 @@ async function ensureSavedEnvironmentConnection(
environmentId: activeRecord.environmentId,
},
client,
...(atomRpc ? { atomRpc } : {}),
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(
activeRecord.environmentId,
+47 -18
View File
@@ -19,9 +19,14 @@ import {
UnifiedSettings,
} from "@t3tools/contracts/settings";
import { ensureLocalApi } from "~/localApi";
import { Struct } from "effect";
import { Cause, Effect, Exit, Option, Struct } from "effect";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
import {
RpcAtomRuntimeUnavailableError,
usePrimaryServerSettingsRpcResult,
useUpdatePrimaryServerSettingsRpc,
} from "~/rpc/useEnvironmentRpcAtoms";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -168,12 +173,17 @@ export function useClientSettingsHydrated(): boolean {
}
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
const serverSettings = useServerSettings();
const legacyServerSettings = useServerSettings();
const serverSettingsRpcResult = usePrimaryServerSettingsRpcResult();
const clientSettings = useSyncExternalStore(
subscribeClientSettings,
getClientSettingsSnapshot,
() => DEFAULT_CLIENT_SETTINGS,
);
const serverSettings =
serverSettingsRpcResult._tag === "Success"
? serverSettingsRpcResult.value
: legacyServerSettings;
const merged = useMemo<UnifiedSettings>(
() => ({
@@ -193,25 +203,44 @@ export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings)
* persisted via RPC. Client keys go through client persistence.
*/
export function useUpdateSettings() {
const updateSettings = useCallback((patch: Partial<UnifiedSettings>) => {
const { serverPatch, clientPatch } = splitPatch(patch);
const updatePrimaryServerSettingsRpc = useUpdatePrimaryServerSettingsRpc();
const updateSettings = useCallback(
(patch: Partial<UnifiedSettings>) => {
const { serverPatch, clientPatch } = splitPatch(patch);
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
}
void Effect.runPromiseExit(updatePrimaryServerSettingsRpc(serverPatch)).then((exit) => {
if (Exit.isSuccess(exit)) {
applySettingsUpdated(exit.value);
return;
}
const typedError = Cause.findErrorOption(exit.cause);
if (
Option.isSome(typedError) &&
typedError.value instanceof RpcAtomRuntimeUnavailableError
) {
void ensureLocalApi().server.updateSettings(serverPatch);
return;
}
console.error("[SERVER_SETTINGS] AtomRpc update failed", Cause.pretty(exit.cause));
});
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
}
if (Object.keys(clientPatch).length > 0) {
persistClientSettings({
...getClientSettingsSnapshot(),
...clientPatch,
});
}
}, []);
if (Object.keys(clientPatch).length > 0) {
persistClientSettings({
...getClientSettingsSnapshot(),
...clientPatch,
});
}
},
[updatePrimaryServerSettingsRpc],
);
const resetSettings = useCallback(() => {
updateSettings(DEFAULT_UNIFIED_SETTINGS);
+4
View File
@@ -4,6 +4,10 @@ import type { ReactNode } from "react";
export let appAtomRegistry = AtomRegistry.make();
export function getAppAtomRegistry(): AtomRegistry.AtomRegistry {
return appAtomRegistry;
}
export function AppAtomRegistryProvider({ children }: { readonly children: ReactNode }) {
return <RegistryContext.Provider value={appAtomRegistry}>{children}</RegistryContext.Provider>;
}
+28
View File
@@ -0,0 +1,28 @@
import { createT3RpcAtomRuntime, type T3RpcAtomRuntime } from "@t3tools/client-runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import {
createWsRpcProtocolLayer,
type WsProtocolLifecycleHandlers,
type WsRpcProtocolSocketUrlProvider,
} from "./protocol";
import { getAppAtomRegistry } from "./atomRegistry";
export type EnvironmentAtomRpcClient = T3RpcAtomRuntime;
export interface EnvironmentAtomRpcClientInput {
readonly environmentId: EnvironmentId;
readonly url: WsRpcProtocolSocketUrlProvider;
readonly lifecycleHandlers?: WsProtocolLifecycleHandlers;
}
export function createEnvironmentAtomRpcClient(
input: EnvironmentAtomRpcClientInput,
): EnvironmentAtomRpcClient {
return createT3RpcAtomRuntime({
environmentId: input.environmentId,
getRegistry: getAppAtomRegistry,
protocol: createWsRpcProtocolLayer(input.url, input.lifecycleHandlers),
spanPrefix: `EnvironmentRpc:${input.environmentId}`,
});
}
@@ -0,0 +1,88 @@
import {
serverSettingsAtom,
updateServerSettingsArg,
updateServerSettingsMutation,
type T3RpcAtomRuntime,
} from "@t3tools/client-runtime";
import {
ServerSettingsError,
type ServerSettings,
type ServerSettingsPatch,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { Data, Effect } from "effect";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import type { RpcClientError } from "effect/unstable/rpc/RpcClientError";
import { useCallback, useEffect, useMemo, useState } from "react";
import { getPrimaryKnownEnvironment } from "../environments/primary";
import {
readEnvironmentConnection,
subscribeEnvironmentConnections,
} from "../environments/runtime";
export class RpcAtomRuntimeUnavailableError extends Data.TaggedError(
"RpcAtomRuntimeUnavailableError",
)<{
readonly environmentId: string | null;
}> {}
export type ServerSettingsRpcAtomError =
| ServerSettingsError
| RpcClientError
| RpcAtomRuntimeUnavailableError;
export type UpdatePrimaryServerSettingsRpc = (
patch: ServerSettingsPatch,
) => Effect.Effect<ServerSettings, ServerSettingsRpcAtomError>;
const missingServerSettingsAtom = Atom.make(
AsyncResult.initial<ServerSettings, ServerSettingsRpcAtomError>(true),
).pipe(Atom.keepAlive, Atom.withLabel("rpc:server-settings:missing-runtime"));
export function usePrimaryEnvironmentRpcAtomRuntime(): T3RpcAtomRuntime | null {
const [, forceSync] = useState(0);
useEffect(() => subscribeEnvironmentConnections(() => forceSync((version) => version + 1)), []);
const environmentId = getPrimaryKnownEnvironment()?.environmentId ?? null;
return environmentId ? (readEnvironmentConnection(environmentId)?.atomRpc ?? null) : null;
}
export function usePrimaryServerSettingsRpcResult() {
const runtime = usePrimaryEnvironmentRpcAtomRuntime();
const atom = useMemo(
() =>
(runtime ? serverSettingsAtom(runtime) : missingServerSettingsAtom) as Atom.Atom<
AsyncResult.AsyncResult<ServerSettings, ServerSettingsRpcAtomError>
>,
[runtime],
);
return useAtomValue(atom);
}
export function useUpdatePrimaryServerSettingsRpc(): UpdatePrimaryServerSettingsRpc {
const runtime = usePrimaryEnvironmentRpcAtomRuntime();
const mutation = useMemo(
() => (runtime ? updateServerSettingsMutation(runtime) : null),
[runtime],
);
return useCallback<UpdatePrimaryServerSettingsRpc>(
(patch: ServerSettingsPatch) => {
if (!runtime || !mutation) {
return Effect.fail(
new RpcAtomRuntimeUnavailableError({
environmentId: getPrimaryKnownEnvironment()?.environmentId ?? null,
}),
);
}
return runtime.runMutation(mutation, updateServerSettingsArg(patch), {
suspendOnWaiting: true,
});
},
[mutation, runtime],
);
}
+2
View File
@@ -1,4 +1,6 @@
export * from "./advertisedEndpoint.ts";
export * from "./knownEnvironment.ts";
export * from "./rpcAtomRuntime.ts";
export * from "./scoped.ts";
export * from "./serverRpcAtoms.ts";
export * from "./sourceControlDiscoveryState.ts";
@@ -0,0 +1,82 @@
import { WsRpcGroup, type EnvironmentId } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { Atom, AtomRegistry, AtomRpc } from "effect/unstable/reactivity";
import type * as Rpc from "effect/unstable/rpc/Rpc";
import type * as RpcClient from "effect/unstable/rpc/RpcClient";
import type * as RpcGroup from "effect/unstable/rpc/RpcGroup";
type WsRpcGroupRpcs =
typeof WsRpcGroup extends RpcGroup.RpcGroup<infer Rpcs extends Rpc.Any> ? Rpcs : never;
export interface T3RpcAtomService extends AtomRpc.AtomRpcClient<
T3RpcAtomService,
string,
WsRpcGroupRpcs
> {}
export type T3RpcAtomProtocol = Layer.Layer<RpcClient.Protocol, never, never>;
export interface T3RpcAtomRuntime {
readonly environmentId: EnvironmentId;
readonly rpc: T3RpcAtomService;
readonly query: T3RpcAtomService["query"];
readonly mutation: T3RpcAtomService["mutation"];
readonly getResult: <A, E>(
atom: Atom.Atom<import("effect/unstable/reactivity").AsyncResult.AsyncResult<A, E>>,
options?: {
readonly suspendOnWaiting?: boolean;
},
) => Effect.Effect<A, E>;
readonly runMutation: <Arg, A, E>(
atom: Atom.AtomResultFn<Arg, A, E>,
arg: Arg,
options?: {
readonly suspendOnWaiting?: boolean;
},
) => Effect.Effect<A, E>;
readonly reset: () => void;
readonly dispose: () => void;
}
export interface T3RpcAtomRuntimeInput {
readonly environmentId: EnvironmentId;
readonly protocol: T3RpcAtomProtocol;
readonly getRegistry: () => AtomRegistry.AtomRegistry;
readonly spanPrefix?: string;
}
export function createT3RpcAtomRuntime(input: T3RpcAtomRuntimeInput): T3RpcAtomRuntime {
const runtime = Atom.context({ memoMap: Layer.makeMemoMapUnsafe() });
const rpc = AtomRpc.Service<T3RpcAtomService>()(
`t3tools/runtime/environment-rpc/${input.environmentId}`,
{
group: WsRpcGroup,
protocol: input.protocol,
runtime,
spanPrefix: input.spanPrefix ?? `EnvironmentRpc:${input.environmentId}`,
},
);
return {
environmentId: input.environmentId,
rpc,
query: rpc.query,
mutation: rpc.mutation,
getResult: (atom, options) => AtomRegistry.getResult(input.getRegistry(), atom, options),
runMutation: (atom, arg, options) =>
Effect.gen(function* () {
yield* Effect.sync(() => {
input.getRegistry().set(atom, arg);
});
return yield* AtomRegistry.getResult(input.getRegistry(), atom, options);
}),
reset: () => {
// Registry ownership stays with the host app. Environment teardown can
// invalidate specific atoms, but it must not reset the app registry.
},
dispose: () => {
// Registry ownership stays with the host app.
},
};
}
@@ -0,0 +1,44 @@
import { WS_METHODS, type ServerSettingsPatch } from "@t3tools/contracts";
import type { T3RpcAtomRuntime } from "./rpcAtomRuntime.ts";
export const SERVER_CONFIG_REACTIVITY_KEY = ["server", "config"] as const;
export const SERVER_SETTINGS_REACTIVITY_KEY = ["server", "settings"] as const;
export function serverConfigAtom(runtime: Pick<T3RpcAtomRuntime, "query">) {
return runtime.query(
WS_METHODS.serverGetConfig,
{},
{
reactivityKeys: SERVER_CONFIG_REACTIVITY_KEY,
serializationKey: "server.getConfig",
timeToLive: Infinity,
},
);
}
export function serverSettingsAtom(runtime: Pick<T3RpcAtomRuntime, "query">) {
return runtime.query(
WS_METHODS.serverGetSettings,
{},
{
reactivityKeys: SERVER_SETTINGS_REACTIVITY_KEY,
serializationKey: "server.getSettings",
timeToLive: Infinity,
},
);
}
export function updateServerSettingsMutation(runtime: Pick<T3RpcAtomRuntime, "mutation">) {
return runtime.mutation(WS_METHODS.serverUpdateSettings);
}
export function updateServerSettingsArg(patch: ServerSettingsPatch) {
return {
payload: { patch },
reactivityKeys: {
config: SERVER_CONFIG_REACTIVITY_KEY,
settings: SERVER_SETTINGS_REACTIVITY_KEY,
},
} as const;
}
+4 -39
View File
@@ -1,7 +1,5 @@
import type { VcsStatusRemoteResult, VcsStatusResult } from "@t3tools/contracts";
import { assert, describe, expect, it } from "@effect/vitest";
import { Effect } from "effect";
import * as Random from "effect/Random";
import { describe, expect, it } from "vitest";
import {
applyGitStatusStreamEvent,
@@ -12,22 +10,6 @@ import {
WORKTREE_BRANCH_PREFIX,
} from "./git.ts";
function deterministicRandom(seed = 0x1234_5678): {
nextIntUnsafe: () => number;
nextDoubleUnsafe: () => number;
} {
let state = seed >>> 0;
const nextIntUnsafe = (): number => {
state = (Math.imul(1_664_525, state) + 1_013_904_223) >>> 0;
return state;
};
return {
nextIntUnsafe,
nextDoubleUnsafe: () => nextIntUnsafe() / 0x1_0000_0000,
};
}
describe("normalizeGitRemoteUrl", () => {
it("canonicalizes equivalent GitHub remotes across protocol variants", () => {
expect(normalizeGitRemoteUrl("[email protected]:T3Tools/T3Code.git")).toBe(
@@ -72,26 +54,9 @@ describe("parseGitHubRepositoryNameWithOwnerFromRemoteUrl", () => {
});
describe("isTemporaryWorktreeBranch", () => {
it.effect("matches the generated temporary worktree refName format", () =>
Effect.gen(function* () {
const branch = yield* buildTemporaryWorktreeBranchName;
assert.equal(isTemporaryWorktreeBranch(branch), true);
}),
);
it.effect("uses the Effect Random service for deterministic temporary refs", () =>
Effect.gen(function* () {
const firstBranch = yield* buildTemporaryWorktreeBranchName.pipe(
Effect.provideService(Random.Random, deterministicRandom()),
);
const secondBranch = yield* buildTemporaryWorktreeBranchName.pipe(
Effect.provideService(Random.Random, deterministicRandom()),
);
assert.equal(firstBranch, secondBranch);
assert.equal(isTemporaryWorktreeBranch(firstBranch), true);
}),
);
it("matches the generated temporary worktree refName format", () => {
expect(isTemporaryWorktreeBranch(buildTemporaryWorktreeBranchName())).toBe(true);
});
it("matches generated temporary worktree refs", () => {
expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef`)).toBe(true);
+7 -16
View File
@@ -7,7 +7,6 @@ import type {
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
@@ -87,12 +86,10 @@ export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
return branchName.slice(firstSeparatorIndex + 1);
}
export const buildTemporaryWorktreeBranchName = Random.nextUUIDv4.pipe(
Effect.map((uuid) => {
const token = uuid.replace(/-/g, "").slice(0, 8).toLowerCase();
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}),
);
export function buildTemporaryWorktreeBranchName(): string {
const token = Effect.runSync(Random.nextUUIDv4).replace(/-/g, "").slice(0, 8).toLowerCase();
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}
export function isTemporaryWorktreeBranch(refName: string): boolean {
return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());
@@ -134,12 +131,10 @@ export function normalizeGitRemoteUrl(value: string): string {
/**
* Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
*/
export function parseGitHubRepositoryNameWithOwnerFromRemoteUrlOption(
url: string | null,
): Option.Option<string> {
export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
const trimmed = url?.trim() ?? "";
if (trimmed.length === 0) {
return Option.none();
return null;
}
const match =
@@ -147,11 +142,7 @@ export function parseGitHubRepositoryNameWithOwnerFromRemoteUrlOption(
trimmed,
);
const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
return repositoryNameWithOwner.length > 0 ? Option.some(repositoryNameWithOwner) : Option.none();
}
export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
return Option.getOrNull(parseGitHubRepositoryNameWithOwnerFromRemoteUrlOption(url));
return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
+20 -44
View File
@@ -1,83 +1,59 @@
import { assert, describe, it } from "@effect/vitest";
import { Option } from "effect";
import { describe, expect, it } from "vitest";
import {
detectSourceControlProviderFromRemoteUrl,
getChangeRequestTerminologyForKind,
parseRemoteHostForSourceControl,
resolveChangeRequestPresentation,
} from "./sourceControl.ts";
describe("source control presentation", () => {
it("uses merge request terminology for GitLab", () => {
assert.deepEqual(getChangeRequestTerminologyForKind("gitlab"), {
expect(getChangeRequestTerminologyForKind("gitlab")).toEqual({
shortLabel: "MR",
singular: "merge request",
});
});
it("uses pull request terminology for GitHub-compatible providers", () => {
assert.deepEqual(getChangeRequestTerminologyForKind("github"), {
expect(getChangeRequestTerminologyForKind("github")).toEqual({
shortLabel: "PR",
singular: "pull request",
});
assert.deepEqual(getChangeRequestTerminologyForKind("azure-devops"), {
expect(getChangeRequestTerminologyForKind("azure-devops")).toEqual({
shortLabel: "PR",
singular: "pull request",
});
assert.deepEqual(getChangeRequestTerminologyForKind("bitbucket"), {
expect(getChangeRequestTerminologyForKind("bitbucket")).toEqual({
shortLabel: "PR",
singular: "pull request",
});
});
it("falls back to generic change request copy for unknown providers", () => {
const presentation = resolveChangeRequestPresentation({
kind: "unknown",
name: "forge",
baseUrl: "",
});
assert.equal(presentation.shortName, "change request");
assert.equal(presentation.longName, "change request");
expect(
resolveChangeRequestPresentation({ kind: "unknown", name: "forge", baseUrl: "" }),
).toEqual(
expect.objectContaining({
shortName: "change request",
longName: "change request",
}),
);
});
});
describe("detectSourceControlProviderFromRemoteUrl", () => {
it("detects common source control hosts", () => {
assert.equal(
detectSourceControlProviderFromRemoteUrl("[email protected]:owner/repo.git")?.kind,
expect(detectSourceControlProviderFromRemoteUrl("[email protected]:owner/repo.git")?.kind).toBe(
"github",
);
assert.equal(
expect(
detectSourceControlProviderFromRemoteUrl("https://gitlab.com/group/repo.git")?.kind,
"gitlab",
);
assert.equal(
).toBe("gitlab");
expect(
detectSourceControlProviderFromRemoteUrl("https://dev.azure.com/org/project/_git/repo")?.kind,
"azure-devops",
);
assert.equal(
).toBe("azure-devops");
expect(
detectSourceControlProviderFromRemoteUrl("[email protected]:workspace/repo.git")?.kind,
"bitbucket",
);
});
});
describe("parseRemoteHostOption", () => {
it("returns parsed hosts as options", () => {
assert.deepEqual(
parseRemoteHostForSourceControl("[email protected]:owner/repo.git"),
Option.some("github.com"),
);
assert.deepEqual(
parseRemoteHostForSourceControl("https://gitlab.com/group/repo.git"),
Option.some("gitlab.com"),
);
});
it("returns none for empty or invalid remotes", () => {
assert.equal(Option.isNone(parseRemoteHostForSourceControl(" ")), true);
assert.equal(Option.isNone(parseRemoteHostForSourceControl("not a url")), true);
).toBe("bitbucket");
});
});
+6 -15
View File
@@ -1,5 +1,4 @@
import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";
import { Option } from "effect";
export interface ChangeRequestPresentation {
readonly icon: "github" | "gitlab" | "azure-devops" | "bitbucket" | "change-request";
@@ -134,36 +133,28 @@ export function getChangeRequestTerminologyForKind(
};
}
function parseRemoteHostOption(remoteUrl: string): Option.Option<string> {
function parseRemoteHost(remoteUrl: string): string | null {
const trimmed = remoteUrl.trim();
if (trimmed.length === 0) {
return Option.none();
return null;
}
if (trimmed.startsWith("git@")) {
const hostWithPath = trimmed.slice("git@".length);
const separatorIndex = hostWithPath.search(/[:/]/);
if (separatorIndex <= 0) {
return Option.none();
return null;
}
return Option.some(hostWithPath.slice(0, separatorIndex).toLowerCase());
return hostWithPath.slice(0, separatorIndex).toLowerCase();
}
try {
return Option.some(new URL(trimmed).hostname.toLowerCase());
return new URL(trimmed).hostname.toLowerCase();
} catch {
return Option.none();
return null;
}
}
function parseRemoteHost(remoteUrl: string): string | null {
return Option.getOrNull(parseRemoteHostOption(remoteUrl));
}
export function parseRemoteHostForSourceControl(remoteUrl: string): Option.Option<string> {
return parseRemoteHostOption(remoteUrl);
}
function toBaseUrl(host: string): string {
return `https://${host}`;
}