diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 8ef202c2d014f..08aae047dd932 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -6,7 +6,7 @@ import { type RelayClientInstallProgressEvent, type RelayClientInstallProgressStage, } from "@t3tools/contracts"; -import { RelayOkResponse } from "@t3tools/contracts/relay"; +import { RelayListEnvironmentsResponse, RelayOkResponse } from "@t3tools/contracts/relay"; import * as RelayClient from "@t3tools/shared/relayClient"; import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; import * as Cause from "effect/Cause"; @@ -152,6 +152,9 @@ interface CloudCliStatus { readonly revoked: boolean; readonly cloudUserId: string | null; readonly relayUrl: string | null; + readonly publicAddress: string | null; + readonly mcpUrl: string | null; + readonly addressLookupError: string | null; readonly publishAgentActivity: boolean; readonly relayClient: RelayClient.RelayClientStatus; readonly linkMode: CliState.CliDesiredLinkMode; @@ -221,6 +224,11 @@ function formatCloudStatus( ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`, ` Environment link: ${provisioned}`, ` Relay: ${status.relayUrl ?? "not provisioned"}`, + ` Public address: ${status.publicAddress ?? "unavailable"}`, + ` MCP URL: ${status.mcpUrl ?? "unavailable"}`, + ...(status.addressLookupError === null + ? [] + : [` Address lookup: ${status.addressLookupError}`]), ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`, ...formatRelayClientStatus(status.relayClient), ...(!status.desired @@ -661,6 +669,48 @@ const connectLinkCommand = Command.make("link", { ), ); +class ConnectAddressCredentialRefreshRequiredError extends Schema.TaggedError()( + "ConnectAddressCredentialRefreshRequiredError", + {}, +) { + override get message() { + return "Stored T3 Connect credential needs refresh. Run `t3 connect login` with the same --base-dir to refresh it, then retry status."; + } +} + +const isConnectAddressCredentialRefreshRequiredError = Schema.is( + ConnectAddressCredentialRefreshRequiredError, +); + +const decodeConnectEndpointUrl = Schema.decodeEffect(Schema.URLFromString); + +const readPublicConnectAddress = Effect.fn("cloud.cli.readPublicAddress")(function* ( + relayUrl: string, +) { + const tokens = yield* CliTokenManager.CloudCliTokenManager; + const stored = yield* tokens.peek; + if (Option.isNone(stored)) return null; + if (stored.value.needsRefresh) return yield* new ConnectAddressCredentialRefreshRequiredError({}); + const token = stored.value.token; + const environment = yield* ServerEnvironment.ServerEnvironmentIdentity; + const environmentId = yield* environment.getEnvironmentId; + const httpClient = yield* HttpClient.HttpClient; + const result = yield* HttpClientRequest.get(`${relayUrl}/v1/environments`).pipe( + HttpClientRequest.bearerToken(token.accessToken), + httpClient.execute, + Effect.flatMap(filterRelayResponse), + Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayListEnvironmentsResponse)), + Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT), + withRelayClientTracing, + ); + const endpoint = result.environments.find( + (item) => item.environmentId === environmentId, + )?.endpoint; + if (endpoint?.providerKind !== "cloudflare_tunnel") return null; + const url = yield* decodeConnectEndpointUrl(endpoint.httpBaseUrl); + return url.protocol === "https:" ? url.host : null; +}); + const connectStatusCommand = Command.make("status", { ...projectLocationFlags, json: jsonFlag, @@ -708,6 +758,14 @@ const connectStatusCommand = Command.make("status", { // A publish-only link has no tunnel for other devices to reach. const reachability = desired && linkMode === "managed" ? yield* checkLiveReachability() : null; + const address = + Option.isSome(cloudUserId) && + Option.isNone(revoked) && + linkMode === "managed" && + Option.isSome(relayUrl) + ? yield* readPublicConnectAddress(bytesToString(relayUrl.value)).pipe(Effect.result) + : null; + const publicAddress = address?._tag === "Success" ? address.success : null; const status: CloudCliStatus = { desired, authenticated, @@ -718,6 +776,14 @@ const connectStatusCommand = Command.make("status", { publishAgentActivity: isAgentActivityPublishingEnabledValue( Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null, ), + publicAddress, + mcpUrl: publicAddress === null ? null : `https://${publicAddress}/mcp`, + addressLookupError: + address?._tag === "Failure" + ? isConnectAddressCredentialRefreshRequiredError(address.failure) + ? address.failure.message + : "Could not read the public address from T3 Connect. Retry when connected and authorized." + : null, relayClient: executable, linkMode, reachability, diff --git a/apps/server/src/cli/connectStatus.test.ts b/apps/server/src/cli/connectStatus.test.ts new file mode 100644 index 0000000000000..0295f83599b65 --- /dev/null +++ b/apps/server/src/cli/connectStatus.test.ts @@ -0,0 +1,211 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as NetService from "@t3tools/shared/Net"; +import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Logger from "effect/Logger"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as TestConsole from "effect/testing/TestConsole"; +import { Command } from "effect/cli"; +import { vi } from "vite-plus/test"; + +import { makeCli } from "../binCli.ts"; + +vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { + const actual = await importOriginal(); + const environment = await import("../environment/ServerEnvironment.ts"); + return { + ...actual, + layerRuntime: Layer.merge( + Layer.mock(actual.EnvironmentAuth)({}), + Layer.succeed(environment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(EnvironmentId.make("this-host")), + }), + ), + }; +}); +vi.mock("../auth/ServerSecretStore.ts", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + layer: Layer.effect( + actual.ServerSecretStore, + Effect.gen(function* () { + const mode = yield* Config.String("TEST_LINK_MODE"); + const values: Record = + mode === "unlinked" + ? {} + : { + "cloud-linked-user-id": "user", + "cloud-relay-url": "https://relay.example.test", + "cloud-cli-oauth-token": + mode === "near-expiry" + ? '{"accessToken":"synthetic-token","refreshToken":"refresh","expiresAtEpochMs":1}' + : mode === "expired" + ? '{"accessToken":"synthetic-token","refreshToken":"refresh","expiresAtEpochMs":0}' + : '{"accessToken":"synthetic-token","refreshToken":"refresh","expiresAtEpochMs":9999999999999}', + ...(mode === "revoked" ? { "cloud-link-revoked": "true" } : {}), + ...(mode === "publish_only" ? { "cloud-cli-desired-link": "publish_only" } : {}), + }; + return actual.ServerSecretStore.of({ + get: (key) => + Effect.succeed( + Option.fromUndefinedOr(values[key]).pipe( + Option.map((value) => new TextEncoder().encode(value)), + ), + ), + set: () => Effect.die("status must not write secrets"), + remove: () => Effect.die("status must not remove secrets"), + create: () => Effect.die("status must not create secrets"), + getOrCreateRandom: () => Effect.die("status must not create secrets"), + }); + }), + ), + }; +}); + +const decodeStatus = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + publicAddress: Schema.NullOr(Schema.String), + mcpUrl: Schema.NullOr(Schema.String), + addressLookupError: Schema.NullOr(Schema.String), + }), + ), +); + +it.effect( + "connect status reports only this host's public endpoint in text and JSON, without changing link state", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-status-" }); + const replies = ( + providerKind = "cloudflare_tunnel", + httpBaseUrl = "https://this.example.test/", + ) => ({ + environments: [ + { + environmentId: "other-host", + label: "Other", + linkedAt: "2026-11-01", + endpoint: { + httpBaseUrl: "https://other.example.test", + wsBaseUrl: "wss://other.example.test", + providerKind: "cloudflare_tunnel", + }, + }, + { + environmentId: "this-host", + label: "This", + linkedAt: "2026-11-01", + endpoint: { + httpBaseUrl, + wsBaseUrl: "wss://this.example.test/", + providerKind, + }, + }, + ], + }); + using fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + assert.equal(request.method, "GET"); + assert.equal(request.url, "https://relay.example.test/v1/environments"); + assert.equal(request.headers.get("authorization"), "Bearer synthetic-token"); + return Response.json(replies()); + }); + const logs: string[] = []; + const logger = Logger.layer([Logger.make(({ message }) => logs.push(String(message)))], { + mergeWithExisting: false, + }); + const run = (mode: string, json = true) => + Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([ + "connect", + "status", + "--base-dir", + baseDir, + ...(json ? ["--json"] : []), + ]).pipe( + Effect.provide( + Layer.merge( + logger, + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { + TEST_LINK_MODE: mode, + T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==", + T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_test", + T3CODE_HOSTED_APP_URL: "https://hosted.example.test", + }, + }), + ), + ), + ), + ); + yield* fs.makeDirectory(`${baseDir}/userdata/attachments`, { recursive: true }); + const expiredUpload = `${baseDir}/userdata/attachments/stale.part`; + yield* fs.writeFileString(expiredUpload, "partial"); + yield* fs.utimes( + expiredUpload, + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + ); + const beforeJson = (yield* TestConsole.logLines).length; + yield* run("linked"); + assert.isFalse(yield* fs.exists(expiredUpload)); + assert.deepStrictEqual(logs, []); + decodeStatus((yield* TestConsole.logLines).slice(beforeJson).join("\n")); + assert.deepStrictEqual(decodeStatus(String((yield* TestConsole.logLines).at(-1))), { + publicAddress: "this.example.test", + mcpUrl: "https://this.example.test/mcp", + addressLookupError: null, + }); + yield* run("linked", false); + assert.include( + String((yield* TestConsole.logLines).at(-1)), + "MCP URL: https://this.example.test/mcp", + ); + for (const mode of ["unlinked", "revoked", "publish_only"]) { + fetch.mockClear(); + yield* run(mode); + assert.deepStrictEqual(decodeStatus(String((yield* TestConsole.logLines).at(-1))), { + publicAddress: null, + mcpUrl: null, + addressLookupError: null, + }); + assert.equal(fetch.mock.calls.length, 0); + } + for (const mode of ["near-expiry", "expired"]) { + fetch.mockClear(); + yield* run(mode); + const needsRefresh = decodeStatus(String((yield* TestConsole.logLines).at(-1))); + assert.isNull(needsRefresh.publicAddress); + assert.equal(fetch.mock.calls.length, 0, "status must not refresh or use a stale token"); + assert.include(needsRefresh.addressLookupError ?? "", "needs refresh"); + assert.include(needsRefresh.addressLookupError ?? "", "t3 connect login"); + } + fetch.mockResolvedValue(Response.json(replies("manual"))); + yield* run("linked"); + assert.isNull(decodeStatus(String((yield* TestConsole.logLines).at(-1))).mcpUrl); + fetch.mockResolvedValue(Response.json(replies("cloudflare_tunnel", "not a URL"))); + yield* run("linked"); + const malformed = decodeStatus(String((yield* TestConsole.logLines).at(-1))); + assert.isNull(malformed.mcpUrl); + assert.isNotNull(malformed.addressLookupError); + fetch.mockResolvedValue(new Response("unavailable", { status: 503 })); + yield* run("linked"); + const failed = decodeStatus(String((yield* TestConsole.logLines).at(-1))); + assert.isNull(failed.publicAddress); + assert.isNotNull(failed.addressLookupError); + }).pipe( + Effect.scoped, + Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)), + ), +); diff --git a/apps/server/src/cli/discovery.test.ts b/apps/server/src/cli/discovery.test.ts new file mode 100644 index 0000000000000..005d6741008f1 --- /dev/null +++ b/apps/server/src/cli/discovery.test.ts @@ -0,0 +1,475 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { AuthSessionId } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Logger from "effect/Logger"; +import * as Layer from "effect/Layer"; +import * as Deferred from "effect/Deferred"; +import * as Fiber from "effect/Fiber"; +import * as TestClock from "effect/testing/TestClock"; +import * as Schema from "effect/Schema"; +import * as Runtime from "effect/Runtime"; +import * as TestConsole from "effect/testing/TestConsole"; +import { Command } from "effect/cli"; +import { vi } from "vite-plus/test"; + +import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts"; +import { + makePersistedServerRuntimeState, + persistServerRuntimeState, +} from "../serverRuntimeState.ts"; +import { listAllThreads, type ThreadTools, withThreadTools } from "./discovery.ts"; +import * as Option from "effect/Option"; +import { projectCommand } from "./project.ts"; +import { threadCommand } from "./thread.ts"; + +vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + layerRuntime: Layer.mock(actual.EnvironmentAuth)({ + issueMcpClientSession: (input) => { + assert.equal(input.access, "read-only"); + return Effect.map(DateTime.now, (expiresAt) => ({ + sessionId: AuthSessionId.make("test-session"), + token: "synthetic-token", + expiresAt, + })); + }, + revokeSession: () => Effect.succeed(true), + }), + }; +}); + +const timestamp = "2026-11-01T12:00:00.000Z"; +const project = (id: string) => ({ + id, + title: id, + workspaceRoot: `/work/${id}`, + defaultModelSelection: id === "alpha" ? { instanceId: "codex", model: "gpt-test" } : null, +}); +const thread = (threadId: string, projectId: string, status: string) => ({ + threadId, + projectId, + title: threadId, + status, + createdBy: "user", + creationSource: "web", + providerInstanceId: "codex", + model: "gpt-test", + runtimeMode: "full-access", + interactionMode: "default", + latestRunId: null, + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: timestamp, + updatedAt: timestamp, +}); + +it.effect("discovery paginates existing MCP tools and preserves current-project defaults", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-" }); + yield* persistServerRuntimeState({ + path: `${baseDir}/userdata/server-runtime.json`, + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3773, + }), + }); + const projects = [project("alpha"), project("beta"), project("empty")]; + const threads = [ + thread("beta-running", "beta", "running"), + thread("alpha-completed", "alpha", "completed"), + { + ...thread("child-running", "alpha", "running"), + parentThreadId: "alpha-completed", + relationshipToParent: "subagent", + }, + ]; + const calls: Array<{ tool: string; args: Readonly> }> = []; + using session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, args) => { + calls.push({ tool, args }); + const cursor = Number(args.cursor); + if (tool === "t3_project_list") { + return Effect.succeed({ + structuredContent: { + projects: projects.slice(cursor, cursor + 1), + nextCursor: cursor + 1 < projects.length ? cursor + 1 : null, + }, + }); + } + assert.equal(tool, "t3_thread_list"); + + assert.equal(args.includeSubagents, true); + const statuses = args.statuses as ReadonlyArray | undefined; + const visible = threads.filter( + (item) => + (args.includeSubagents === true || item.relationshipToParent !== "subagent") && + (args.allProjects === true || item.projectId === args.projectId) && + (statuses === undefined || statuses.includes(item.status)), + ); + return Effect.succeed({ + structuredContent: { + projectId: args.projectId ?? null, + currentThreadId: null, + threads: visible.slice(cursor, cursor + 1), + nextCursor: cursor + 1 < visible.length ? cursor + 1 : null, + total: visible.length, + }, + }); + }, + }), + ); + const logs: string[] = []; + const logger = Logger.layer([Logger.make(({ message }) => logs.push(String(message)))], { + mergeWithExisting: false, + }); + const runProject = (args: string[]) => + Command.runWith(projectCommand, { version: "0.0.0" })(args).pipe(Effect.provide(logger)); + const runThread = (args: string[]) => + Command.runWith(threadCommand, { version: "0.0.0" })(args).pipe(Effect.provide(logger)); + const flags = ["--base-dir", baseDir, "--json"]; + yield* fs.makeDirectory(`${baseDir}/userdata/attachments`, { recursive: true }); + const expiredUpload = `${baseDir}/userdata/attachments/stale.part`; + yield* fs.writeFileString(expiredUpload, "partial"); + yield* fs.utimes( + expiredUpload, + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + ); + const beforeJson = (yield* TestConsole.logLines).length; + yield* runProject(["list", ...flags]); + assert.isFalse(yield* fs.exists(expiredUpload)); + assert.deepStrictEqual(logs, []); + const stdout = (yield* TestConsole.logLines).slice(beforeJson).join("\n"); + assert(Array.isArray(JSON.parse(stdout))); + assert.deepStrictEqual(JSON.parse(String((yield* TestConsole.logLines).at(-1))), [ + { ...projects[0], threadCounts: { completed: 1 } }, + { ...projects[1], threadCounts: { running: 1 } }, + { ...projects[2], threadCounts: {} }, + ]); + assert.deepStrictEqual( + calls.map(({ tool, args }) => [tool, args.cursor]), + [ + ["t3_project_list", 0], + ["t3_project_list", 1], + ["t3_project_list", 2], + ["t3_thread_list", 0], + ["t3_thread_list", 1], + ["t3_thread_list", 2], + ["t3_thread_list", 0], + ["t3_thread_list", 1], + ["t3_thread_list", 2], + ], + ); + for (const [extra, expected] of [ + [[], ["alpha-completed"]], + [["--all-projects"], ["beta-running", "alpha-completed"]], + [["--project", "beta"], ["beta-running"]], + [["--project", "/work/alpha/nested"], ["alpha-completed"]], + [["--status", "running"], []], + [["--include-subagents"], ["alpha-completed", "child-running"]], + [["--include-subagents", "--project", "alpha", "--status", "running"], ["child-running"]], + [ + ["--include-subagents", "--all-projects", "--status", "running"], + ["beta-running", "child-running"], + ], + [["--all-projects", "--status", "running"], ["beta-running"]], + ] as const) { + yield* fs.writeFileString(expiredUpload, "partial"); + yield* fs.utimes( + expiredUpload, + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + ); + const beforeJson = (yield* TestConsole.logLines).length; + yield* runThread(["list", ...extra, ...flags]); + assert.isFalse(yield* fs.exists(expiredUpload)); + assert.deepStrictEqual(logs, []); + const rows = JSON.parse((yield* TestConsole.logLines).slice(beforeJson).join("\n")) as Array<{ + threadId: string; + parentThreadId: string | null; + relationshipToParent: string | null; + }>; + const child = rows.find((row) => row.threadId === "child-running"); + if (child) { + assert.equal(child.parentThreadId, "alpha-completed"); + assert.equal(child.relationshipToParent, "subagent"); + } + assert.deepStrictEqual( + rows.map((row) => row.threadId), + [...expected], + ); + } + const unknownId = yield* runThread(["list", "--project", "unknown-id", ...flags]).pipe( + Effect.result, + ); + assert(unknownId._tag === "Failure"); + const sessionsBefore = session.mock.calls.length; + const conflicting = yield* runThread([ + "list", + "--all-projects", + "--project", + "alpha", + ...flags, + ]).pipe(Effect.result); + assert(conflicting._tag === "Failure"); + assert.equal(session.mock.calls.length, sessionsBefore); + assert.equal( + (yield* TestConsole.errorLines).at(-1), + "--all-projects and --project cannot be used together.", + ); + yield* fs.writeFileString(expiredUpload, "partial"); + yield* fs.utimes( + expiredUpload, + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + DateTime.toDateUtc(DateTime.makeUnsafe(-172800000)), + ); + yield* runThread(["list", "--base-dir", baseDir]); + assert.include(logs.join("\n"), "Removed expired attachment uploads."); + assert.equal( + (yield* TestConsole.logLines).at(-1), + "alpha-completed completed alpha-completed", + ); + yield* runProject(["list", "--base-dir", baseDir]); + assert.include((yield* TestConsole.logLines).join("\n"), "codex/gpt-test"); + const unknown = yield* runThread(["list", "--project", "/unknown-project", ...flags]).pipe( + Effect.result, + ); + assert(unknown._tag === "Failure"); + assert.isFalse(Runtime.getErrorReported(unknown.failure)); + assert.equal( + (yield* TestConsole.errorLines).at(-1), + "No T3 Code project matches '/unknown-project'. Pass an exact project id or an explicit path (such as ./name) inside a project.", + ); + session.mockReturnValue( + Effect.fail(new McpBridge.AcpMcpBridgeError({ message: "synthetic connection refused" })), + ); + for (const run of [runProject, runThread]) { + const failed = yield* run(["list", ...flags]).pipe(Effect.result); + assert(failed._tag === "Failure"); + assert.isFalse(Runtime.getErrorReported(failed.failure)); + assert.include( + String((yield* TestConsole.errorLines).at(-1)), + "Could not reach the T3 Code server", + ); + } + for (const run of [runProject, runThread]) { + const failed = yield* run(["list", "--base-dir", `${baseDir}/offline`]).pipe(Effect.result); + assert(failed._tag === "Failure"); + assert.isFalse(Runtime.getErrorReported(failed.failure)); + assert.equal( + (yield* TestConsole.errorLines).at(-1), + `No running T3 Code server uses ${baseDir}/offline. Start T3 Code, then retry.`, + ); + } + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.WorkingDirectory, "/work/alpha"), + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + ), + ), + ), +); + +it.effect("thread pagination retries reordering without duplicate identities", () => + Effect.gen(function* () { + let scan = 0; + const a = thread("a", "alpha", "running"); + const b = thread("b", "alpha", "running"); + const c = thread("c", "alpha", "running"); + const call = ((tool: string, args: Readonly>) => { + assert.equal(tool, "t3_thread_list"); + if (args.cursor === 0) scan++; + const rows = + scan === 1 ? (args.cursor === 0 ? [a, b] : [b]) : args.cursor === 0 ? [c, a] : [b]; + return Effect.succeed({ threads: rows, total: 3, nextCursor: args.cursor === 0 ? 2 : null }); + }) as ThreadTools["call"]; + const result = yield* listAllThreads({ call }, { allProjects: true }); + assert.deepStrictEqual( + result.map((row) => row.threadId), + ["c", "a", "b"], + ); + assert.equal(scan, 3); + }), +); + +it.effect( + "discovery deadlines cover initialization and listing without limiting the callback", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-timeout-" }); + yield* persistServerRuntimeState({ + path: `${baseDir}/userdata/server-runtime.json`, + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3773, + }), + }); + for (const phase of ["initialize", "list", "callback"] as const) { + const started = yield* Deferred.make(); + const stalled = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)); + using _session = vi + .spyOn(McpBridge, "mcpToolSession") + .mockReturnValue( + phase === "initialize" ? stalled : Effect.succeed({ call: () => stalled }), + ); + const program = withThreadTools( + { baseDir: Option.some(baseDir) }, + (tools) => + phase === "callback" ? stalled : listAllThreads(tools, { allProjects: true }), + { access: "read-only", quietLogs: true }, + ); + const fiber = yield* Command.runWith( + Command.make("probe").pipe(Command.withHandler(() => program)), + { version: "0.0.0" }, + )([]).pipe(Effect.result, Effect.forkChild); + yield* Deferred.await(started); + yield* TestClock.adjust("10 seconds"); + if (phase === "callback") { + assert.isUndefined(fiber.pollUnsafe()); + yield* Fiber.interrupt(fiber); + } else { + const result = yield* Fiber.join(fiber); + assert(result._tag === "Failure"); + assert.include(String(result.failure), "Could not reach"); + assert.include(String(result.failure), "timed out"); + } + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + ), + ), + ), +); + +it.effect("discovery aborts stalled HTTP headers and bodies and closes MCP sessions", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-discovery-http-" }); + yield* persistServerRuntimeState({ + path: `${baseDir}/userdata/server-runtime.json`, + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3773, + }), + }); + for (const phase of ["initialize", "t3_project_list", "t3_thread_list", "DELETE"]) { + for (const stall of phase === "DELETE" ? ["headers"] : ["headers", "body"]) { + const started = yield* Deferred.make(); + let deleted = false; + let aborted = false; + using _fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => { + if (init?.method === "DELETE") { + deleted = true; + if (phase !== "DELETE") return new Response(null, { status: 204 }); + } + const message = ( + init?.method === "DELETE" + ? { id: "cleanup", method: "DELETE" } + : JSON.parse(String(init?.body)) + ) as { + id: string; + method: string; + params?: { name?: string }; + }; + const method = message.params?.name ?? message.method; + if (method === phase) { + if (stall === "headers") { + return new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => { + aborted = true; + reject(new Error("aborted")); + }); + Deferred.doneUnsafe(started, Effect.void); + }); + } + return new Response( + new ReadableStream({ + start(controller) { + init?.signal?.addEventListener("abort", () => { + aborted = true; + controller.error(new Error("aborted")); + }); + Deferred.doneUnsafe(started, Effect.void); + }, + cancel() { + aborted = true; + }, + }), + { + headers: { + "content-type": "text/event-stream", + "mcp-session-id": "timeout-session", + }, + }, + ); + } + if (method === "initialize") + return Response.json( + { id: message.id, result: { protocolVersion: "2025-06-18" } }, + { headers: { "mcp-session-id": "timeout-session" } }, + ); + if (message.method === "tools/call") return Response.json({ id: message.id, result: {} }); + return new Response(null, { status: 202 }); + }); + const program = withThreadTools( + { baseDir: Option.some(baseDir) }, + (tools) => tools.call(phase === "DELETE" ? "t3_project_list" : phase, {}, Schema.Unknown), + { access: "read-only", quietLogs: true }, + ); + const fiber = yield* Command.runWith( + Command.make("probe").pipe(Command.withHandler(() => program)), + { version: "0.0.0" }, + )([]).pipe(Effect.result, Effect.forkChild); + yield* Deferred.await(started); + yield* TestClock.adjust("10 seconds"); + const result = yield* Fiber.join(fiber); + if (phase === "DELETE") assert(result._tag === "Success"); + else { + assert(result._tag === "Failure"); + assert.include(String(result.failure), "Could not reach"); + } + assert.isTrue(aborted, `${phase} ${stall}`); + assert.equal(deleted, phase !== "initialize" || stall === "body"); + } + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + ), + ), + ), +); diff --git a/apps/server/src/cli/discovery.ts b/apps/server/src/cli/discovery.ts new file mode 100644 index 0000000000000..029b9811d0f8d --- /dev/null +++ b/apps/server/src/cli/discovery.ts @@ -0,0 +1,301 @@ +import { + OrchestratorMcpFailure, + OrchestratorMcpThreadListResult, + ModelSelection, + ProjectId, + type AuthMcpClientAccess, + type OrchestratorMcpThreadListInput, + type OrchestratorMcpThreadListItem, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as References from "effect/References"; +import * as Runtime from "effect/Runtime"; +import * as Schema from "effect/Schema"; +import { GlobalFlag } from "effect/cli"; +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as ServerConfig from "../config.ts"; +import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; +import { expandHomePath } from "../os-jank.ts"; +import { readLiveServerRuntimeState } from "../serverRuntimeState.ts"; +import { resolveCliAuthConfig } from "./config.ts"; + +class ThreadServerNotRunningError extends Schema.TaggedError()( + "ThreadServerNotRunningError", + { baseDir: Schema.String }, +) { + override readonly [Runtime.errorReported] = false; + override get message(): string { + return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`; + } +} + +class ThreadServerUnreachableError extends Schema.TaggedError()( + "ThreadServerUnreachableError", + { origin: Schema.String, cause: Schema.Defect() }, +) { + override readonly [Runtime.errorReported] = false; + override get message(): string { + const reason = this.cause instanceof Error ? ` ${this.cause.message}` : ""; + return `Could not reach the T3 Code server at ${this.origin}.${reason}`; + } +} + +class ThreadToolFailedError extends Schema.TaggedError()( + "ThreadToolFailedError", + { tool: Schema.String, detail: Schema.String }, +) { + override readonly [Runtime.errorReported] = false; + override get message(): string { + return this.detail; + } +} + +export class DiscoveryProjectNotFoundError extends Schema.TaggedError()( + "DiscoveryProjectNotFoundError", + { identifier: Schema.String }, +) { + override readonly [Runtime.errorReported] = false; + override get message() { + return `No T3 Code project matches '${this.identifier}'. Pass an exact project id or an explicit path (such as ./name) inside a project.`; + } +} + +export const DiscoveryCliError = Schema.Union([ + ThreadServerNotRunningError, + ThreadServerUnreachableError, + ThreadToolFailedError, + DiscoveryProjectNotFoundError, +]); +const isDiscoveryCliError = Schema.is(DiscoveryCliError); +export const reportDiscoveryErrors = (effect: Effect.Effect) => + effect.pipe( + Effect.tapError((error) => + isDiscoveryCliError(error) ? Console.error(error.message) : Effect.void, + ), + ); + +const decodeFailureText = Schema.decodeUnknownOption(Schema.fromJsonString(OrchestratorMcpFailure)); +const ToolResult = Schema.Struct({ + isError: Schema.optional(Schema.Boolean), + structuredContent: Schema.optional(Schema.Unknown), + content: Schema.optional( + Schema.Array(Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) })), + ), +}); + +const decodeToolResult = Schema.decodeUnknownEffect(ToolResult); + +const ProjectListResult = Schema.Struct({ + projects: Schema.Array( + Schema.Struct({ + id: ProjectId, + title: Schema.String, + workspaceRoot: Schema.String, + defaultModelSelection: Schema.NullOr(ModelSelection).pipe( + Schema.withDecodingDefault(Effect.succeed(null)), + ), + }), + ), + nextCursor: Schema.NullOr(Schema.Int), +}); + +const toolFailureDetail = (result: typeof ToolResult.Type) => { + const text = result.content?.find((part) => part.text !== undefined)?.text ?? ""; + return Option.match(decodeFailureText(text), { + onNone: () => text || "The tool call failed.", + onSome: (failure) => failure.message, + }); +}; + +const DISCOVERY_REQUEST_TIMEOUT = "10 seconds"; + +export const isExplicitProjectPath = (identifier: string) => + /^(?:\.{1,2}(?:[\\/]|$)|[\\/]|~(?:[\\/]|$)|[A-Za-z]:[\\/])/.test(identifier); + +const makeThreadTools = (session: McpToolSession, origin: string) => { + const unexpected = (tool: string) => + new ThreadToolFailedError({ + tool, + detail: `The server sent an unexpected ${tool} result. Update the t3 CLI to match the server.`, + }); + return { + call: Effect.fn("cli.thread.callTool")(function* >( + tool: string, + args: Readonly>, + schema: S, + ): Effect.fn.Return { + const request = session.call(tool, args); + const raw = yield* ( + tool === "t3_project_list" || tool === "t3_thread_list" + ? request.pipe(Effect.timeout(DISCOVERY_REQUEST_TIMEOUT)) + : request + ).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause }))); + const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool))); + if (result.isError === true) { + return yield* new ThreadToolFailedError({ tool, detail: toolFailureDetail(result) }); + } + return yield* Schema.decodeUnknownEffect(schema)(result.structuredContent).pipe( + Effect.mapError(() => unexpected(tool)), + ); + }), + }; +}; +export type ThreadTools = ReturnType; + +/** + * Signs in as a short-lived MCP client of the running server, the same way an + * outside agent does, and revokes that session when the command ends. + */ +export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* ( + flags: { readonly baseDir: Option.Option; readonly json?: boolean }, + run: (tools: ThreadTools) => Effect.Effect, + options?: { readonly access?: AuthMcpClientAccess; readonly quietLogs?: boolean }, +) { + const logLevel = yield* GlobalFlag.LogLevel; + const quietLogs = options?.quietLogs ?? flags.json ?? false; + const config = yield* resolveCliAuthConfig(flags, logLevel, { quietLogs }); + const minimumLogLevel = quietLogs ? "Error" : config.logLevel; + return yield* Effect.gen(function* () { + const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath); + if (Option.isNone(runtimeState)) { + return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir }); + } + const origin = runtimeState.value.origin; + const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; + const issued = yield* Effect.acquireRelease( + environmentAuth.issueMcpClientSession({ + label: "t3 thread cli", + // The CLI runs as the machine's owner. New threads still start at + // the project's default mode, never at this ceiling by default. + access: options?.access ?? "full-access", + peerLink: false, + client: { deviceType: "bot" }, + }), + (session) => + environmentAuth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })), + ); + const session = yield* mcpToolSession({ + endpoint: new URL("/mcp", origin).href, + authorization: `Bearer ${issued.token}`, + clientName: "t3-thread-cli", + }).pipe( + Effect.timeout(DISCOVERY_REQUEST_TIMEOUT), + Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })), + ); + return yield* run(makeThreadTools(session, origin)); + }).pipe( + Effect.scoped, + Effect.provideService(References.MinimumLogLevel, minimumLogLevel), + Effect.provide( + EnvironmentAuth.layerRuntime.pipe( + Layer.provideMerge(ServerConfig.layer(config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), + ), + ), + ); +}); + +export const resolveDiscoveryProject = Effect.fn("cli.discovery.resolveProject")(function* < + P extends { + readonly id: ProjectId; + readonly workspaceRoot: string; + }, +>(projects: ReadonlyArray

, identifier: string) { + const byId = projects.find((project) => project.id === identifier); + if (byId !== undefined) return byId; + if (!isExplicitProjectPath(identifier)) { + return yield* new DiscoveryProjectNotFoundError({ identifier }); + } + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + // Stored roots keep the path the project was added with, which may pass + // through a symlink (macOS /tmp), so both sides compare as real paths. + const realPath = (value: string) => + fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value)); + const target = yield* realPath( + path.resolve(yield* HostProcess.WorkingDirectory, yield* expandHomePath(identifier)), + ); + const roots = yield* Effect.forEach(projects, (project) => + Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })), + ); + const containing = roots + .filter(({ root }) => { + const relative = path.relative(root, target); + return ( + relative === "" || + (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ); + }) + .toSorted((left, right) => right.root.length - left.root.length)[0]; + if (containing === undefined) { + return yield* new DiscoveryProjectNotFoundError({ identifier }); + } + return containing.project; +}); + +export const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* ( + tools: ThreadTools, +) { + const projects: Array<(typeof ProjectListResult.Type)["projects"][number]> = []; + let cursor: number | null = 0; + while (cursor !== null) { + const page: typeof ProjectListResult.Type = yield* tools.call( + "t3_project_list", + { cursor, limit: 100 }, + ProjectListResult, + ); + projects.push(...page.projects); + cursor = page.nextCursor; + } + return projects; +}); + +export const listAllThreads = Effect.fn("cli.discovery.listAllThreads")(function* ( + tools: ThreadTools, + input: Pick< + OrchestratorMcpThreadListInput, + "projectId" | "allProjects" | "statuses" | "includeSubagents" + >, +) { + let previousIds: string | undefined; + for (let attempt = 0; attempt < 4; attempt++) { + const threads = new Map(); + let cursor: number | null = 0; + let paginated = false; + let total = 0; + while (cursor !== null) { + const page: OrchestratorMcpThreadListResult = yield* tools.call( + "t3_thread_list", + { ...input, includeSubagents: true, limit: 100, cursor }, + OrchestratorMcpThreadListResult, + ); + for (const thread of page.threads) threads.set(thread.threadId, thread); + total = page.total; + cursor = page.nextCursor; + paginated ||= cursor !== null; + } + const ids = [...threads.keys()].sort().join("\n"); + // Offset pages can shift during a turn; verify membership with a second scan. + if ( + threads.size === total && + ((!paginated && previousIds === undefined) || ids === previousIds) + ) { + return [...threads.values()] + .filter( + (thread) => input.includeSubagents === true || thread.relationshipToParent !== "subagent", + ) + .toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + } + previousIds = ids; + } + return yield* new ThreadToolFailedError({ + tool: "t3_thread_list", + detail: "Thread listing changed while paging. Retry when activity has settled.", + }); +}); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index d2e84e0d4f4f5..8238c66dc02a1 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -1,12 +1,16 @@ import { AuthStandardClientScopes, CommandId, + DEFAULT_SERVER_SETTINGS, + ServerSettings as ServerSettingsSchema, EnvironmentHttpCommonError, PROJECT_TRACKED_FOLDERS_MAX, type ProjectMutation, type ProjectSnapshot, ProjectId, } from "@t3tools/contracts"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { fromLenientJson } from "@t3tools/shared/schemaJson"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -35,6 +39,12 @@ import * as ServerSettings from "../serverSettings.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { discoverFolders, mergeProjectFolders } from "../workspace/WorkspaceFolders.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; +import { + reportDiscoveryErrors, + withThreadTools, + listAllProjects, + listAllThreads, +} from "./discovery.ts"; import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as RunningServer from "./runningServer.ts"; @@ -556,7 +566,75 @@ const projectRenameCommand = Command.make("rename", { ), ); +const encodeDiscoveryJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +// The app saves a project's model in settings.json; the project record keeps only a pre-fold value. +const decodeProjectModelSettings = Schema.decodeUnknownOption( + fromLenientJson( + Schema.Struct({ + projectSettingsOverrides: ServerSettingsSchema.fields.projectSettingsOverrides, + projectSettingsFolded: ServerSettingsSchema.fields.projectSettingsFolded, + }), + ), +); + +const projectListCommand = Command.make("list", { + ...projectLocationFlags, + json: Flag.Boolean("json").pipe(Flag.withDefault(false)), +}).pipe( + Command.withDescription("List projects, their default models, and thread counts by status."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.project.list")(function* (tools) { + const snapshot = { + projects: yield* listAllProjects(tools), + threads: yield* listAllThreads(tools, { allProjects: true }), + }; + const { settingsPath } = yield* ServerConfig.ServerConfig; + const settingsJson = yield* (yield* FileSystem.FileSystem) + .readFileString(settingsPath) + .pipe(Effect.orElseSucceed(() => "{}")); + const settings = { + ...DEFAULT_SERVER_SETTINGS, + ...Option.getOrUndefined(decodeProjectModelSettings(settingsJson)), + }; + const countsByProject = new Map>(); + for (const thread of snapshot.threads) { + const counts = countsByProject.get(thread.projectId) ?? {}; + counts[thread.status] = (counts[thread.status] ?? 0) + 1; + countsByProject.set(thread.projectId, counts); + } + const projects = snapshot.projects.map((project) => { + const threadCounts = countsByProject.get(project.id) ?? {}; + return { + id: project.id, + title: project.title, + workspaceRoot: project.workspaceRoot, + defaultModelSelection: + resolveProjectSettings(settings, project.id, project).overrides + .defaultModelSelection ?? null, + threadCounts, + }; + }); + if (flags.json) return yield* Console.log(encodeDiscoveryJson(projects)); + for (const project of projects) { + const model = project.defaultModelSelection; + yield* Console.log( + `${project.id} ${project.title} ${project.workspaceRoot} ${model === null ? "default" : `${model.instanceId}/${model.model}`} ${encodeDiscoveryJson(project.threadCounts)}`, + ); + } + }), + { access: "read-only", quietLogs: flags.json }, + ).pipe(reportDiscoveryErrors), + ), +); + export const projectCommand = Command.make("project").pipe( Command.withDescription("Manage projects."), - Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]), + Command.withSubcommands([ + projectListCommand, + projectAddCommand, + projectRemoveCommand, + projectRenameCommand, + ]), ); diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 49887ee0bb7cc..3fa79665c5b1e 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -18,6 +18,7 @@ import * as TestConsole from "effect/testing/TestConsole"; import { Command } from "effect/cli"; import { vi } from "vite-plus/test"; +import type { ThreadTools } from "./discovery.ts"; import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts"; import { makePersistedServerRuntimeState, @@ -29,7 +30,6 @@ import { readLatestMessages, resolveProject, threadCommand, - type ThreadTools, titleFromMessage, waitForRun, } from "./thread.ts"; @@ -180,9 +180,11 @@ it.effect( port: 3_773, }), }); + const calls: string[] = []; using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( Effect.succeed({ call: (tool, args) => { + calls.push(tool); switch (tool) { case "t3_project_list": return Effect.succeed({ structuredContent: { projects, nextCursor: null } }); @@ -197,6 +199,23 @@ it.effect( }), ); + const unknownId = "e7a60774-3d3e-4ed7-9147-b0cfce631234"; + yield* fs.makeDirectory(path.join(cwd, unknownId)); + for (const args of [ + ["start", unknownId, "Do not dispatch"], + ["list", "--project", unknownId], + ]) { + const failed = yield* Command.runWith(threadCommand, { version: "0.0.0" })([ + ...args, + "--base-dir", + baseDir, + ]).pipe(Effect.provideService(HostProcess.WorkingDirectory, cwd), Effect.result); + assert(failed._tag === "Failure"); + assert.deepStrictEqual(calls, ["t3_project_list"]); + assert.isFalse(yield* fs.exists(path.join(baseDir, "userdata", "statev2.sqlite"))); + calls.length = 0; + } + for (const [identifier, expectedProjectId] of [ ["intended-project", "intended-project"], ["~/literal-id", "~/literal-id"], @@ -699,7 +718,7 @@ it.live("resolves a path inside a git worktree of the project's repository to th assert.deepStrictEqual(yield* resolveFrom([sample], worktree), sample); assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample); - assert.deepStrictEqual(yield* resolveFrom([sample], worktree, "pkg/index.ts"), sample); + assert.deepStrictEqual(yield* resolveFrom([sample], worktree, "./pkg/index.ts"), sample); assert.deepStrictEqual(yield* resolveFrom([featureProject], featureWorktree), featureProject); const ambiguous = yield* Effect.flip(resolveFrom([sample, featureProject], featureWorktree)); assert.strictEqual(ambiguous._tag, "ThreadUsageError"); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index e63e762237e85..e7ed66a05bacd 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -1,6 +1,4 @@ import { - OrchestratorMcpFailure, - OrchestratorMcpThreadListResult, OrchestratorMcpThreadReadResult, OrchestratorMcpThreadSendResult, OrchestratorMcpThreadWaitResult, @@ -9,32 +7,36 @@ import { ThreadId, TrimmedNonEmptyString, type OrchestratorMcpThreadDetail, - type OrchestratorMcpThreadListItem, type OrchestratorMcpThreadRun, type OrchestratorMcpThreadStatus, + OrchestrationV2RunStatus, type OrchestratorMcpThreadTimelineItem, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; -import * as References from "effect/References"; import * as Runtime from "effect/Runtime"; import * as Schema from "effect/Schema"; import * as Stdio from "effect/Stdio"; import * as Stream from "effect/Stream"; -import { Argument, Command, Flag, GlobalFlag } from "effect/cli"; +import { Argument, Command, Flag } from "effect/cli"; -import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; -import * as ServerConfig from "../config.ts"; -import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; import { expandHomePath } from "../os-jank.ts"; import * as ProcessRunner from "../processRunner.ts"; -import { readLiveServerRuntimeState } from "../serverRuntimeState.ts"; -import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; +import { + DiscoveryCliError, + DiscoveryProjectNotFoundError, + resolveDiscoveryProject, + isExplicitProjectPath, + withThreadTools, + listAllProjects, + listAllThreads, + type ThreadTools, +} from "./discovery.ts"; +import { projectLocationFlags } from "./config.ts"; /** * Short enough that a run which stops to ask the user something is noticed @@ -54,37 +56,6 @@ const READ_PAGE_LIMIT = 100; const READ_ITEM_MAX_CHARS = 20_000; const TITLE_MAX_CHARS = 80; -export class ThreadServerNotRunningError extends Schema.TaggedError()( - "ThreadServerNotRunningError", - { baseDir: Schema.String }, -) { - override readonly [Runtime.errorReported] = false; - override get message(): string { - return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`; - } -} - -export class ThreadServerUnreachableError extends Schema.TaggedError()( - "ThreadServerUnreachableError", - { origin: Schema.String, cause: Schema.Defect() }, -) { - override readonly [Runtime.errorReported] = false; - override get message(): string { - const reason = this.cause instanceof Error ? ` ${this.cause.message}` : ""; - return `Could not reach the T3 Code server at ${this.origin}.${reason}`; - } -} - -export class ThreadToolFailedError extends Schema.TaggedError()( - "ThreadToolFailedError", - { tool: Schema.String, detail: Schema.String }, -) { - override readonly [Runtime.errorReported] = false; - override get message(): string { - return this.detail; - } -} - export class ThreadUsageError extends Schema.TaggedError()("ThreadUsageError", { detail: Schema.String, }) { @@ -94,16 +65,6 @@ export class ThreadUsageError extends Schema.TaggedError()("Th } } -export class ThreadProjectNotFoundError extends Schema.TaggedError()( - "ThreadProjectNotFoundError", - { identifier: Schema.String }, -) { - override readonly [Runtime.errorReported] = false; - override get message(): string { - return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`; - } -} - /** Exit code 2 lets a script tell "needs a human" apart from a failed run. */ export class ThreadNeedsInputError extends Schema.TaggedError()( "ThreadNeedsInputError", @@ -129,11 +90,8 @@ export class ThreadRunEndedError extends Schema.TaggedError } const ThreadCliError = Schema.Union([ - ThreadServerNotRunningError, - ThreadServerUnreachableError, - ThreadToolFailedError, ThreadUsageError, - ThreadProjectNotFoundError, + DiscoveryCliError, ThreadNeedsInputError, ThreadRunEndedError, ]); @@ -150,116 +108,15 @@ const reportThreadErrors = (effect: Effect.Effect) => ), ); -const decodeFailureText = Schema.decodeUnknownOption(Schema.fromJsonString(OrchestratorMcpFailure)); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); const printJson = (value: unknown) => Console.log(encodeJson(value)); -const ToolResult = Schema.Struct({ - isError: Schema.optional(Schema.Boolean), - structuredContent: Schema.optional(Schema.Unknown), - content: Schema.optional( - Schema.Array(Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) })), - ), -}); - -const decodeToolResult = Schema.decodeUnknownEffect(ToolResult); - -const ProjectListResult = Schema.Struct({ - projects: Schema.Array( - Schema.Struct({ id: ProjectId, title: Schema.String, workspaceRoot: Schema.String }), - ), - nextCursor: Schema.NullOr(Schema.Int), -}); - const ThreadLaunchResult = Schema.Struct({ threadId: ThreadId, projectId: ProjectId, runId: Schema.NullOr(RunId), }); -const toolFailureDetail = (result: typeof ToolResult.Type) => { - const text = result.content?.find((part) => part.text !== undefined)?.text ?? ""; - return Option.match(decodeFailureText(text), { - onNone: () => text || "The tool call failed.", - onSome: (failure) => failure.message, - }); -}; - -const makeThreadTools = (session: McpToolSession, origin: string) => { - const unexpected = (tool: string) => - new ThreadToolFailedError({ - tool, - detail: `The server sent an unexpected ${tool} result. Update the t3 CLI to match the server.`, - }); - return { - call: Effect.fn("cli.thread.callTool")(function* >( - tool: string, - args: Readonly>, - schema: S, - ): Effect.fn.Return { - const raw = yield* session - .call(tool, args) - .pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause }))); - const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool))); - if (result.isError === true) { - return yield* new ThreadToolFailedError({ tool, detail: toolFailureDetail(result) }); - } - return yield* Schema.decodeUnknownEffect(schema)(result.structuredContent).pipe( - Effect.mapError(() => unexpected(tool)), - ); - }), - }; -}; -export type ThreadTools = ReturnType; - -/** - * Signs in as a short-lived MCP client of the running server, the same way an - * outside agent does, and revokes that session when the command ends. - */ -const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* ( - flags: { readonly baseDir: Option.Option; readonly json: boolean }, - run: (tools: ThreadTools) => Effect.Effect, -) { - const logLevel = yield* GlobalFlag.LogLevel; - const config = yield* resolveCliAuthConfig(flags, logLevel, { quietLogs: flags.json }); - const minimumLogLevel = flags.json ? "Error" : config.logLevel; - return yield* Effect.gen(function* () { - const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath); - if (Option.isNone(runtimeState)) { - return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir }); - } - const origin = runtimeState.value.origin; - const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; - const issued = yield* Effect.acquireRelease( - environmentAuth.issueMcpClientSession({ - label: "t3 thread cli", - // The CLI runs as the machine's owner. New threads still start at - // the project's default mode, never at this ceiling by default. - access: "full-access", - peerLink: false, - client: { deviceType: "bot" }, - }), - (session) => - environmentAuth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })), - ); - const session = yield* mcpToolSession({ - endpoint: new URL("/mcp", origin).href, - authorization: `Bearer ${issued.token}`, - clientName: "t3-thread-cli", - }).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause }))); - return yield* run(makeThreadTools(session, origin)); - }).pipe( - Effect.scoped, - Effect.provideService(References.MinimumLogLevel, minimumLogLevel), - Effect.provide( - EnvironmentAuth.layerRuntime.pipe( - Layer.provide(ServerConfig.layer(config)), - Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), - ), - ), - ); -}); - const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argument: string) { const text = argument === "-" @@ -273,21 +130,6 @@ const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argum return text; }); -const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools: ThreadTools) { - const projects: Array<(typeof ProjectListResult.Type)["projects"][number]> = []; - let cursor: number | null = 0; - while (cursor !== null) { - const page: typeof ProjectListResult.Type = yield* tools.call( - "t3_project_list", - { cursor, limit: 100 }, - ProjectListResult, - ); - projects.push(...page.projects); - cursor = page.nextCursor; - } - return projects; -}); - /** The checkouts of the git repository at `directory`, or none outside a repository. */ const listGitCheckouts = Effect.fn("cli.thread.listGitCheckouts")(function* (directory: string) { const processRunner = yield* ProcessRunner.ProcessRunner; @@ -323,6 +165,9 @@ export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( const byId = projects.find((project) => project.id === identifier); if (byId !== undefined) return byId; + if (!isExplicitProjectPath(identifier)) { + return yield* new DiscoveryProjectNotFoundError({ identifier }); + } const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; // Stored roots keep the path the project was added with, which may pass @@ -347,7 +192,9 @@ export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( .filter(({ root }) => contains(root, candidate)) .toSorted((left, right) => right.root.length - left.root.length)[0]?.project; - const containing = deepestContaining(target); + const containing = yield* resolveDiscoveryProject(projects, identifier).pipe( + Effect.catchTags({ DiscoveryProjectNotFoundError: () => Effect.undefined }), + ); if (containing !== undefined) return containing; const targetInfo = yield* fileSystem.stat(target).pipe(Effect.option); const gitDirectory = @@ -360,7 +207,7 @@ export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( .filter((checkout) => contains(checkout, target)) .toSorted((left, right) => right.length - left.length)[0]; if (ownCheckout === undefined) { - return yield* new ThreadProjectNotFoundError({ identifier }); + return yield* new DiscoveryProjectNotFoundError({ identifier }); } const relative = path.relative(ownCheckout, target); const matches = new Map(); @@ -371,7 +218,7 @@ export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( } const [match, ...others] = matches.values(); if (match === undefined) { - return yield* new ThreadProjectNotFoundError({ identifier }); + return yield* new DiscoveryProjectNotFoundError({ identifier }); } if (others.length > 0) { const names = [match, ...others].map((project) => `${project.title} (${project.id})`); @@ -834,45 +681,66 @@ const decodeThreadId = (value: string) => const threadListCommand = Command.make("list", { ...projectLocationFlags, project: Flag.String("project").pipe( - Flag.withDescription("Project id or a path inside the project. Defaults to this directory."), - Flag.withDefault("."), + Flag.withDescription( + "Exact project id or an explicit path (./, ../, /, ~) inside the project. Defaults to this directory.", + ), + Flag.optional, + ), + allProjects: Flag.Boolean("all-projects").pipe( + Flag.withDescription("List threads across all projects instead of the current project."), + Flag.withDefault(false), + ), + includeSubagents: Flag.Boolean("include-subagents").pipe( + Flag.withDescription("Include subagent threads when checking active work across projects."), + Flag.withDefault(false), + ), + status: Flag.Literals("status", ["idle", ...OrchestrationV2RunStatus.literals]).pipe( + Flag.withDescription("Filter by thread status, such as running, waiting, or completed."), + Flag.optional, ), json: jsonFlag, }).pipe( - Command.withDescription("List a project's threads, newest first."), + Command.withDescription("List a project's threads, most recently updated first."), Command.withHandler((flags) => - withThreadTools( - flags, - Effect.fn("cli.thread.list")(function* (tools) { - const project = yield* resolveProject(tools, flags.project); - const threads: Array = []; - let cursor: number | null = 0; - while (cursor !== null) { - const page: OrchestratorMcpThreadListResult = yield* tools.call( - "t3_thread_list", - { projectId: project.id, includeSubagents: true, limit: 100, cursor }, - OrchestratorMcpThreadListResult, - ); - threads.push( - ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"), - ); - cursor = page.nextCursor; - } - if (flags.json) { - return yield* printJson(threads); - } - for (const thread of threads) { - yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`); - } - }), - ).pipe(reportThreadErrors), + Effect.gen(function* () { + if (flags.allProjects && Option.isSome(flags.project)) { + return yield* new ThreadUsageError({ + detail: "--all-projects and --project cannot be used together.", + }); + } + yield* withThreadTools( + flags, + Effect.fn("cli.thread.list")(function* (tools) { + const project = flags.allProjects + ? undefined + : yield* resolveProject( + tools, + Option.getOrElse(flags.project, () => "."), + ); + const threads = yield* listAllThreads(tools, { + includeSubagents: flags.includeSubagents, + ...(project === undefined ? { allProjects: true } : { projectId: project.id }), + ...(Option.isSome(flags.status) ? { statuses: [flags.status.value] } : {}), + }); + if (flags.json) return yield* printJson(threads); + for (const thread of threads) { + yield* Console.log( + `${thread.threadId} ${flags.allProjects ? `${thread.projectId} ` : ""}${thread.status.padEnd(11)} ${thread.title}`, + ); + } + }), + { access: "read-only", quietLogs: flags.json }, + ); + }).pipe(reportThreadErrors), ), ); const threadStartCommand = Command.make("start", { ...projectLocationFlags, project: Argument.String("project").pipe( - Argument.withDescription("Project id or a path inside the project, such as ."), + Argument.withDescription( + "Exact project id or an explicit path (./, ../, /, ~) inside the project, such as .", + ), ), message: messageArgument, title: Flag.String("title").pipe( diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index 596c594a0a343..cc7b24774dba0 100644 --- a/apps/server/src/cloud/CliTokenManager.ts +++ b/apps/server/src/cloud/CliTokenManager.ts @@ -280,6 +280,13 @@ export class CloudCliTokenManager extends Context.Service< CloudCliTokenManagerError | Terminal.QuitError >; readonly getExisting: Effect.Effect, CloudCliTokenManagerError>; + readonly peek: Effect.Effect< + Option.Option<{ + readonly token: PersistedToken; + readonly needsRefresh: boolean; + }>, + CloudCliTokenManagerError + >; readonly hasCredential: Effect.Effect; readonly store: (token: PersistedToken) => Effect.Effect; readonly clear: Effect.Effect; @@ -605,6 +612,17 @@ export const make = Effect.gen(function* () { Effect.provide(services), ), ); + const peek = semaphore.withPermits(1)( + Effect.gen(function* () { + const stored = yield* read(); + const now = yield* Clock.currentTimeMillis; + return Option.map(stored, (token) => ({ + token, + needsRefresh: token.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS <= now, + })); + }).pipe(Effect.mapError((cause) => new CloudCliCredentialReadError({ cause }))), + ); + const hasCredential = semaphore.withPermits(1)( read().pipe( Effect.map(Option.isSome), @@ -639,7 +657,7 @@ export const make = Effect.gen(function* () { ); }); - return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear }); + return CloudCliTokenManager.of({ get, getExisting, peek, hasCredential, store, clear }); }); export const layer = Layer.effect(CloudCliTokenManager, make); diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts index a71a8f00b81c7..fa6cf7f2cf00a 100644 --- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts +++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts @@ -237,6 +237,7 @@ describe("releaseManagedTunnelOnShutdown", () => { CliTokenManager.CloudCliTokenManager.of({ get: unusedSecretStoreOperation(), getExisting: harness.getExisting ?? Effect.succeedSome(cliToken), + peek: unusedSecretStoreOperation(), hasCredential: unusedSecretStoreOperation(), store: () => unusedSecretStoreOperation(), clear: unusedSecretStoreOperation(), diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index 11bd819f4b88b..300f46ee35d51 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -100,14 +100,18 @@ export const mcpToolSession = ( const send = Effect.fn("AcpMcpStdioBridge.send")(function* ( message: unknown, - ): Effect.fn.Return, AcpMcpBridgeError> { + ): Effect.fn.Return, AcpMcpBridgeError, Scope.Scope> { + const controller = yield* Effect.acquireRelease( + Effect.sync(() => new AbortController()), + (controller) => Effect.sync(() => controller.abort()), + ); const response = yield* Effect.tryPromise({ - try: (signal) => + try: () => fetchImplementation(options.endpoint, { method: "POST", headers: { "content-type": "application/json", ...headers() }, body: JSON.stringify(message), - signal, + signal: controller.signal, }), catch: bridgeError, }); @@ -129,7 +133,7 @@ export const mcpToolSession = ( return Effect.void; }); return payloads; - }); + }, Effect.scoped); const request = Effect.fn("AcpMcpStdioBridge.request")(function* ( method: string, @@ -150,10 +154,14 @@ export const mcpToolSession = ( sessionId === null ? Effect.void : Effect.tryPromise({ - try: () => - fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }), + try: (signal) => + fetchImplementation(options.endpoint, { method: "DELETE", headers: headers(), signal }), catch: bridgeError, - }).pipe(Effect.flatMap(discardResponseBody), Effect.ignore), + }).pipe( + Effect.flatMap(discardResponseBody), + Effect.timeoutOption("10 seconds"), + Effect.ignore, + ), ); // Registered before the handshake so a session the server opened is ended diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 9c164f91c9962..77723c0474698 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -137,8 +137,52 @@ Agents without OAuth support cannot connect. ## Scripts on the host -On the machine that runs the environment, `t3 thread` uses the same tools -without a sign-in: +On the machine that runs the environment, the CLI can discover projects and +threads without opening the app or an interactive sign-in. The environment’s +server must be running; the app window can be closed. Use `--base-dir ` +when the server uses a non-default T3 home. + +```sh +t3 project list +t3 project list --json +t3 thread list +t3 thread list --all-projects --json +t3 thread list --all-projects --include-subagents --status running --json +t3 thread list --project --status running --json +t3 connect status --json +``` + +`project list` includes project ids, titles, workspace paths, configured default +provider/model selections, and thread counts by status. A null model selection +means the project inherits its default. Counts and `thread list` cover active +sidebar threads; archived threads and side chats are excluded. Subagents are +hidden by default. Pass `--include-subagents` to `thread list` to include them; +JSON includes `parentThreadId` and `relationshipToParent`. Project counts always +exclude subagents. +Statuses with no threads are omitted from the counts. `thread list` defaults to +`--project .`, listing the project containing the current directory. Pass +`--all-projects` to list across projects; it cannot be combined with `--project`. +Threads are listed most recently updated first. To count running work across all +projects, including children whose parents are waiting on delegation: + +```sh +t3 thread list --all-projects --include-subagents --status running --json | jq length +``` + +Project selectors exact-match ids. An unknown bare id fails, even if a directory +with that name exists. Use an explicit path (`.`, `./name`, `../name`, `/abs/path`, +or `~/name`) to select the containing project. Multi-page listings verify thread +membership with repeat reads and fail if it keeps changing; they are not an +atomic snapshot of all statuses. + +For a linked managed T3 Connect environment, `connect status` includes its public +address and MCP URL. Looking up the address requires a stored Connect credential +and access to the relay. If the lookup fails, status reports that failure; +unlinked, revoked, and publish-only links have no public MCP URL. Status never +refreshes the Connect credential. If it reports that the credential needs +refresh, run `t3 connect login` with the same `--base-dir`, then retry status. + +You can also start, message, and inspect a thread: ```sh id=$(t3 thread start . "Find why the tests are slow")