From c3b24995030e54839f98253068c1d60aae5bba2f Mon Sep 17 00:00:00 2001 From: Apollo Meijer Date: Sun, 8 Nov 2026 15:49:37 +0100 Subject: [PATCH 1/8] feat(cli): discover projects, threads, and public Connect addresses --- apps/server/src/cli/connect.ts | 49 +++- apps/server/src/cli/connectStatus.test.ts | 172 +++++++++++++ apps/server/src/cli/discovery.test.ts | 232 ++++++++++++++++++ apps/server/src/cli/discovery.ts | 148 +++++++++++ apps/server/src/cli/project.ts | 47 +++- apps/server/src/cli/thread.ts | 76 ++---- apps/server/src/mcp/OrchestratorMcpService.ts | 81 +----- .../src/orchestration-v2/threadSummary.ts | 76 ++++++ docs/user/outside-agents.md | 28 ++- 9 files changed, 781 insertions(+), 128 deletions(-) create mode 100644 apps/server/src/cli/connectStatus.test.ts create mode 100644 apps/server/src/cli/discovery.test.ts create mode 100644 apps/server/src/cli/discovery.ts create mode 100644 apps/server/src/orchestration-v2/threadSummary.ts diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 5145429e304d4..4a385cb7eee4c 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -8,7 +8,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"; @@ -148,6 +148,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; @@ -208,6 +211,11 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b ` 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 || status.linkMode !== "managed" @@ -667,6 +675,31 @@ const connectLinkCommand = Command.make("link", { ), ); +const readPublicConnectAddress = Effect.fn("cloud.cli.readPublicAddress")(function* ( + relayUrl: string, +) { + const tokens = yield* CliTokenManager.CloudCliTokenManager; + const token = yield* tokens.getExisting; + if (Option.isNone(token)) return null; + 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.value.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 = new URL(endpoint.httpBaseUrl); + return url.protocol === "https:" ? url.host : null; +}); + const connectStatusCommand = Command.make("status", { ...projectLocationFlags, json: jsonFlag, @@ -706,6 +739,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, @@ -716,6 +757,12 @@ 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" + ? "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..89decba928e96 --- /dev/null +++ b/apps/server/src/cli/connectStatus.test.ts @@ -0,0 +1,172 @@ +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 Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +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", + ...(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"), + }); + }), + ), + }; +}); +vi.mock("../cloud/CliTokenManager.ts", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + layer: Layer.mock(actual.CloudCliTokenManager)({ + hasCredential: Effect.succeed(true), + getExisting: Effect.succeedSome({ + accessToken: "synthetic-token", + refreshToken: "refresh", + expiresAtEpochMs: 9999999999999, + }), + }), + }; +}); + +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") => ({ + 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: "https://this.example.test/", + 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 run = (mode: string, json = true) => + Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([ + "connect", + "status", + "--base-dir", + baseDir, + ...(json ? ["--json"] : []), + ]).pipe( + Effect.provide( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { TEST_LINK_MODE: mode } })), + ), + ); + yield* run("linked"); + 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); + } + fetch.mockResolvedValue(Response.json(replies("manual"))); + yield* run("linked"); + assert.isNull(decodeStatus(String((yield* TestConsole.logLines).at(-1))).mcpUrl); + 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..b53bf92e73902 --- /dev/null +++ b/apps/server/src/cli/discovery.test.ts @@ -0,0 +1,232 @@ +// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the Node HTTP boundary. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { AuthOrchestrationReadScope, AuthSessionId, EnvironmentId } from "@t3tools/contracts"; +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 Layer from "effect/Layer"; +import * as TestConsole from "effect/testing/TestConsole"; +import { Command } from "effect/cli"; +import { vi } from "vite-plus/test"; + +import { + makePersistedServerRuntimeState, + persistServerRuntimeState, +} from "../serverRuntimeState.ts"; +import { projectCommand } from "./project.ts"; +import { threadCommand } from "./thread.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.succeed(environment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(EnvironmentId.make("this-host")), + }), + Layer.mock(actual.EnvironmentAuth)({ + issueSession: (input) => { + assert.deepStrictEqual(input?.scopes, [AuthOrchestrationReadScope]); + return Effect.map(DateTime.now, (expiresAt) => ({ + sessionId: AuthSessionId.make("test-session"), + token: "synthetic-token", + method: "bearer-access-token" as const, + scopes: [AuthOrchestrationReadScope], + subject: "test", + client: { deviceType: "bot" as const }, + 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, + scripts: [], + createdAt: timestamp, + updatedAt: timestamp, + deletedAt: null, +}); +const thread = (id: string, projectId: string, status: string, updatedAt = timestamp) => ({ + id, + projectId, + title: id, + status, + updatedAt, + createdAt: timestamp, + createdBy: "user", + creationSource: "web", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-test" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id }, + forkedFrom: null, + activeProviderThreadId: null, + latestRunId: null, + activeRunId: null, + pendingRuntimeRequest: null, + latestVisibleMessage: null, + latestUserMessageAt: null, + hasActionableProposedPlan: false, + itemCount: 0, + visibleItemCount: 0, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, +}); + +it.live("lists projects and all threads through HTTP, with project and status filters", () => + Effect.gen(function* () { + const requests: Array = []; + const child = { + ...thread("child", "alpha", "running"), + lineage: { + parentThreadId: "older", + relationshipToParent: "subagent", + rootThreadId: "older", + }, + }; + const sideChat = { + ...thread("side", "alpha", "running"), + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: "side", + sideChat: true, + }, + }; + const server = yield* Effect.acquireRelease( + Effect.callback((resume) => { + const server = NodeHttp.createServer((request, response) => { + requests.push(`${request.method} ${request.url}`); + assert.equal(request.headers.authorization, "Bearer synthetic-token"); + response.setHeader("content-type", "application/json"); + if (request.url === "/api/projects") { + response.end( + JSON.stringify({ + projects: [ + project("alpha"), + project("beta"), + project("empty"), + { ...project("deleted"), deletedAt: timestamp }, + ], + updatedAt: timestamp, + }), + ); + } else if (request.url === "/api/orchestration/shell") { + assert.equal(request.headers["x-t3-orchestration-protocol"], "2"); + response.end( + JSON.stringify({ + schemaVersion: 1, + snapshotSequence: 0, + projects: [], + threads: [ + thread("older", "alpha", "completed"), + { + ...thread("newer", "beta", "completed", "2026-11-02T12:00:00.000Z"), + activityRunStatus: "running", + }, + child, + sideChat, + ], + archivedThreads: [thread("archived", "alpha", "completed")], + }), + ); + } else { + response.writeHead(404).end(); + } + }); + server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))); + }), + (server) => Effect.sync(() => server.close()), + ); + const address = server.address(); + assert(address !== null && typeof address !== "string"); + 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: address.port, + }), + }); + const runProject = Command.runWith(projectCommand, { version: "0.0.0" }); + const runThread = Command.runWith(threadCommand, { version: "0.0.0" }); + const flags = ["--base-dir", baseDir, "--json"]; + yield* runProject(["list", ...flags]); + assert.deepStrictEqual(JSON.parse(String((yield* TestConsole.logLines).at(-1) ?? "")), [ + { + id: "alpha", + title: "alpha", + workspaceRoot: "/work/alpha", + defaultModelSelection: { instanceId: "codex", model: "gpt-test" }, + threadCounts: { completed: 1 }, + }, + { + id: "beta", + title: "beta", + workspaceRoot: "/work/beta", + defaultModelSelection: null, + threadCounts: { running: 1 }, + }, + { + id: "empty", + title: "empty", + workspaceRoot: "/work/empty", + defaultModelSelection: null, + threadCounts: {}, + }, + ]); + for (const [extra, expected] of [ + [[], ["newer", "older"]], + [["--project", "alpha"], ["older"]], + [["--project", "/work/alpha/subdir"], ["older"]], + [["--status", "running"], ["newer"]], + [["--project", "alpha", "--status", "running"], []], + ] as const) { + yield* runThread(["list", ...extra, ...flags]); + const rows = JSON.parse(String((yield* TestConsole.logLines).at(-1) ?? "")) as Array<{ + threadId: string; + }>; + assert.deepStrictEqual( + rows.map((row) => row.threadId), + [...expected], + ); + } + yield* runProject(["list", "--base-dir", baseDir]); + assert.include((yield* TestConsole.logLines).join("\n"), "codex/gpt-test"); + yield* runThread(["list", "--base-dir", baseDir]); + assert.include(String((yield* TestConsole.logLines).at(-1) ?? ""), "older alpha completed"); + assert.equal(requests.length, 16); + assert.isTrue(requests.every((request) => request.startsWith("GET /api/"))); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + Layer.fresh(TestConsole.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..cab1630aa5165 --- /dev/null +++ b/apps/server/src/cli/discovery.ts @@ -0,0 +1,148 @@ +import { + AuthOrchestrationReadScope, + EnvironmentHttpApi, + ORCHESTRATION_PROTOCOL_HEADER, + ORCHESTRATION_PROTOCOL_VERSION_TEXT, + isListedThreadLineage, + type ProjectId, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; +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 Schema from "effect/Schema"; +import { GlobalFlag } from "effect/cli"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpApiClient from "effect/http-api/HttpApiClient"; + +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerConfig from "../config.ts"; +import { expandHomePath } from "../os-jank.ts"; +import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; + +class DiscoveryServerNotRunningError extends Schema.TaggedError()( + "DiscoveryServerNotRunningError", + { baseDir: Schema.String }, +) { + override get message() { + return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`; + } +} + +class DiscoveryProjectNotFoundError extends Schema.TaggedError()( + "DiscoveryProjectNotFoundError", + { identifier: Schema.String }, +) { + override get message() { + return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`; + } +} + +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; + 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; +}); + +const readSnapshot = Effect.fn("cli.discovery.readSnapshot")(function* ( + origin: string, + token: string, +) { + const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin }); + const headers = { + authorization: `Bearer ${token}`, + [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT, + } as const; + const [projects, shell] = yield* Effect.all([ + client.projects.snapshot({ headers }), + client.orchestration.shellSnapshot({ headers, query: {} }), + ]); + const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; + const environmentId = yield* identity.getEnvironmentId; + const nowMs = yield* Clock.currentTimeMillis; + const { listItemFromShell } = yield* Effect.promise( + () => import("../orchestration-v2/threadSummary.ts"), + ); + const threads = shell.threads + .filter((thread) => isListedThreadLineage(thread.lineage)) + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) || + right.id.localeCompare(left.id), + ) + .map((thread) => + listItemFromShell(thread, formatThreadLink({ environmentId, threadId: thread.id }), nowMs), + ); + return { projects: projects.projects.filter((project) => project.deletedAt === null), threads }; +}); +type DiscoverySnapshot = Effect.Success>; + +export const withDiscoverySnapshot = Effect.fn("cli.discovery.withSnapshot")(function* ( + flags: CliAuthLocationFlags, + run: (snapshot: DiscoverySnapshot) => Effect.Effect, +) { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveCliAuthConfig(flags, logLevel); + return yield* Effect.gen(function* () { + const state = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); + if (Option.isNone(state)) + return yield* new DiscoveryServerNotRunningError({ baseDir: config.baseDir }); + const auth = yield* EnvironmentAuth.EnvironmentAuth; + return yield* Effect.acquireUseRelease( + auth.issueSession({ scopes: [AuthOrchestrationReadScope], label: "t3 discovery cli" }), + (session) => + readSnapshot(state.value.origin, session.token).pipe( + Effect.timeout("10 seconds"), + Effect.flatMap(run), + ), + (session) => auth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })), + ); + }).pipe( + Effect.provide( + Layer.merge( + FetchHttpClient.layer, + EnvironmentAuth.layerRuntime.pipe( + Layer.provide(ServerConfig.layer(config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)), + ), + ), + ), + ); +}); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index f604f8eb43696..015d4fb5b9554 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -42,6 +42,7 @@ import { readPersistedServerRuntimeState, } from "../serverRuntimeState.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; +import { withDiscoverySnapshot } from "./discovery.ts"; import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; type ProjectMutationTarget = { @@ -593,7 +594,51 @@ const projectRenameCommand = Command.make("rename", { ), ); +const encodeDiscoveryJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); + +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) => + withDiscoverySnapshot( + flags, + Effect.fn("cli.project.list")(function* (snapshot) { + 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: project.defaultModelSelection, + 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)}`, + ); + } + }), + ), + ), +); + 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.ts b/apps/server/src/cli/thread.ts index 80dfad018e158..c4dec43a8d5ca 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -1,6 +1,5 @@ import { OrchestratorMcpFailure, - OrchestratorMcpThreadListResult, OrchestratorMcpThreadReadResult, OrchestratorMcpThreadSendResult, OrchestratorMcpThreadWaitResult, @@ -8,17 +7,14 @@ import { RunId, ThreadId, TrimmedNonEmptyString, - type OrchestratorMcpThreadListItem, 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"; @@ -29,8 +25,8 @@ import { Argument, Command, Flag, 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 { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { resolveDiscoveryProject, withDiscoverySnapshot } from "./discovery.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -282,31 +278,7 @@ const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( const byId = projects.find((project) => project.id === identifier); if (byId !== undefined) return byId; - 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 ThreadProjectNotFoundError({ identifier }); - } - return containing.project; + return yield* resolveDiscoveryProject(projects, identifier); }); /** Every item on a timeline view, oldest first. */ @@ -565,33 +537,33 @@ 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("Filter by project id or a path inside the project."), + Flag.optional, + ), + 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 threads across all projects, newest first."), Command.withHandler((flags) => - withThreadTools( + withDiscoverySnapshot( 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: false, limit: 100, cursor }, - OrchestratorMcpThreadListResult, - ); - threads.push(...page.threads); - cursor = page.nextCursor; - } - if (flags.json) { - return yield* printJson(threads); - } + Effect.fn("cli.thread.list")(function* (snapshot) { + const project = Option.isSome(flags.project) + ? yield* resolveDiscoveryProject(snapshot.projects, flags.project.value) + : undefined; + const threads = snapshot.threads.filter( + (thread) => + (project === undefined || thread.projectId === project.id) && + (Option.isNone(flags.status) || thread.status === flags.status.value), + ); + if (flags.json) return yield* printJson(threads); for (const thread of threads) { - yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`); + yield* Console.log( + `${thread.threadId} ${thread.projectId} ${thread.status.padEnd(11)} ${thread.title}`, + ); } }), ).pipe(reportThreadErrors), diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 9d15408483a3e..c5cd57d8886d4 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -37,11 +37,9 @@ import { type OrchestratorMcpListScheduledTasksInput, type ProjectId, type OrchestratorMcpThreadDetail, - type OrchestratorMcpThreadPullRequest, type OrchestratorMcpThreadInterruptInput, type OrchestratorMcpThreadInterruptResult, type OrchestratorMcpThreadListInput, - type OrchestratorMcpThreadListItem, type OrchestratorMcpThreadListResult, type OrchestratorMcpThreadReadInput, type OrchestratorMcpThreadReadResult, @@ -69,10 +67,6 @@ import { import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; -import { - normalizeThreadPullRequestKey, - visibleThreadPullRequests, -} from "../sourceControl/threadPullRequests.ts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -103,6 +97,12 @@ import { runOutcome } from "../orchestration-v2/RestartBackgroundNote.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import { + listItemFromShell, + threadSettlement, + threadSnooze, + threadPullRequests, +} from "../orchestration-v2/threadSummary.ts"; import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts"; import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as ProjectService from "../project/ProjectService.ts"; @@ -760,71 +760,6 @@ function threadTitle(input: { return `${detail.slice(0, end)}...`; } -function threadSettlement( - thread: Pick, -): Pick { - const settled = thread.settledOverride === "settled"; - return { - settled, - settledAt: settled && thread.settledAt !== null ? DateTime.formatIso(thread.settledAt) : null, - }; -} - -function threadSnooze( - thread: Parameters[0], - nowMs: number, -): Pick { - const snoozed = isSnoozed(thread, nowMs); - return { - snoozed, - snoozedUntil: - snoozed && thread.snoozedUntil != null ? DateTime.formatIso(thread.snoozedUntil) : null, - }; -} - -function threadPullRequests( - links: OrchestrationV2ThreadShell["pullRequests"], -): OrchestratorMcpThreadPullRequest[] { - return visibleThreadPullRequests(links ?? []).map((link) => ({ - host: normalizeThreadPullRequestKey(link).host, - repository: link.repository, - number: link.number, - url: link.url, - source: link.source, - state: link.snapshot?.state ?? null, - })); -} - -function listItemFromShell( - scope: McpInvocationScope, - shell: OrchestrationV2ThreadShell, - nowMs: number, -): OrchestratorMcpThreadListItem { - return { - threadId: shell.id, - projectId: shell.projectId, - title: shell.title, - link: threadLinkFor(scope, shell.id), - createdBy: shell.createdBy, - creationSource: shell.creationSource, - status: shell.activityRunStatus ?? shell.status, - latestRunId: shell.latestRunId, - providerInstanceId: shell.modelSelection.instanceId, - model: shell.modelSelection.model, - runtimeMode: shell.runtimeMode, - interactionMode: shell.interactionMode, - linkedPullRequest: shell.linkedPullRequest ?? null, - pullRequests: threadPullRequests(shell.pullRequests), - ...threadSettlement(shell), - ...threadSnooze(shell, nowMs), - parentThreadId: shell.lineage.parentThreadId, - relationshipToParent: shell.lineage.relationshipToParent, - itemCount: shell.visibleItemCount, - createdAt: DateTime.formatIso(shell.createdAt), - updatedAt: DateTime.formatIso(shell.updatedAt), - }; -} - function threadDetail( scope: McpInvocationScope, projection: Pick, @@ -3025,7 +2960,9 @@ const make = Effect.gen(function* () { return { projectId, currentThreadId: parent?.thread.id ?? null, - threads: page.map((shell) => listItemFromShell(scope, shell, nowMs)), + threads: page.map((shell) => + listItemFromShell(shell, threadLinkFor(scope, shell.id), nowMs), + ), nextCursor, total: filtered.length, } satisfies OrchestratorMcpThreadListResult; diff --git a/apps/server/src/orchestration-v2/threadSummary.ts b/apps/server/src/orchestration-v2/threadSummary.ts new file mode 100644 index 0000000000000..6aaf0d3632867 --- /dev/null +++ b/apps/server/src/orchestration-v2/threadSummary.ts @@ -0,0 +1,76 @@ +import type { + OrchestrationV2ThreadShell, + OrchestratorMcpThreadListItem, + OrchestratorMcpThreadPullRequest, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { + normalizeThreadPullRequestKey, + visibleThreadPullRequests, +} from "../sourceControl/threadPullRequests.ts"; +import { isSnoozed } from "./ThreadSettlementService.ts"; + +export function threadSettlement( + thread: Pick, +): Pick { + const settled = thread.settledOverride === "settled"; + return { + settled, + settledAt: settled && thread.settledAt !== null ? DateTime.formatIso(thread.settledAt) : null, + }; +} + +export function threadSnooze( + thread: Parameters[0], + nowMs: number, +): Pick { + const snoozed = isSnoozed(thread, nowMs); + return { + snoozed, + snoozedUntil: + snoozed && thread.snoozedUntil != null ? DateTime.formatIso(thread.snoozedUntil) : null, + }; +} + +export function threadPullRequests( + links: OrchestrationV2ThreadShell["pullRequests"], +): OrchestratorMcpThreadPullRequest[] { + return visibleThreadPullRequests(links ?? []).map((link) => ({ + host: normalizeThreadPullRequestKey(link).host, + repository: link.repository, + number: link.number, + url: link.url, + source: link.source, + state: link.snapshot?.state ?? null, + })); +} + +export function listItemFromShell( + shell: OrchestrationV2ThreadShell, + link: string, + nowMs: number, +): OrchestratorMcpThreadListItem { + return { + threadId: shell.id, + projectId: shell.projectId, + title: shell.title, + link, + createdBy: shell.createdBy, + creationSource: shell.creationSource, + status: shell.activityRunStatus ?? shell.status, + latestRunId: shell.latestRunId, + providerInstanceId: shell.modelSelection.instanceId, + model: shell.modelSelection.model, + runtimeMode: shell.runtimeMode, + interactionMode: shell.interactionMode, + linkedPullRequest: shell.linkedPullRequest ?? null, + pullRequests: threadPullRequests(shell.pullRequests), + ...threadSettlement(shell), + ...threadSnooze(shell, nowMs), + parentThreadId: shell.lineage.parentThreadId, + relationshipToParent: shell.lineage.relationshipToParent, + itemCount: shell.visibleItemCount, + createdAt: DateTime.formatIso(shell.createdAt), + updatedAt: DateTime.formatIso(shell.updatedAt), + }; +} diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index ebc477d712fca..ccc3110d3d3ff 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -95,8 +95,32 @@ 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 signing in through MCP. 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 --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, subagents, and side chats are excluded. +Statuses with no threads are omitted from the counts. `thread list` spans all +projects unless `--project` is supplied, and orders threads newest first. + +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. + +You can also start, message, and inspect a thread: ```sh id=$(t3 thread start . "Find why the tests are slow") From 8dd0816919f7e315003f12e48aa7f5ade8f3237e Mon Sep 17 00:00:00 2001 From: Apollo Meijer Date: Sun, 8 Nov 2026 16:30:24 +0100 Subject: [PATCH 2/8] fix(cli): report discovery and endpoint lookup failures cleanly --- apps/server/src/cli/connect.ts | 4 +++- apps/server/src/cli/connectStatus.test.ts | 12 ++++++++-- apps/server/src/cli/discovery.test.ts | 28 ++++++++++++++++++++++- apps/server/src/cli/discovery.ts | 18 +++++++++++++++ apps/server/src/cli/project.ts | 4 ++-- apps/server/src/cli/thread.ts | 14 ++---------- 6 files changed, 62 insertions(+), 18 deletions(-) diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 4a385cb7eee4c..2a40389467dc3 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -675,6 +675,8 @@ const connectLinkCommand = Command.make("link", { ), ); +const decodeConnectEndpointUrl = Schema.decodeEffect(Schema.URLFromString); + const readPublicConnectAddress = Effect.fn("cloud.cli.readPublicAddress")(function* ( relayUrl: string, ) { @@ -696,7 +698,7 @@ const readPublicConnectAddress = Effect.fn("cloud.cli.readPublicAddress")(functi (item) => item.environmentId === environmentId, )?.endpoint; if (endpoint?.providerKind !== "cloudflare_tunnel") return null; - const url = new URL(endpoint.httpBaseUrl); + const url = yield* decodeConnectEndpointUrl(endpoint.httpBaseUrl); return url.protocol === "https:" ? url.host : null; }); diff --git a/apps/server/src/cli/connectStatus.test.ts b/apps/server/src/cli/connectStatus.test.ts index 89decba928e96..ae6415f31da2a 100644 --- a/apps/server/src/cli/connectStatus.test.ts +++ b/apps/server/src/cli/connectStatus.test.ts @@ -93,7 +93,10 @@ it.effect( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-status-" }); - const replies = (providerKind = "cloudflare_tunnel") => ({ + const replies = ( + providerKind = "cloudflare_tunnel", + httpBaseUrl = "https://this.example.test/", + ) => ({ environments: [ { environmentId: "other-host", @@ -110,7 +113,7 @@ it.effect( label: "This", linkedAt: "2026-11-01", endpoint: { - httpBaseUrl: "https://this.example.test/", + httpBaseUrl, wsBaseUrl: "wss://this.example.test/", providerKind, }, @@ -160,6 +163,11 @@ it.effect( 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))); diff --git a/apps/server/src/cli/discovery.test.ts b/apps/server/src/cli/discovery.test.ts index b53bf92e73902..b96b336046fc7 100644 --- a/apps/server/src/cli/discovery.test.ts +++ b/apps/server/src/cli/discovery.test.ts @@ -9,6 +9,7 @@ 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 Runtime from "effect/Runtime"; import * as Layer from "effect/Layer"; import * as TestConsole from "effect/testing/TestConsole"; import { Command } from "effect/cli"; @@ -155,7 +156,11 @@ it.live("lists projects and all threads through HTTP, with project and status fi }); server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))); }), - (server) => Effect.sync(() => server.close()), + (server) => + Effect.callback((resume) => { + server.close(() => resume(Effect.void)); + server.closeAllConnections(); + }), ); const address = server.address(); assert(address !== null && typeof address !== "string"); @@ -217,6 +222,27 @@ it.live("lists projects and all threads through HTTP, with project and status fi assert.include(String((yield* TestConsole.logLines).at(-1) ?? ""), "older alpha completed"); assert.equal(requests.length, 16); assert.isTrue(requests.every((request) => request.startsWith("GET /api/"))); + const unknownProject = yield* runThread([ + "list", + "--project", + "missing-project", + ...flags, + ]).pipe(Effect.result); + assert(unknownProject._tag === "Failure"); + assert.isFalse(Runtime.getErrorReported(unknownProject.failure)); + assert.deepStrictEqual(yield* TestConsole.errorLines, [ + "No T3 Code project matches 'missing-project'. Pass a project id or a path inside a project.", + ]); + const offlineBaseDir = `${baseDir}/offline`; + for (const run of [runProject, runThread]) { + const errorsBefore = (yield* TestConsole.errorLines).length; + const stopped = yield* run(["list", "--base-dir", offlineBaseDir]).pipe(Effect.result); + assert(stopped._tag === "Failure"); + assert.isFalse(Runtime.getErrorReported(stopped.failure)); + assert.deepStrictEqual((yield* TestConsole.errorLines).slice(errorsBefore), [ + `No running T3 Code server uses ${offlineBaseDir}. Start T3 Code, then retry.`, + ]); + } }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/cli/discovery.ts b/apps/server/src/cli/discovery.ts index cab1630aa5165..44b9052cc3887 100644 --- a/apps/server/src/cli/discovery.ts +++ b/apps/server/src/cli/discovery.ts @@ -8,6 +8,8 @@ import { } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import * as Console from "effect/Console"; +import * as Runtime from "effect/Runtime"; import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -32,6 +34,7 @@ class DiscoveryServerNotRunningError extends Schema.TaggedError(effect: Effect.Effect) => + effect.pipe( + Effect.tapError((error) => + isDiscoveryCliError(error) ? Console.error(error.message) : Effect.void, + ), + ); + export const resolveDiscoveryProject = Effect.fn("cli.discovery.resolveProject")(function* < P extends { readonly id: ProjectId; @@ -97,6 +114,7 @@ const readSnapshot = Effect.fn("cli.discovery.readSnapshot")(function* ( const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; const environmentId = yield* identity.getEnvironmentId; const nowMs = yield* Clock.currentTimeMillis; + // Keep settlement-service dependencies off the CLI help and startup paths. const { listItemFromShell } = yield* Effect.promise( () => import("../orchestration-v2/threadSummary.ts"), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 015d4fb5b9554..ba5405c8416b0 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -42,7 +42,7 @@ import { readPersistedServerRuntimeState, } from "../serverRuntimeState.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; -import { withDiscoverySnapshot } from "./discovery.ts"; +import { reportDiscoveryErrors, withDiscoverySnapshot } from "./discovery.ts"; import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; type ProjectMutationTarget = { @@ -629,7 +629,7 @@ const projectListCommand = Command.make("list", { ); } }), - ), + ).pipe(reportDiscoveryErrors), ), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index c4dec43a8d5ca..42f650a6c8821 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -26,7 +26,7 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerConfig from "../config.ts"; import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; -import { resolveDiscoveryProject, withDiscoverySnapshot } from "./discovery.ts"; +import { DiscoveryCliError, resolveDiscoveryProject, withDiscoverySnapshot } from "./discovery.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -77,16 +77,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", @@ -116,7 +106,7 @@ const ThreadCliError = Schema.Union([ ThreadServerUnreachableError, ThreadToolFailedError, ThreadUsageError, - ThreadProjectNotFoundError, + DiscoveryCliError, ThreadNeedsInputError, ThreadRunEndedError, ]); From 1b847f3fe45781ffa5ebf036f49286b4cedea9e8 Mon Sep 17 00:00:00 2001 From: Apollo Meijer Date: Sun, 8 Nov 2026 16:39:29 +0100 Subject: [PATCH 3/8] fix(cli): report unreachable discovery servers without stack traces --- apps/server/src/cli/discovery.test.ts | 13 +++++++++++++ apps/server/src/cli/discovery.ts | 14 ++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/apps/server/src/cli/discovery.test.ts b/apps/server/src/cli/discovery.test.ts index b96b336046fc7..f76a16c019101 100644 --- a/apps/server/src/cli/discovery.test.ts +++ b/apps/server/src/cli/discovery.test.ts @@ -233,6 +233,19 @@ it.live("lists projects and all threads through HTTP, with project and status fi assert.deepStrictEqual(yield* TestConsole.errorLines, [ "No T3 Code project matches 'missing-project'. Pass a project id or a path inside a project.", ]); + yield* Effect.callback((resume) => { + server.close(() => resume(Effect.void)); + server.closeAllConnections(); + }); + for (const run of [runProject, runThread]) { + const errorsBefore = (yield* TestConsole.errorLines).length; + const unreachable = yield* run(["list", ...flags]).pipe(Effect.result); + assert(unreachable._tag === "Failure"); + assert.isFalse(Runtime.getErrorReported(unreachable.failure)); + assert.deepStrictEqual((yield* TestConsole.errorLines).slice(errorsBefore), [ + `Could not read projects and threads from the T3 Code server using ${baseDir}. Check that the server is running, then retry.`, + ]); + } const offlineBaseDir = `${baseDir}/offline`; for (const run of [runProject, runThread]) { const errorsBefore = (yield* TestConsole.errorLines).length; diff --git a/apps/server/src/cli/discovery.ts b/apps/server/src/cli/discovery.ts index 44b9052cc3887..488abe71e687b 100644 --- a/apps/server/src/cli/discovery.ts +++ b/apps/server/src/cli/discovery.ts @@ -50,9 +50,20 @@ class DiscoveryProjectNotFoundError extends Schema.TaggedError()( + "DiscoverySnapshotReadError", + { baseDir: Schema.String, cause: Schema.Defect() }, +) { + override readonly [Runtime.errorReported] = false; + override get message() { + return `Could not read projects and threads from the T3 Code server using ${this.baseDir}. Check that the server is running, then retry.`; + } +} + export const DiscoveryCliError = Schema.Union([ DiscoveryServerNotRunningError, DiscoveryProjectNotFoundError, + DiscoverySnapshotReadError, ]); const isDiscoveryCliError = Schema.is(DiscoveryCliError); @@ -148,6 +159,9 @@ export const withDiscoverySnapshot = Effect.fn("cli.discovery.withSnapshot")(fun (session) => readSnapshot(state.value.origin, session.token).pipe( Effect.timeout("10 seconds"), + Effect.mapError( + (cause) => new DiscoverySnapshotReadError({ baseDir: config.baseDir, cause }), + ), Effect.flatMap(run), ), (session) => auth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })), From 59d60e2dd84b812e6e2caec0cd972d2579fd1831 Mon Sep 17 00:00:00 2001 From: Apollo Meijer Date: Wed, 11 Nov 2026 11:30:56 +0100 Subject: [PATCH 4/8] fix(cli): inspect Connect credentials without refreshing --- apps/server/src/cli/connect.ts | 25 ++++++++++-- apps/server/src/cli/connectStatus.test.ts | 39 ++++++++++++------- apps/server/src/cloud/CliTokenManager.ts | 20 +++++++++- .../src/cloud/CloudLink.lifecycle.test.ts | 1 + 4 files changed, 65 insertions(+), 20 deletions(-) diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 2a40389467dc3..cacd5b24fe14f 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -675,19 +675,34 @@ const connectLinkCommand = Command.make("link", { ), ); +class ConnectAddressCredentialRefreshRequiredError extends Schema.TaggedError()( + "ConnectAddressCredentialRefreshRequiredError", + {}, +) { + override get message() { + return "Stored T3 Connect credential needs refresh. Wait for the running server to refresh it, then retry."; + } +} + +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 token = yield* tokens.getExisting; - if (Option.isNone(token)) return null; + 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.value.accessToken), + HttpClientRequest.bearerToken(token.accessToken), httpClient.execute, Effect.flatMap(filterRelayResponse), Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayListEnvironmentsResponse)), @@ -763,7 +778,9 @@ const connectStatusCommand = Command.make("status", { mcpUrl: publicAddress === null ? null : `https://${publicAddress}/mcp`, addressLookupError: address?._tag === "Failure" - ? "Could not read the public address from T3 Connect. Retry when connected and authorized." + ? isConnectAddressCredentialRefreshRequiredError(address.failure) + ? address.failure.message + : "Could not read the public address from T3 Connect. Retry when connected and authorized." : null, relayClient: executable, linkMode, diff --git a/apps/server/src/cli/connectStatus.test.ts b/apps/server/src/cli/connectStatus.test.ts index ae6415f31da2a..df8bcd41d42d4 100644 --- a/apps/server/src/cli/connectStatus.test.ts +++ b/apps/server/src/cli/connectStatus.test.ts @@ -43,6 +43,12 @@ vi.mock("../auth/ServerSecretStore.ts", async (importOriginal) => { : { "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" } : {}), }; @@ -62,20 +68,6 @@ vi.mock("../auth/ServerSecretStore.ts", async (importOriginal) => { ), }; }); -vi.mock("../cloud/CliTokenManager.ts", async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - layer: Layer.mock(actual.CloudCliTokenManager)({ - hasCredential: Effect.succeed(true), - getExisting: Effect.succeedSome({ - accessToken: "synthetic-token", - refreshToken: "refresh", - expiresAtEpochMs: 9999999999999, - }), - }), - }; -}); const decodeStatus = Schema.decodeUnknownSync( Schema.fromJsonString( @@ -136,7 +128,16 @@ it.effect( ...(json ? ["--json"] : []), ]).pipe( Effect.provide( - ConfigProvider.layer(ConfigProvider.fromEnv({ env: { TEST_LINK_MODE: mode } })), + 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* run("linked"); @@ -160,6 +161,14 @@ it.effect( }); 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"); + } fetch.mockResolvedValue(Response.json(replies("manual"))); yield* run("linked"); assert.isNull(decodeStatus(String((yield* TestConsole.logLines).at(-1))).mcpUrl); diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index 11a09f481ac4b..7062b90fc7f29 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 f62575fc07310..aeee6bd3ecc4c 100644 --- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts +++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts @@ -223,6 +223,7 @@ describe("releaseManagedTunnelOnShutdown", () => { CliTokenManager.CloudCliTokenManager.of({ get: unusedSecretStoreOperation(), getExisting: harness.getExisting ?? Effect.succeedSome(cliToken), + peek: unusedSecretStoreOperation(), hasCredential: unusedSecretStoreOperation(), store: () => unusedSecretStoreOperation(), clear: unusedSecretStoreOperation(), From 3ecfefc16f138e40e91d36e5f631577465f3d329 Mon Sep 17 00:00:00 2001 From: Apollo Meijer Date: Wed, 11 Nov 2026 11:31:25 +0100 Subject: [PATCH 5/8] fix(cli): reuse MCP discovery and preserve project-scoped lists --- apps/server/src/cli/discovery.test.ts | 316 ++++++++---------- apps/server/src/cli/discovery.ts | 262 ++++++++++----- apps/server/src/cli/project.ts | 16 +- apps/server/src/cli/thread.test.ts | 9 +- apps/server/src/cli/thread.ts | 224 +++---------- apps/server/src/mcp/OrchestratorMcpService.ts | 81 ++++- .../src/orchestration-v2/threadSummary.ts | 76 ----- docs/user/outside-agents.md | 13 +- 8 files changed, 445 insertions(+), 552 deletions(-) delete mode 100644 apps/server/src/orchestration-v2/threadSummary.ts diff --git a/apps/server/src/cli/discovery.test.ts b/apps/server/src/cli/discovery.test.ts index f76a16c019101..a00bf3322bd60 100644 --- a/apps/server/src/cli/discovery.test.ts +++ b/apps/server/src/cli/discovery.test.ts @@ -1,20 +1,20 @@ -// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises the Node HTTP boundary. -import * as NodeHttp from "node:http"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; -import { AuthOrchestrationReadScope, AuthSessionId, EnvironmentId } from "@t3tools/contracts"; +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 Runtime from "effect/Runtime"; import * as Layer from "effect/Layer"; +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, @@ -24,29 +24,19 @@ import { threadCommand } from "./thread.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.succeed(environment.ServerEnvironmentIdentity, { - getEnvironmentId: Effect.succeed(EnvironmentId.make("this-host")), - }), - Layer.mock(actual.EnvironmentAuth)({ - issueSession: (input) => { - assert.deepStrictEqual(input?.scopes, [AuthOrchestrationReadScope]); - return Effect.map(DateTime.now, (expiresAt) => ({ - sessionId: AuthSessionId.make("test-session"), - token: "synthetic-token", - method: "bearer-access-token" as const, - scopes: [AuthOrchestrationReadScope], - subject: "test", - client: { deviceType: "bot" as const }, - expiresAt, - })); - }, - revokeSession: () => Effect.succeed(true), - }), - ), + 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), + }), }; }); @@ -56,159 +46,110 @@ const project = (id: string) => ({ title: id, workspaceRoot: `/work/${id}`, defaultModelSelection: id === "alpha" ? { instanceId: "codex", model: "gpt-test" } : null, - scripts: [], - createdAt: timestamp, - updatedAt: timestamp, - deletedAt: null, }); -const thread = (id: string, projectId: string, status: string, updatedAt = timestamp) => ({ - id, +const thread = (threadId: string, projectId: string, status: string) => ({ + threadId, projectId, - title: id, + title: threadId, status, - updatedAt, - createdAt: timestamp, createdBy: "user", creationSource: "web", providerInstanceId: "codex", - modelSelection: { instanceId: "codex", model: "gpt-test" }, + model: "gpt-test", runtimeMode: "full-access", interactionMode: "default", - branch: null, - worktreePath: null, - lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id }, - forkedFrom: null, - activeProviderThreadId: null, latestRunId: null, - activeRunId: null, - pendingRuntimeRequest: null, - latestVisibleMessage: null, - latestUserMessageAt: null, - hasActionableProposedPlan: false, - itemCount: 0, - visibleItemCount: 0, - archivedAt: null, - settledOverride: null, + linkedPullRequest: null, + settled: false, settledAt: null, - deletedAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: timestamp, + updatedAt: timestamp, }); -it.live("lists projects and all threads through HTTP, with project and status filters", () => +it.effect("discovery paginates existing MCP tools and preserves current-project defaults", () => Effect.gen(function* () { - const requests: Array = []; - const child = { - ...thread("child", "alpha", "running"), - lineage: { - parentThreadId: "older", - relationshipToParent: "subagent", - rootThreadId: "older", - }, - }; - const sideChat = { - ...thread("side", "alpha", "running"), - lineage: { - parentThreadId: null, - relationshipToParent: null, - rootThreadId: "side", - sideChat: true, - }, - }; - const server = yield* Effect.acquireRelease( - Effect.callback((resume) => { - const server = NodeHttp.createServer((request, response) => { - requests.push(`${request.method} ${request.url}`); - assert.equal(request.headers.authorization, "Bearer synthetic-token"); - response.setHeader("content-type", "application/json"); - if (request.url === "/api/projects") { - response.end( - JSON.stringify({ - projects: [ - project("alpha"), - project("beta"), - project("empty"), - { ...project("deleted"), deletedAt: timestamp }, - ], - updatedAt: timestamp, - }), - ); - } else if (request.url === "/api/orchestration/shell") { - assert.equal(request.headers["x-t3-orchestration-protocol"], "2"); - response.end( - JSON.stringify({ - schemaVersion: 1, - snapshotSequence: 0, - projects: [], - threads: [ - thread("older", "alpha", "completed"), - { - ...thread("newer", "beta", "completed", "2026-11-02T12:00:00.000Z"), - activityRunStatus: "running", - }, - child, - sideChat, - ], - archivedThreads: [thread("archived", "alpha", "completed")], - }), - ); - } else { - response.writeHead(404).end(); - } - }); - server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))); - }), - (server) => - Effect.callback((resume) => { - server.close(() => resume(Effect.void)); - server.closeAllConnections(); - }), - ); - const address = server.address(); - assert(address !== null && typeof address !== "string"); 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: address.port, + port: 3773, }), }); + const projects = [project("alpha"), project("beta"), project("empty")]; + const threads = [ + thread("beta-running", "beta", "running"), + thread("alpha-completed", "alpha", "completed"), + ]; + 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, false); + const statuses = args.statuses as ReadonlyArray | undefined; + const visible = threads.filter( + (item) => + (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 runProject = Command.runWith(projectCommand, { version: "0.0.0" }); const runThread = Command.runWith(threadCommand, { version: "0.0.0" }); const flags = ["--base-dir", baseDir, "--json"]; yield* runProject(["list", ...flags]); - assert.deepStrictEqual(JSON.parse(String((yield* TestConsole.logLines).at(-1) ?? "")), [ - { - id: "alpha", - title: "alpha", - workspaceRoot: "/work/alpha", - defaultModelSelection: { instanceId: "codex", model: "gpt-test" }, - threadCounts: { completed: 1 }, - }, - { - id: "beta", - title: "beta", - workspaceRoot: "/work/beta", - defaultModelSelection: null, - threadCounts: { running: 1 }, - }, - { - id: "empty", - title: "empty", - workspaceRoot: "/work/empty", - defaultModelSelection: null, - threadCounts: {}, - }, + 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], + ], + ); for (const [extra, expected] of [ - [[], ["newer", "older"]], - [["--project", "alpha"], ["older"]], - [["--project", "/work/alpha/subdir"], ["older"]], - [["--status", "running"], ["newer"]], - [["--project", "alpha", "--status", "running"], []], + [[], ["alpha-completed"]], + [["--all-projects"], ["beta-running", "alpha-completed"]], + [["--project", "beta"], ["beta-running"]], + [["--project", "/work/alpha/nested"], ["alpha-completed"]], + [["--status", "running"], []], + [["--all-projects", "--status", "running"], ["beta-running"]], ] as const) { yield* runThread(["list", ...extra, ...flags]); - const rows = JSON.parse(String((yield* TestConsole.logLines).at(-1) ?? "")) as Array<{ + const rows = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{ threadId: string; }>; assert.deepStrictEqual( @@ -216,52 +157,63 @@ it.live("lists projects and all threads through HTTP, with project and status fi [...expected], ); } - yield* runProject(["list", "--base-dir", baseDir]); - assert.include((yield* TestConsole.logLines).join("\n"), "codex/gpt-test"); - yield* runThread(["list", "--base-dir", baseDir]); - assert.include(String((yield* TestConsole.logLines).at(-1) ?? ""), "older alpha completed"); - assert.equal(requests.length, 16); - assert.isTrue(requests.every((request) => request.startsWith("GET /api/"))); - const unknownProject = yield* runThread([ + const sessionsBefore = session.mock.calls.length; + const conflicting = yield* runThread([ "list", + "--all-projects", "--project", - "missing-project", + "alpha", ...flags, ]).pipe(Effect.result); - assert(unknownProject._tag === "Failure"); - assert.isFalse(Runtime.getErrorReported(unknownProject.failure)); - assert.deepStrictEqual(yield* TestConsole.errorLines, [ - "No T3 Code project matches 'missing-project'. Pass a project id or a path inside a project.", - ]); - yield* Effect.callback((resume) => { - server.close(() => resume(Effect.void)); - server.closeAllConnections(); - }); + 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* runThread(["list", "--base-dir", baseDir]); + 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 a project id or a path inside a project.", + ); + session.mockReturnValue( + Effect.fail(new McpBridge.AcpMcpBridgeError({ message: "synthetic connection refused" })), + ); for (const run of [runProject, runThread]) { - const errorsBefore = (yield* TestConsole.errorLines).length; - const unreachable = yield* run(["list", ...flags]).pipe(Effect.result); - assert(unreachable._tag === "Failure"); - assert.isFalse(Runtime.getErrorReported(unreachable.failure)); - assert.deepStrictEqual((yield* TestConsole.errorLines).slice(errorsBefore), [ - `Could not read projects and threads from the T3 Code server using ${baseDir}. Check that the server is running, then retry.`, - ]); + 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", + ); } - const offlineBaseDir = `${baseDir}/offline`; for (const run of [runProject, runThread]) { - const errorsBefore = (yield* TestConsole.errorLines).length; - const stopped = yield* run(["list", "--base-dir", offlineBaseDir]).pipe(Effect.result); - assert(stopped._tag === "Failure"); - assert.isFalse(Runtime.getErrorReported(stopped.failure)); - assert.deepStrictEqual((yield* TestConsole.errorLines).slice(errorsBefore), [ - `No running T3 Code server uses ${offlineBaseDir}. Start T3 Code, then retry.`, - ]); + 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, - Layer.fresh(TestConsole.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 index 488abe71e687b..05f843e2c30dc 100644 --- a/apps/server/src/cli/discovery.ts +++ b/apps/server/src/cli/discovery.ts @@ -1,72 +1,78 @@ import { - AuthOrchestrationReadScope, - EnvironmentHttpApi, - ORCHESTRATION_PROTOCOL_HEADER, - ORCHESTRATION_PROTOCOL_VERSION_TEXT, - isListedThreadLineage, - type ProjectId, + OrchestratorMcpFailure, + OrchestratorMcpThreadListResult, + ModelSelection, + ProjectId, + type AuthMcpClientAccess, + type OrchestratorMcpThreadListInput, + type OrchestratorMcpThreadListItem, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { formatThreadLink } from "@t3tools/shared/threadLinks"; import * as Console from "effect/Console"; -import * as Runtime from "effect/Runtime"; -import * as Clock from "effect/Clock"; -import * as DateTime from "effect/DateTime"; 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 FetchHttpClient from "effect/http/FetchHttpClient"; -import * as HttpApiClient from "effect/http-api/HttpApiClient"; - import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; -import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ServerConfig from "../config.ts"; +import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; import { expandHomePath } from "../os-jank.ts"; import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; -import { type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts"; +import { resolveCliAuthConfig } from "./config.ts"; -class DiscoveryServerNotRunningError extends Schema.TaggedError()( - "DiscoveryServerNotRunningError", +class ThreadServerNotRunningError extends Schema.TaggedError()( + "ThreadServerNotRunningError", { baseDir: Schema.String }, ) { override readonly [Runtime.errorReported] = false; - override get message() { + override get message(): string { return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`; } } -class DiscoveryProjectNotFoundError extends Schema.TaggedError()( - "DiscoveryProjectNotFoundError", - { identifier: Schema.String }, +class ThreadServerUnreachableError extends Schema.TaggedError()( + "ThreadServerUnreachableError", + { origin: Schema.String, cause: Schema.Defect() }, ) { override readonly [Runtime.errorReported] = false; - override get message() { - return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`; + 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 DiscoverySnapshotReadError extends Schema.TaggedError()( - "DiscoverySnapshotReadError", - { baseDir: Schema.String, cause: Schema.Defect() }, +class ThreadToolFailedError extends Schema.TaggedError()( + "ThreadToolFailedError", + { tool: Schema.String, detail: Schema.String }, +) { + override readonly [Runtime.errorReported] = false; + override get message(): string { + return this.detail; + } +} + +class DiscoveryProjectNotFoundError extends Schema.TaggedError()( + "DiscoveryProjectNotFoundError", + { identifier: Schema.String }, ) { override readonly [Runtime.errorReported] = false; override get message() { - return `Could not read projects and threads from the T3 Code server using ${this.baseDir}. Check that the server is running, then retry.`; + return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`; } } export const DiscoveryCliError = Schema.Union([ - DiscoveryServerNotRunningError, + ThreadServerNotRunningError, + ThreadServerUnreachableError, + ThreadToolFailedError, DiscoveryProjectNotFoundError, - DiscoverySnapshotReadError, ]); const isDiscoveryCliError = Schema.is(DiscoveryCliError); - export const reportDiscoveryErrors = (effect: Effect.Effect) => effect.pipe( Effect.tapError((error) => @@ -74,6 +80,113 @@ export const reportDiscoveryErrors = (effect: Effect.Effect) = ), ); +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 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. + */ +export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* ( + flags: { readonly baseDir: Option.Option }, + run: (tools: ThreadTools) => Effect.Effect, + options?: { readonly access: AuthMcpClientAccess }, +) { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveCliAuthConfig(flags, logLevel); + return yield* Effect.gen(function* () { + const runtimeState = yield* readPersistedServerRuntimeState(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.mapError((cause) => new ThreadServerUnreachableError({ origin, cause }))); + return yield* run(makeThreadTools(session, origin)); + }).pipe( + Effect.scoped, + Effect.provide( + EnvironmentAuth.layerRuntime.pipe( + Layer.provide(ServerConfig.layer(config)), + Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)), + ), + ), + ); +}); + export const resolveDiscoveryProject = Effect.fn("cli.discovery.resolveProject")(function* < P extends { readonly id: ProjectId; @@ -109,72 +222,37 @@ export const resolveDiscoveryProject = Effect.fn("cli.discovery.resolveProject") return containing.project; }); -const readSnapshot = Effect.fn("cli.discovery.readSnapshot")(function* ( - origin: string, - token: string, +export const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* ( + tools: ThreadTools, ) { - const client = yield* HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin }); - const headers = { - authorization: `Bearer ${token}`, - [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT, - } as const; - const [projects, shell] = yield* Effect.all([ - client.projects.snapshot({ headers }), - client.orchestration.shellSnapshot({ headers, query: {} }), - ]); - const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; - const environmentId = yield* identity.getEnvironmentId; - const nowMs = yield* Clock.currentTimeMillis; - // Keep settlement-service dependencies off the CLI help and startup paths. - const { listItemFromShell } = yield* Effect.promise( - () => import("../orchestration-v2/threadSummary.ts"), - ); - const threads = shell.threads - .filter((thread) => isListedThreadLineage(thread.lineage)) - .toSorted( - (left, right) => - DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) || - right.id.localeCompare(left.id), - ) - .map((thread) => - listItemFromShell(thread, formatThreadLink({ environmentId, threadId: thread.id }), nowMs), + 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, ); - return { projects: projects.projects.filter((project) => project.deletedAt === null), threads }; + projects.push(...page.projects); + cursor = page.nextCursor; + } + return projects; }); -type DiscoverySnapshot = Effect.Success>; -export const withDiscoverySnapshot = Effect.fn("cli.discovery.withSnapshot")(function* ( - flags: CliAuthLocationFlags, - run: (snapshot: DiscoverySnapshot) => Effect.Effect, +export const listAllThreads = Effect.fn("cli.discovery.listAllThreads")(function* ( + tools: ThreadTools, + input: Pick, ) { - const logLevel = yield* GlobalFlag.LogLevel; - const config = yield* resolveCliAuthConfig(flags, logLevel); - return yield* Effect.gen(function* () { - const state = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); - if (Option.isNone(state)) - return yield* new DiscoveryServerNotRunningError({ baseDir: config.baseDir }); - const auth = yield* EnvironmentAuth.EnvironmentAuth; - return yield* Effect.acquireUseRelease( - auth.issueSession({ scopes: [AuthOrchestrationReadScope], label: "t3 discovery cli" }), - (session) => - readSnapshot(state.value.origin, session.token).pipe( - Effect.timeout("10 seconds"), - Effect.mapError( - (cause) => new DiscoverySnapshotReadError({ baseDir: config.baseDir, cause }), - ), - Effect.flatMap(run), - ), - (session) => auth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })), + const threads: Array = []; + let cursor: number | null = 0; + while (cursor !== null) { + const page: OrchestratorMcpThreadListResult = yield* tools.call( + "t3_thread_list", + { ...input, includeSubagents: false, limit: 100, cursor }, + OrchestratorMcpThreadListResult, ); - }).pipe( - Effect.provide( - Layer.merge( - FetchHttpClient.layer, - EnvironmentAuth.layerRuntime.pipe( - Layer.provide(ServerConfig.layer(config)), - Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)), - ), - ), - ), - ); + threads.push(...page.threads); + cursor = page.nextCursor; + } + return threads; }); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index ba5405c8416b0..ec965247c5cc5 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -42,7 +42,12 @@ import { readPersistedServerRuntimeState, } from "../serverRuntimeState.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; -import { reportDiscoveryErrors, withDiscoverySnapshot } from "./discovery.ts"; +import { + reportDiscoveryErrors, + withThreadTools, + listAllProjects, + listAllThreads, +} from "./discovery.ts"; import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; type ProjectMutationTarget = { @@ -602,9 +607,13 @@ const projectListCommand = Command.make("list", { }).pipe( Command.withDescription("List projects, their default models, and thread counts by status."), Command.withHandler((flags) => - withDiscoverySnapshot( + withThreadTools( flags, - Effect.fn("cli.project.list")(function* (snapshot) { + Effect.fn("cli.project.list")(function* (tools) { + const snapshot = { + projects: yield* listAllProjects(tools), + threads: yield* listAllThreads(tools, { allProjects: true }), + }; const countsByProject = new Map>(); for (const thread of snapshot.threads) { const counts = countsByProject.get(thread.projectId) ?? {}; @@ -629,6 +638,7 @@ const projectListCommand = Command.make("list", { ); } }), + { access: "read-only" }, ).pipe(reportDiscoveryErrors), ), ); diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index f182f708c4cfa..dc6eb09c15662 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -14,18 +14,13 @@ 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, persistServerRuntimeState, } from "../serverRuntimeState.ts"; -import { - readLatestMessages, - threadCommand, - type ThreadTools, - titleFromMessage, - waitForRun, -} from "./thread.ts"; +import { readLatestMessages, threadCommand, titleFromMessage, waitForRun } from "./thread.ts"; vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { const actual = await importOriginal(); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 42f650a6c8821..2524a5bfcdb6b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -1,5 +1,4 @@ import { - OrchestratorMcpFailure, OrchestratorMcpThreadReadResult, OrchestratorMcpThreadSendResult, OrchestratorMcpThreadWaitResult, @@ -13,21 +12,22 @@ import { } from "@t3tools/contracts"; import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -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 { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; -import { DiscoveryCliError, resolveDiscoveryProject, withDiscoverySnapshot } from "./discovery.ts"; -import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; +import { + DiscoveryCliError, + resolveDiscoveryProject, + 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 @@ -37,37 +37,6 @@ const WAIT_SLICE_MS = 15_000; const READ_PAGE_LIMIT = 100; 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, }) { @@ -102,9 +71,6 @@ export class ThreadRunEndedError extends Schema.TaggedError } const ThreadCliError = Schema.Union([ - ThreadServerNotRunningError, - ThreadServerUnreachableError, - ThreadToolFailedError, ThreadUsageError, DiscoveryCliError, ThreadNeedsInputError, @@ -123,114 +89,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 }, - run: (tools: ThreadTools) => Effect.Effect, -) { - const logLevel = yield* GlobalFlag.LogLevel; - const config = yield* resolveCliAuthConfig(flags, logLevel); - return yield* Effect.gen(function* () { - const runtimeState = yield* readPersistedServerRuntimeState(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.provide( - EnvironmentAuth.layerRuntime.pipe( - Layer.provide(ServerConfig.layer(config)), - Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)), - ), - ), - ); -}); - const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argument: string) { const text = argument === "-" @@ -244,21 +111,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; -}); - /** A project id, or a path inside a project's folder (deepest project wins). */ const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( tools: ThreadTools, @@ -527,36 +379,50 @@ const decodeThreadId = (value: string) => const threadListCommand = Command.make("list", { ...projectLocationFlags, project: Flag.String("project").pipe( - Flag.withDescription("Filter by project id or a path inside the project."), + Flag.withDescription("Project id or a 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), + ), 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 threads across all projects, newest first."), + Command.withDescription("List a project's threads, most recently updated first."), Command.withHandler((flags) => - withDiscoverySnapshot( - flags, - Effect.fn("cli.thread.list")(function* (snapshot) { - const project = Option.isSome(flags.project) - ? yield* resolveDiscoveryProject(snapshot.projects, flags.project.value) - : undefined; - const threads = snapshot.threads.filter( - (thread) => - (project === undefined || thread.projectId === project.id) && - (Option.isNone(flags.status) || thread.status === flags.status.value), - ); - if (flags.json) return yield* printJson(threads); - for (const thread of threads) { - yield* Console.log( - `${thread.threadId} ${thread.projectId} ${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, { + ...(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" }, + ); + }).pipe(reportThreadErrors), ), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index a601e6886944a..a1425d56e8e56 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -37,9 +37,11 @@ import { type OrchestratorMcpListScheduledTasksInput, type ProjectId, type OrchestratorMcpThreadDetail, + type OrchestratorMcpThreadPullRequest, type OrchestratorMcpThreadInterruptInput, type OrchestratorMcpThreadInterruptResult, type OrchestratorMcpThreadListInput, + type OrchestratorMcpThreadListItem, type OrchestratorMcpThreadListResult, type OrchestratorMcpThreadReadInput, type OrchestratorMcpThreadReadResult, @@ -68,6 +70,10 @@ import { import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import { + normalizeThreadPullRequestKey, + visibleThreadPullRequests, +} from "../sourceControl/threadPullRequests.ts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -98,12 +104,6 @@ import { runOutcome } from "../orchestration-v2/RestartBackgroundNote.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; -import { - listItemFromShell, - threadSettlement, - threadSnooze, - threadPullRequests, -} from "../orchestration-v2/threadSummary.ts"; import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts"; import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as ProjectService from "../project/ProjectService.ts"; @@ -761,6 +761,71 @@ function threadTitle(input: { return `${detail.slice(0, end)}...`; } +function threadSettlement( + thread: Pick, +): Pick { + const settled = thread.settledOverride === "settled"; + return { + settled, + settledAt: settled && thread.settledAt !== null ? DateTime.formatIso(thread.settledAt) : null, + }; +} + +function threadSnooze( + thread: Parameters[0], + nowMs: number, +): Pick { + const snoozed = isSnoozed(thread, nowMs); + return { + snoozed, + snoozedUntil: + snoozed && thread.snoozedUntil != null ? DateTime.formatIso(thread.snoozedUntil) : null, + }; +} + +function threadPullRequests( + links: OrchestrationV2ThreadShell["pullRequests"], +): OrchestratorMcpThreadPullRequest[] { + return visibleThreadPullRequests(links ?? []).map((link) => ({ + host: normalizeThreadPullRequestKey(link).host, + repository: link.repository, + number: link.number, + url: link.url, + source: link.source, + state: link.snapshot?.state ?? null, + })); +} + +function listItemFromShell( + scope: McpInvocationScope, + shell: OrchestrationV2ThreadShell, + nowMs: number, +): OrchestratorMcpThreadListItem { + return { + threadId: shell.id, + projectId: shell.projectId, + title: shell.title, + link: threadLinkFor(scope, shell.id, shell.title), + createdBy: shell.createdBy, + creationSource: shell.creationSource, + status: shell.activityRunStatus ?? shell.status, + latestRunId: shell.latestRunId, + providerInstanceId: shell.modelSelection.instanceId, + model: shell.modelSelection.model, + runtimeMode: shell.runtimeMode, + interactionMode: shell.interactionMode, + linkedPullRequest: shell.linkedPullRequest ?? null, + pullRequests: threadPullRequests(shell.pullRequests), + ...threadSettlement(shell), + ...threadSnooze(shell, nowMs), + parentThreadId: shell.lineage.parentThreadId, + relationshipToParent: shell.lineage.relationshipToParent, + itemCount: shell.visibleItemCount, + createdAt: DateTime.formatIso(shell.createdAt), + updatedAt: DateTime.formatIso(shell.updatedAt), + }; +} + function threadDetail( scope: McpInvocationScope, projection: Pick, @@ -2992,9 +3057,7 @@ const make = Effect.gen(function* () { return { projectId, currentThreadId: parent?.thread.id ?? null, - threads: page.map((shell) => - listItemFromShell(shell, threadLinkFor(scope, shell.id, shell.title), nowMs), - ), + threads: page.map((shell) => listItemFromShell(scope, shell, nowMs)), nextCursor, total: filtered.length, } satisfies OrchestratorMcpThreadListResult; diff --git a/apps/server/src/orchestration-v2/threadSummary.ts b/apps/server/src/orchestration-v2/threadSummary.ts deleted file mode 100644 index 6aaf0d3632867..0000000000000 --- a/apps/server/src/orchestration-v2/threadSummary.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { - OrchestrationV2ThreadShell, - OrchestratorMcpThreadListItem, - OrchestratorMcpThreadPullRequest, -} from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -import { - normalizeThreadPullRequestKey, - visibleThreadPullRequests, -} from "../sourceControl/threadPullRequests.ts"; -import { isSnoozed } from "./ThreadSettlementService.ts"; - -export function threadSettlement( - thread: Pick, -): Pick { - const settled = thread.settledOverride === "settled"; - return { - settled, - settledAt: settled && thread.settledAt !== null ? DateTime.formatIso(thread.settledAt) : null, - }; -} - -export function threadSnooze( - thread: Parameters[0], - nowMs: number, -): Pick { - const snoozed = isSnoozed(thread, nowMs); - return { - snoozed, - snoozedUntil: - snoozed && thread.snoozedUntil != null ? DateTime.formatIso(thread.snoozedUntil) : null, - }; -} - -export function threadPullRequests( - links: OrchestrationV2ThreadShell["pullRequests"], -): OrchestratorMcpThreadPullRequest[] { - return visibleThreadPullRequests(links ?? []).map((link) => ({ - host: normalizeThreadPullRequestKey(link).host, - repository: link.repository, - number: link.number, - url: link.url, - source: link.source, - state: link.snapshot?.state ?? null, - })); -} - -export function listItemFromShell( - shell: OrchestrationV2ThreadShell, - link: string, - nowMs: number, -): OrchestratorMcpThreadListItem { - return { - threadId: shell.id, - projectId: shell.projectId, - title: shell.title, - link, - createdBy: shell.createdBy, - creationSource: shell.creationSource, - status: shell.activityRunStatus ?? shell.status, - latestRunId: shell.latestRunId, - providerInstanceId: shell.modelSelection.instanceId, - model: shell.modelSelection.model, - runtimeMode: shell.runtimeMode, - interactionMode: shell.interactionMode, - linkedPullRequest: shell.linkedPullRequest ?? null, - pullRequests: threadPullRequests(shell.pullRequests), - ...threadSettlement(shell), - ...threadSnooze(shell, nowMs), - parentThreadId: shell.lineage.parentThreadId, - relationshipToParent: shell.lineage.relationshipToParent, - itemCount: shell.visibleItemCount, - createdAt: DateTime.formatIso(shell.createdAt), - updatedAt: DateTime.formatIso(shell.updatedAt), - }; -} diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index d8d53cad41720..d6cbd40935be0 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -122,7 +122,7 @@ Agents without OAuth support cannot connect. ## Scripts on the host On the machine that runs the environment, the CLI can discover projects and -threads without opening the app or signing in through MCP. The environment’s +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. @@ -130,6 +130,7 @@ when the server uses a non-default T3 home. t3 project list t3 project list --json t3 thread list +t3 thread list --all-projects --json t3 thread list --project --status running --json t3 connect status --json ``` @@ -138,13 +139,17 @@ t3 connect status --json 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, subagents, and side chats are excluded. -Statuses with no threads are omitted from the counts. `thread list` spans all -projects unless `--project` is supplied, and orders threads newest first. +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. 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. +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, wait for the running server to refresh it, then retry. You can also start, message, and inspect a thread: From e451b09cfbba7d388809a8495445018365c86c15 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 11 Nov 2026 14:28:16 +0000 Subject: [PATCH 6/8] fix(cli): report project models from settings and keep JSON discovery output clean --- apps/server/src/cli/discovery.ts | 15 +++++++++++---- apps/server/src/cli/project.ts | 27 +++++++++++++++++++++++++-- apps/server/src/cli/thread.ts | 2 +- 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/apps/server/src/cli/discovery.ts b/apps/server/src/cli/discovery.ts index 05f843e2c30dc..924277b7808d5 100644 --- a/apps/server/src/cli/discovery.ts +++ b/apps/server/src/cli/discovery.ts @@ -147,10 +147,12 @@ export type ThreadTools = ReturnType; export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* ( flags: { readonly baseDir: Option.Option }, run: (tools: ThreadTools) => Effect.Effect, - options?: { readonly access: AuthMcpClientAccess }, + options?: { readonly access?: AuthMcpClientAccess; readonly quietLogs?: boolean }, ) { const logLevel = yield* GlobalFlag.LogLevel; - const config = yield* resolveCliAuthConfig(flags, logLevel); + const config = yield* resolveCliAuthConfig(flags, logLevel, { + quietLogs: options?.quietLogs === true, + }); return yield* Effect.gen(function* () { const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); if (Option.isNone(runtimeState)) { @@ -180,8 +182,13 @@ export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* Effect.scoped, Effect.provide( EnvironmentAuth.layerRuntime.pipe( - Layer.provide(ServerConfig.layer(config)), - Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)), + Layer.provideMerge(ServerConfig.layer(config)), + Layer.provide( + Layer.succeed( + References.MinimumLogLevel, + options?.quietLogs === true ? "Error" : config.logLevel, + ), + ), ), ), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index ec965247c5cc5..2bc21784aae2e 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, EnvironmentHttpApi, EnvironmentHttpCommonError, 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 Duration from "effect/Duration"; @@ -600,6 +604,15 @@ 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, @@ -614,6 +627,14 @@ const projectListCommand = Command.make("list", { 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) ?? {}; @@ -626,7 +647,9 @@ const projectListCommand = Command.make("list", { id: project.id, title: project.title, workspaceRoot: project.workspaceRoot, - defaultModelSelection: project.defaultModelSelection, + defaultModelSelection: + resolveProjectSettings(settings, project.id, project).overrides + .defaultModelSelection ?? null, threadCounts, }; }); @@ -638,7 +661,7 @@ const projectListCommand = Command.make("list", { ); } }), - { access: "read-only" }, + { access: "read-only", quietLogs: flags.json }, ).pipe(reportDiscoveryErrors), ), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 2524a5bfcdb6b..bdb06d6d2945b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -420,7 +420,7 @@ const threadListCommand = Command.make("list", { ); } }), - { access: "read-only" }, + { access: "read-only", quietLogs: flags.json }, ); }).pipe(reportThreadErrors), ), From 34aaf6af03782031d0cc1e6962aa1bc912d66040 Mon Sep 17 00:00:00 2001 From: Apollo Meijer Date: Sat, 14 Nov 2026 20:52:09 +0100 Subject: [PATCH 7/8] feat(cli): include subagents and harden discovery commands --- apps/server/src/cli/connect.ts | 2 +- apps/server/src/cli/connectStatus.test.ts | 40 +++- apps/server/src/cli/discovery.test.ts | 259 +++++++++++++++++++++- apps/server/src/cli/discovery.ts | 70 ++++-- apps/server/src/cli/thread.test.ts | 21 +- apps/server/src/cli/thread.ts | 17 +- apps/server/src/mcp/AcpMcpStdioBridge.ts | 22 +- docs/user/outside-agents.md | 21 +- 8 files changed, 407 insertions(+), 45 deletions(-) diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index bf2f5ee7ad549..43a80185132a5 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -692,7 +692,7 @@ class ConnectAddressCredentialRefreshRequiredError extends Schema.TaggedError logs.push(String(message)))], { + mergeWithExisting: false, + }); const run = (mode: string, json = true) => Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([ "connect", @@ -128,19 +134,34 @@ it.effect( ...(json ? ["--json"] : []), ]).pipe( Effect.provide( - 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", - }, - }), + 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", @@ -168,6 +189,7 @@ it.effect( 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"); diff --git a/apps/server/src/cli/discovery.test.ts b/apps/server/src/cli/discovery.test.ts index a00bf3322bd60..feb6c68e8e75b 100644 --- a/apps/server/src/cli/discovery.test.ts +++ b/apps/server/src/cli/discovery.test.ts @@ -8,7 +8,12 @@ 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"; @@ -19,6 +24,8 @@ 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"; @@ -86,6 +93,11 @@ it.effect("discovery paginates existing MCP tools and preserves current-project 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( @@ -102,10 +114,11 @@ it.effect("discovery paginates existing MCP tools and preserves current-project }); } assert.equal(tool, "t3_thread_list"); - assert.equal(args.includeSubagents, false); + 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)), ); @@ -121,10 +134,29 @@ it.effect("discovery paginates existing MCP tools and preserves current-project }, }), ); - const runProject = Command.runWith(projectCommand, { version: "0.0.0" }); - const runThread = Command.runWith(threadCommand, { version: "0.0.0" }); + 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 } }, @@ -138,6 +170,8 @@ it.effect("discovery paginates existing MCP tools and preserves current-project ["t3_project_list", 2], ["t3_thread_list", 0], ["t3_thread_list", 1], + ["t3_thread_list", 0], + ["t3_thread_list", 1], ], ); for (const [extra, expected] of [ @@ -146,17 +180,43 @@ it.effect("discovery paginates existing MCP tools and preserves current-project [["--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]); - const rows = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{ + 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", @@ -171,7 +231,14 @@ it.effect("discovery paginates existing MCP tools and preserves current-project (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", @@ -185,7 +252,7 @@ it.effect("discovery paginates existing MCP tools and preserves current-project assert.isFalse(Runtime.getErrorReported(unknown.failure)); assert.equal( (yield* TestConsole.errorLines).at(-1), - "No T3 Code project matches '/unknown-project'. Pass a project id or a path inside a project.", + "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" })), @@ -221,3 +288,185 @@ it.effect("discovery paginates existing MCP tools and preserves current-project ), ), ); + +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 index adef6c2ee0653..a3206222f95c2 100644 --- a/apps/server/src/cli/discovery.ts +++ b/apps/server/src/cli/discovery.ts @@ -62,7 +62,7 @@ export class DiscoveryProjectNotFoundError extends Schema.TaggedError { }); }; +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({ @@ -125,9 +130,12 @@ const makeThreadTools = (session: McpToolSession, origin: string) => { args: Readonly>, schema: S, ): Effect.fn.Return { - const raw = yield* session - .call(tool, args) - .pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause }))); + 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) }); @@ -176,7 +184,10 @@ export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* endpoint: new URL("/mcp", origin).href, authorization: `Bearer ${issued.token}`, clientName: "t3-thread-cli", - }).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause }))); + }).pipe( + Effect.timeout(DISCOVERY_REQUEST_TIMEOUT), + Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })), + ); return yield* run(makeThreadTools(session, origin)); }).pipe( Effect.scoped, @@ -202,6 +213,9 @@ export const resolveDiscoveryProject = Effect.fn("cli.discovery.resolveProject") >(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 @@ -248,18 +262,40 @@ export const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* export const listAllThreads = Effect.fn("cli.discovery.listAllThreads")(function* ( tools: ThreadTools, - input: Pick, + input: Pick< + OrchestratorMcpThreadListInput, + "projectId" | "allProjects" | "statuses" | "includeSubagents" + >, ) { - const threads: Array = []; - let cursor: number | null = 0; - while (cursor !== null) { - const page: OrchestratorMcpThreadListResult = yield* tools.call( - "t3_thread_list", - { ...input, includeSubagents: false, limit: 100, cursor }, - OrchestratorMcpThreadListResult, - ); - threads.push(...page.threads); - cursor = page.nextCursor; + 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: input.includeSubagents ?? false, 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()].toSorted((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + } + previousIds = ids; } - return threads; + 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/thread.test.ts b/apps/server/src/cli/thread.test.ts index 24ad9d26f7fd5..9a384de503a5c 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -80,9 +80,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 } }); @@ -97,6 +99,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"], @@ -520,7 +539,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 57a2e91961454..2b68eaa4259f9 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -29,6 +29,7 @@ import { DiscoveryCliError, DiscoveryProjectNotFoundError, resolveDiscoveryProject, + isExplicitProjectPath, withThreadTools, listAllProjects, listAllThreads, @@ -163,6 +164,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 @@ -585,13 +589,19 @@ 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.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, @@ -616,6 +626,7 @@ const threadListCommand = Command.make("list", { 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] } : {}), }); @@ -635,7 +646,9 @@ const threadListCommand = Command.make("list", { 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/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index ffddcf7d5866b..89ac893578a93 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 d852463f43bff..7f12e686fe2aa 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -147,6 +147,7 @@ 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 ``` @@ -154,18 +155,32 @@ 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, subagents, and side chats are excluded. +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. +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, wait for the running server to refresh it, then retry. +refresh, run `t3 connect login` with the same `--base-dir`, then retry status. You can also start, message, and inspect a thread: From d51b8dc5e60b2e3dfc430bab0ea2134a1baf8cb9 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Sun, 15 Nov 2026 03:44:50 +0000 Subject: [PATCH 8/8] fix(cli): keep json logs quiet across thread commands --- apps/server/src/cli/discovery.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/apps/server/src/cli/discovery.ts b/apps/server/src/cli/discovery.ts index 2d5b4cc8b9e0a..f88467822389a 100644 --- a/apps/server/src/cli/discovery.ts +++ b/apps/server/src/cli/discovery.ts @@ -153,15 +153,14 @@ export type ThreadTools = ReturnType; * 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 }, + 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 config = yield* resolveCliAuthConfig(flags, logLevel, { - quietLogs: options?.quietLogs === true, - }); - const minimumLogLevel = options?.quietLogs === true ? "Error" : config.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)) { @@ -195,7 +194,7 @@ export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* Effect.provideService(References.MinimumLogLevel, minimumLogLevel), Effect.provide( EnvironmentAuth.layerRuntime.pipe( - Layer.provide(ServerConfig.layer(config)), + Layer.provideMerge(ServerConfig.layer(config)), Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)), ), ),