Prepare datamodel for multi-environment (#1765)

Co-authored-by: justsomelegs <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-04-09 02:05:20 +00:00
1 parent 72b7f90c50
commit b96308fc5a
121 files changed
+10195 -4958

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
{
"name": "@t3tools/client-runtime",
"version": "0.0.0-alpha.1",
"private": true,
"type": "module",
"exports": {
".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
}
},
"scripts": {
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@t3tools/contracts": "workspace:*"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
+2
View File
@@ -0,0 +1,2 @@
export * from "./knownEnvironment";
export * from "./scoped";
@@ -0,0 +1,63 @@
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { createKnownEnvironmentFromWsUrl } from "./knownEnvironment";
import {
parseScopedProjectKey,
parseScopedThreadKey,
scopedProjectKey,
scopedRefKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "./scoped";
describe("known environment bootstrap helpers", () => {
it("creates known environments from explicit ws urls", () => {
expect(
createKnownEnvironmentFromWsUrl({
label: "Remote environment",
wsUrl: "wss://remote.example.com/ws",
}),
).toEqual({
id: "ws:Remote environment",
label: "Remote environment",
source: "manual",
target: {
type: "ws",
wsUrl: "wss://remote.example.com/ws",
},
});
});
});
describe("scoped refs", () => {
const environmentId = EnvironmentId.makeUnsafe("environment-test");
const projectRef = scopeProjectRef(environmentId, ProjectId.makeUnsafe("project-1"));
const threadRef = scopeThreadRef(environmentId, ThreadId.makeUnsafe("thread-1"));
it("builds stable scoped project and thread keys", () => {
expect(scopedRefKey(projectRef)).toBe("environment-test:project-1");
expect(scopedRefKey(threadRef)).toBe("environment-test:thread-1");
expect(scopedProjectKey(projectRef)).toBe("environment-test:project-1");
expect(scopedThreadKey(threadRef)).toBe("environment-test:thread-1");
});
it("returns typed scoped refs", () => {
expect(projectRef).toEqual({
environmentId,
projectId: ProjectId.makeUnsafe("project-1"),
});
expect(threadRef).toEqual({
environmentId,
threadId: ThreadId.makeUnsafe("thread-1"),
});
});
it("parses scoped project and thread keys back into refs", () => {
expect(parseScopedProjectKey("environment-test:project-1")).toEqual(projectRef);
expect(parseScopedThreadKey("environment-test:thread-1")).toEqual(threadRef);
expect(parseScopedProjectKey("bad-key")).toBeNull();
expect(parseScopedThreadKey("bad-key")).toBeNull();
});
});
@@ -0,0 +1,39 @@
import type { EnvironmentId } from "@t3tools/contracts";
export interface KnownEnvironmentConnectionTarget {
readonly type: "ws";
readonly wsUrl: string;
}
export type KnownEnvironmentSource = "configured" | "desktop-managed" | "manual" | "window-origin";
export interface KnownEnvironment {
readonly id: string;
readonly label: string;
readonly source: KnownEnvironmentSource;
readonly environmentId?: EnvironmentId;
readonly target: KnownEnvironmentConnectionTarget;
}
export function createKnownEnvironmentFromWsUrl(input: {
readonly id?: string;
readonly label: string;
readonly source?: KnownEnvironmentSource;
readonly wsUrl: string;
}): KnownEnvironment {
return {
id: input.id ?? `ws:${input.label}`,
label: input.label,
source: input.source ?? "manual",
target: {
type: "ws",
wsUrl: input.wsUrl,
},
};
}
export function getKnownEnvironmentBaseUrl(
environment: KnownEnvironment | null | undefined,
): string | null {
return environment?.target.wsUrl ?? null;
}
+64
View File
@@ -0,0 +1,64 @@
import type {
EnvironmentId,
ProjectId,
ScopedProjectRef,
ScopedThreadRef,
ThreadId,
} from "@t3tools/contracts";
export function scopeProjectRef(
environmentId: EnvironmentId,
projectId: ProjectId,
): ScopedProjectRef {
return { environmentId, projectId };
}
export function scopeThreadRef(environmentId: EnvironmentId, threadId: ThreadId): ScopedThreadRef {
return { environmentId, threadId };
}
export function scopedRefKey(ref: ScopedProjectRef | ScopedThreadRef): string {
const localId = "projectId" in ref ? ref.projectId : ref.threadId;
return `${ref.environmentId}:${localId}`;
}
export function scopedProjectKey(ref: ScopedProjectRef): string {
return scopedRefKey(ref);
}
export function scopedThreadKey(ref: ScopedThreadRef): string {
return scopedRefKey(ref);
}
function parseScopedKey(key: string): { environmentId: EnvironmentId; localId: string } | null {
const separatorIndex = key.indexOf(":");
if (separatorIndex <= 0 || separatorIndex >= key.length - 1) {
return null;
}
return {
environmentId: key.slice(0, separatorIndex) as EnvironmentId,
localId: key.slice(separatorIndex + 1),
};
}
export function parseScopedProjectKey(key: string): ScopedProjectRef | null {
const parsed = parseScopedKey(key);
if (!parsed) {
return null;
}
return {
environmentId: parsed.environmentId,
projectId: parsed.localId as ProjectId,
};
}
export function parseScopedThreadKey(key: string): ScopedThreadRef | null {
const parsed = parseScopedKey(key);
if (!parsed) {
return null;
}
return {
environmentId: parsed.environmentId,
threadId: parsed.localId as ThreadId,
};
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src"]
}
+2
View File
@@ -19,6 +19,8 @@ export const ThreadId = makeEntityId("ThreadId");
export type ThreadId = typeof ThreadId.Type;
export const ProjectId = makeEntityId("ProjectId");
export type ProjectId = typeof ProjectId.Type;
export const EnvironmentId = makeEntityId("EnvironmentId");
export type EnvironmentId = typeof EnvironmentId.Type;
export const CommandId = makeEntityId("CommandId");
export type CommandId = typeof CommandId.Type;
export const EventId = makeEntityId("EventId");
+77
View File
@@ -0,0 +1,77 @@
import { Schema } from "effect";
import { EnvironmentId, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
export const ExecutionEnvironmentPlatformOs = Schema.Literals([
"darwin",
"linux",
"windows",
"unknown",
]);
export type ExecutionEnvironmentPlatformOs = typeof ExecutionEnvironmentPlatformOs.Type;
export const ExecutionEnvironmentPlatformArch = Schema.Literals(["arm64", "x64", "other"]);
export type ExecutionEnvironmentPlatformArch = typeof ExecutionEnvironmentPlatformArch.Type;
export const ExecutionEnvironmentPlatform = Schema.Struct({
os: ExecutionEnvironmentPlatformOs,
arch: ExecutionEnvironmentPlatformArch,
});
export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;
export const ExecutionEnvironmentCapabilities = Schema.Struct({
repositoryIdentity: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
});
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
export const ExecutionEnvironmentDescriptor = Schema.Struct({
environmentId: EnvironmentId,
label: TrimmedNonEmptyString,
platform: ExecutionEnvironmentPlatform,
serverVersion: TrimmedNonEmptyString,
capabilities: ExecutionEnvironmentCapabilities,
});
export type ExecutionEnvironmentDescriptor = typeof ExecutionEnvironmentDescriptor.Type;
export const EnvironmentConnectionState = Schema.Literals([
"connecting",
"connected",
"disconnected",
"error",
]);
export type EnvironmentConnectionState = typeof EnvironmentConnectionState.Type;
export const RepositoryIdentityLocator = Schema.Struct({
source: Schema.Literal("git-remote"),
remoteName: TrimmedNonEmptyString,
remoteUrl: TrimmedNonEmptyString,
});
export type RepositoryIdentityLocator = typeof RepositoryIdentityLocator.Type;
export const RepositoryIdentity = Schema.Struct({
canonicalKey: TrimmedNonEmptyString,
locator: RepositoryIdentityLocator,
displayName: Schema.optionalKey(TrimmedNonEmptyString),
provider: Schema.optionalKey(TrimmedNonEmptyString),
owner: Schema.optionalKey(TrimmedNonEmptyString),
name: Schema.optionalKey(TrimmedNonEmptyString),
});
export type RepositoryIdentity = typeof RepositoryIdentity.Type;
export const ScopedProjectRef = Schema.Struct({
environmentId: EnvironmentId,
projectId: ProjectId,
});
export type ScopedProjectRef = typeof ScopedProjectRef.Type;
export const ScopedThreadRef = Schema.Struct({
environmentId: EnvironmentId,
threadId: ThreadId,
});
export type ScopedThreadRef = typeof ScopedThreadRef.Type;
export const ScopedThreadSessionRef = Schema.Struct({
environmentId: EnvironmentId,
threadId: ThreadId,
});
export type ScopedThreadSessionRef = typeof ScopedThreadSessionRef.Type;
+1
View File
@@ -1,4 +1,5 @@
export * from "./baseSchemas";
export * from "./environment";
export * from "./ipc";
export * from "./terminal";
export * from "./provider";
+63 -37
View File
@@ -105,8 +105,14 @@ export interface DesktopUpdateCheckResult {
state: DesktopUpdateState;
}
export interface DesktopEnvironmentBootstrap {
label: string;
wsUrl: string | null;
}
export interface DesktopBridge {
getWsUrl: () => string | null;
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
setTheme: (theme: DesktopTheme) => Promise<void>;
@@ -123,51 +129,25 @@ export interface DesktopBridge {
onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
}
export interface NativeApi {
/**
* APIs bound to the local app shell, not to any particular backend environment.
*
* These capabilities describe the desktop/browser host that the user is
* currently running: dialogs, editor/external-link opening, context menus, and
* app-level settings/config access. They must not be used as a proxy for
* "whatever environment the user is targeting", because in a multi-environment
* world the local shell and a selected backend environment are distinct
* concepts.
*/
export interface LocalApi {
dialogs: {
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
};
terminal: {
open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;
write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;
resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;
clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;
restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;
close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
};
projects: {
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;
};
shell: {
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
openExternal: (url: string) => Promise<void>;
};
git: {
// Existing branch/worktree API
listBranches: (input: GitListBranchesInput) => Promise<GitListBranchesResult>;
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
createBranch: (input: GitCreateBranchInput) => Promise<GitCreateBranchResult>;
checkout: (input: GitCheckoutInput) => Promise<GitCheckoutResult>;
init: (input: GitInitInput) => Promise<void>;
resolvePullRequest: (input: GitPullRequestRefInput) => Promise<GitResolvePullRequestResult>;
preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Promise<GitPreparePullRequestThreadResult>;
// Stacked action API
pull: (input: GitPullInput) => Promise<GitPullResult>;
refreshStatus: (input: GitStatusInput) => Promise<GitStatusResult>;
onStatus: (
input: GitStatusInput,
callback: (status: GitStatusResult) => void,
options?: {
onResubscribe?: () => void;
},
) => () => void;
};
contextMenu: {
show: <T extends string>(
items: readonly ContextMenuItem<T>[],
@@ -181,6 +161,52 @@ export interface NativeApi {
getSettings: () => Promise<ServerSettings>;
updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
};
}
/**
* APIs bound to a specific backend environment connection.
*
* These operations must always be routed with explicit environment context.
* They represent remote stateful capabilities such as orchestration, terminal,
* project, and git operations. In multi-environment mode, each environment gets
* its own instance of this surface, and callers should resolve it by
* `environmentId` rather than reaching through the local desktop bridge.
*/
export interface EnvironmentApi {
terminal: {
open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;
write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;
resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;
clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;
restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;
close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
};
projects: {
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;
};
git: {
listBranches: (input: GitListBranchesInput) => Promise<GitListBranchesResult>;
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
createBranch: (input: GitCreateBranchInput) => Promise<GitCreateBranchResult>;
checkout: (input: GitCheckoutInput) => Promise<GitCheckoutResult>;
init: (input: GitInitInput) => Promise<void>;
resolvePullRequest: (input: GitPullRequestRefInput) => Promise<GitResolvePullRequestResult>;
preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Promise<GitPreparePullRequestThreadResult>;
pull: (input: GitPullInput) => Promise<GitPullResult>;
refreshStatus: (input: GitStatusInput) => Promise<GitStatusResult>;
onStatus: (
input: GitStatusInput,
callback: (status: GitStatusResult) => void,
options?: {
onResubscribe?: () => void;
},
) => () => void;
};
orchestration: {
getSnapshot: () => Promise<OrchestrationReadModel>;
dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;
+4
View File
@@ -1,5 +1,6 @@
import { Option, Schema, SchemaIssue, Struct } from "effect";
import { ClaudeModelOptions, CodexModelOptions } from "./model";
import { RepositoryIdentity } from "./environment";
import {
ApprovalRequestId,
CheckpointRef,
@@ -141,6 +142,7 @@ export const OrchestrationProject = Schema.Struct({
id: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -647,6 +649,7 @@ export const ProjectCreatedPayload = Schema.Struct({
projectId: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -657,6 +660,7 @@ export const ProjectMetaUpdatedPayload = Schema.Struct({
projectId: ProjectId,
title: Schema.optional(TrimmedNonEmptyString),
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
updatedAt: IsoDateTime,
+4
View File
@@ -1,4 +1,5 @@
import { Schema } from "effect";
import { ExecutionEnvironmentDescriptor } from "./environment";
import {
IsoDateTime,
NonNegativeInt,
@@ -83,6 +84,7 @@ export const ServerObservability = Schema.Struct({
export type ServerObservability = typeof ServerObservability.Type;
export const ServerConfig = Schema.Struct({
environment: ExecutionEnvironmentDescriptor,
cwd: TrimmedNonEmptyString,
keybindingsConfigPath: TrimmedNonEmptyString,
keybindings: ResolvedKeybindingsConfig,
@@ -167,10 +169,12 @@ export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;
export const ServerLifecycleReadyPayload = Schema.Struct({
at: IsoDateTime,
environment: ExecutionEnvironmentDescriptor,
});
export type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;
export const ServerLifecycleWelcomePayload = Schema.Struct({
environment: ExecutionEnvironmentDescriptor,
cwd: TrimmedNonEmptyString,
projectName: TrimmedNonEmptyString,
bootstrapProjectId: Schema.optional(ProjectId),
+48 -1
View File
@@ -1,7 +1,54 @@
import type { GitStatusRemoteResult, GitStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { applyGitStatusStreamEvent } from "./git";
import {
applyGitStatusStreamEvent,
normalizeGitRemoteUrl,
parseGitHubRepositoryNameWithOwnerFromRemoteUrl,
} from "./git";
describe("normalizeGitRemoteUrl", () => {
it("canonicalizes equivalent GitHub remotes across protocol variants", () => {
expect(normalizeGitRemoteUrl("[email protected]:T3Tools/T3Code.git")).toBe(
"github.com/t3tools/t3code",
);
expect(normalizeGitRemoteUrl("https://github.com/T3Tools/T3Code.git")).toBe(
"github.com/t3tools/t3code",
);
expect(normalizeGitRemoteUrl("ssh://[email protected]/T3Tools/T3Code")).toBe(
"github.com/t3tools/t3code",
);
});
it("preserves nested group paths for providers like GitLab", () => {
expect(normalizeGitRemoteUrl("[email protected]:T3Tools/platform/T3Code.git")).toBe(
"gitlab.com/t3tools/platform/t3code",
);
expect(normalizeGitRemoteUrl("https://gitlab.com/T3Tools/platform/T3Code.git")).toBe(
"gitlab.com/t3tools/platform/t3code",
);
});
it("drops explicit ports from URL-shaped remotes", () => {
expect(normalizeGitRemoteUrl("https://gitlab.company.com:8443/team/project.git")).toBe(
"gitlab.company.com/team/project",
);
expect(normalizeGitRemoteUrl("ssh://[email protected]:2222/team/project.git")).toBe(
"gitlab.company.com/team/project",
);
});
});
describe("parseGitHubRepositoryNameWithOwnerFromRemoteUrl", () => {
it("extracts the owner and repository from common GitHub remote shapes", () => {
expect(
parseGitHubRepositoryNameWithOwnerFromRemoteUrl("[email protected]:T3Tools/T3Code.git"),
).toBe("T3Tools/T3Code");
expect(
parseGitHubRepositoryNameWithOwnerFromRemoteUrl("https://github.com/T3Tools/T3Code.git"),
).toBe("T3Tools/T3Code");
});
});
describe("applyGitStatusStreamEvent", () => {
it("treats a remote-only update as a repository when local state is missing", () => {
+50
View File
@@ -80,6 +80,56 @@ export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
return branchName.slice(firstSeparatorIndex + 1);
}
/**
* Normalize a git remote URL into a stable comparison key.
*/
export function normalizeGitRemoteUrl(value: string): string {
const normalized = value
.trim()
.replace(/\/+$/g, "")
.replace(/\.git$/i, "")
.toLowerCase();
if (/^(?:ssh|https?|git):\/\//i.test(normalized)) {
try {
const url = new URL(normalized);
const repositoryPath = url.pathname
.split("/")
.filter((segment) => segment.length > 0)
.join("/");
if (url.hostname && repositoryPath.includes("/")) {
return `${url.hostname}/${repositoryPath}`;
}
} catch {
return normalized;
}
}
const scpStyleHostAndPath = /^git@([^:/\s]+)[:/]([^/\s]+(?:\/[^/\s]+)+)$/i.exec(normalized);
if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {
return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;
}
return normalized;
}
/**
* Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.
*/
export function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {
const trimmed = url?.trim() ?? "";
if (trimmed.length === 0) {
return null;
}
const match =
/^(?:git@github\.com:|ssh:\/\/git@github\.com\/|https:\/\/github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(
trimmed,
);
const repositoryNameWithOwner = match?.[1]?.trim() ?? "";
return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,