TypeScript
feat: triage an issue from the command palette, no terminal needed (#22753)
Theo Browne7e884b2df619
diff --git a/.github/triage/PLAYBOOK.md b/.github/triage/PLAYBOOK.mdindex 13ca38fed4a..78a0156d1ea 100644--- a/.github/triage/PLAYBOOK.md+++ b/.github/triage/PLAYBOOK.md@@ -11,8 +11,8 @@ provided alongside this playbook. Everything machine-specific lives there, not h## 1. Ask what went wrong-Your first message to the user: ask them to describe what went wrong, in their own-words. Ask them to paste screenshots directly into this session if they have any.+Unless the user already described it, your first message asks what went wrong, in+their own words. Ask them to paste screenshots directly into this session if they have any.Ask follow-up questions when the description is vague. Good repro steps are the mostvaluable thing you can extract from this conversation.diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsxindex b900108065c..3194d880532 100644--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx@@ -1,3 +1,4 @@+import { useAtomValue } from "@effect/atom-react";import { uuidv4 } from "../../lib/uuid";import { useNavigation } from "@react-navigation/native";import {@@ -41,15 +42,25 @@ import { deriveBottomControlInsets } from "../../lib/reserved-regions";import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";-import { useProjects, useThreadShell, useThreadShells } from "../../state/entities";+import {+ useProjects,+ useServerConfigs,+ useThreadShell,+ useThreadShells,+} from "../../state/entities";import { useThreadSearch } from "../../state/queries";import { requestThreadMessageJump } from "../threads/threadMessageJump";import { threadEnvironment } from "../../state/threads";import { useAtomCommand } from "../../state/use-atom-command";+import { serverEnvironment } from "../../state/server";import { useWorkspaceEnvironments } from "../../state/workspace";import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";+import { pickTriageEnvironment } from "../triage/triageTarget";+import { useStartTriage } from "../triage/useStartTriage";+import { useNewTaskFlow } from "../threads/new-task-flow-provider";+import { useActiveNewTask } from "../../state/active-new-task";import {filterCommandPaletteItems,nextPaletteIndex,@@ -256,6 +267,22 @@ export function CommandPalette(props: {query.startsWith(">") ? "" : query,environmentLabels === undefined ? {} : { environmentLabels },);+ const serverConfigs = useServerConfigs();+ const startTriage = useStartTriage();+ const newTaskFlow = useNewTaskFlow();+ const draftEnvironmentId =+ useActiveNewTask() === null ? null : (newTaskFlow.selectedProject?.environmentId ?? null);+ const triageEnvironmentId = pickTriageEnvironment({+ // The route names the machine even before the thread shell loads.+ onScreen: activeThreadRef?.environmentId ?? draftEnvironmentId,+ connected: searchEnvironmentIds,+ supportsTriage: (environmentId) =>+ serverConfigs.get(environmentId)?.environment.capabilities.triage === true,+ });+ const canTriage =+ useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) &&+ triageEnvironmentId !== null &&+ serverConfigs.get(triageEnvironmentId)?.environment.capabilities.triage === true;const contentMatchByKey = useMemo(() =>new Map(@@ -324,6 +351,17 @@ export function CommandPalette(props: {run: () => openSettings(navigation, "SettingsArchive"),},];+ if (canTriage) {+ actions.push({+ key: "triage",+ kind: "action",+ title: "Triage an issue",+ // Mobile has no triage hero, so name the machine before it starts.+ detail: `On ${savedConnectionsById[triageEnvironmentId]?.environmentLabel ?? "this machine"}`,+ searchTerms: ["triage", "bug", "issue", "report", "broken", "debug", "help", "support"],+ run: () => void startTriage(triageEnvironmentId),+ });+ }const projectByKey = new Map(projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),);@@ -430,12 +468,15 @@ export function CommandPalette(props: {activeThread,activeThreadRef,environments.length,+ canTriage,navigation,projects,runCommand,savedConnectionsById,selectDetail,+ startTriage,threads,+ triageEnvironmentId,]);const rankedMessageKeys = useMemo(() => {const subjectByKey = new Map(diff --git a/apps/mobile/src/features/triage/triageTarget.test.ts b/apps/mobile/src/features/triage/triageTarget.test.tsnew file mode 100644index 00000000000..58fc8b3e04c--- /dev/null+++ b/apps/mobile/src/features/triage/triageTarget.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vite-plus/test";++import { pickTriageEnvironment } from "./triageTarget";++describe("pickTriageEnvironment", () => {+ it("triages the machine on screen", () => {+ expect(+ pickTriageEnvironment({+ onScreen: "laptop",+ connected: ["desktop", "laptop"],+ supportsTriage: () => true,+ }),+ ).toBe("laptop");+ });++ it("with nothing on screen, skips connected machines whose server lacks triage", () => {+ expect(+ pickTriageEnvironment({+ onScreen: null,+ connected: ["old-server", "new-server"],+ supportsTriage: (environmentId) => environmentId === "new-server",+ }),+ ).toBe("new-server");+ });+});diff --git a/apps/mobile/src/features/triage/triageTarget.ts b/apps/mobile/src/features/triage/triageTarget.tsnew file mode 100644index 00000000000..0712ab21e2f--- /dev/null+++ b/apps/mobile/src/features/triage/triageTarget.ts@@ -0,0 +1,11 @@+/**+ * The machine triage runs on: the one on screen, else the first connected+ * machine whose server supports triage. The palette row names the pick.+ */+export function pickTriageEnvironment<Id extends string>(input: {+ readonly onScreen: Id | null;+ readonly connected: ReadonlyArray<Id>;+ readonly supportsTriage: (environmentId: Id) => boolean;+}): Id | null {+ return input.onScreen ?? input.connected.find(input.supportsTriage) ?? null;+}diff --git a/apps/mobile/src/features/triage/useStartTriage.ts b/apps/mobile/src/features/triage/useStartTriage.tsnew file mode 100644index 00000000000..059e852337d--- /dev/null+++ b/apps/mobile/src/features/triage/useStartTriage.ts@@ -0,0 +1,106 @@+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import type { EnvironmentId } from "@t3tools/contracts";+import { useNavigation } from "@react-navigation/native";+import * as Clipboard from "expo-clipboard";+import Constants from "expo-constants";++import * as Dialog from "../../components/ui/Dialog";+import { authClientMetadata } from "../../lib/authClientMetadata";+import { projectEnvironment } from "../../state/projects";+import { serverEnvironment } from "../../state/server";+import { useAtomCommand } from "../../state/use-atom-command";+import {+ createNewTaskDraft,+ setComposerDraftText,+ waitForComposerDraftsLoaded,+} from "../../state/use-composer-drafts";+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";++const CLI_COMMAND = "npx t3 triage";++/**+ * In-app `t3 triage`, as on web: the server writes the session files and+ * clones the matching source, then a No project draft opens with the prompt.+ */+export function useStartTriage() {+ const navigation = useNavigation();+ const selectDetail = useSelectWorkspaceDetail();+ const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });+ const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });++ const fail = (message: string) =>+ Dialog.alert(+ "Could not start triage",+ `${message} Run ${CLI_COMMAND} in a terminal on that machine instead.`,+ [+ {+ text: "Copy command",+ onPress: () =>+ void Clipboard.setStringAsync(CLI_COMMAND).catch(() =>+ Dialog.alert("Could not copy", `Type ${CLI_COMMAND} instead.`),+ ),+ },+ { text: "OK", style: "cancel" },+ ],+ );+ const errorMessage = (error: unknown, fallback: string) =>+ error instanceof Error ? error.message : fallback;++ const activeRoute = () => {+ const state = navigation.getState();+ return state?.routes[state.index];+ };++ return async (environmentId: EnvironmentId) => {+ // If the user goes elsewhere while this waits, the draft stays closed+ // instead of pulling them away. Split view changes params, not the route.+ const startRoute = activeRoute();+ const routeChanged = () => {+ const route = activeRoute();+ if (route === startRoute) return false;+ if (route === undefined || startRoute === undefined) return true;+ return route.key !== startRoute.key || route.params !== startRoute.params;+ };+ const scratch = await openScratch({ environmentId, input: {} });+ if (scratch._tag === "Failure") {+ if (!isAtomCommandInterrupted(scratch)) {+ fail(+ errorMessage(+ squashAtomCommandFailure(scratch),+ "This machine cannot start threads without a project.",+ ),+ );+ }+ return;+ }+ const prepared = await prepare({+ environmentId,+ input: { client: authClientMetadata(Constants.expoConfig?.version) },+ });+ if (prepared._tag === "Failure") {+ if (!isAtomCommandInterrupted(prepared)) {+ fail(errorMessage(squashAtomCommandFailure(prepared), "The server could not prepare it."));+ }+ return;+ }+ try {+ await waitForComposerDraftsLoaded();+ } catch {+ fail("Drafts could not be loaded.");+ return;+ }+ if (routeChanged()) return;+ const draftId = createNewTaskDraft({+ environmentId,+ projectId: scratch.value.id,+ });+ setComposerDraftText(draftId, prepared.value.prompt);+ selectDetail({+ name: "Thread",+ params: { draft: { environmentId, projectId: scratch.value.id, title: "Triage", draftId } },+ });+ };+}diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.tsindex 397adb04fbf..122b4bac892 100644--- a/apps/server/src/auth/RpcAuthorization.test.ts+++ b/apps/server/src/auth/RpcAuthorization.test.ts@@ -43,6 +43,12 @@ describe("RPC authorization scopes", () => {}});+ it("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {+ expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(+ AuthOrchestrationOperateScope,+ );+ });+it("separates passive terminal observation from operations that can change a shell", () => {for (const method of [WS_METHODS.terminalObserve,diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.tsindex e6f2f51eec5..b040054748c 100644--- a/apps/server/src/cli/triage.ts+++ b/apps/server/src/cli/triage.ts@@ -1,33 +1,23 @@// @effect-diagnostics nodeBuiltinImport:offimport * as NodeChildProcess from "node:child_process";-import * as NodeOS from "node:os";import * as NodeReadlinePromises from "node:readline/promises";-import * as HostProcess from "@t3tools/shared/HostProcess";import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";import * as Config from "effect/Config";import * as Console from "effect/Console";-import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";import * as Option from "effect/Option";-import * as Path from "effect/Path";import * as Schema from "effect/Schema";import { Command, Flag } from "effect/cli";import packageJson from "../../package.json" with { type: "json" };-import * as BootService from "../cloud/bootService.ts";import * as ServerConfig from "../config.ts";import { resolveBaseDir } from "../os-jank.ts";-import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";+import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";+import { describeServerProcess, writeTriageSession } from "../triage/triageSession.ts";import { baseDirFlag } from "./config.ts";import { interactiveStdin } from "./consoleStdin.ts";import { resolveCliCommand } from "./invocation.ts";-import {- buildTriageContext,- buildTriageLaunchPrompt,- buildTriageSeedPrompt,-} from "./triagePrompt.ts";interface TriageAgent {readonly id: "claude" | "codex";@@ -67,23 +57,6 @@ export class TriageAgentSpawnError extends Schema.TaggedError<TriageAgentSpawnEr}}-export const describeServerProcess = Effect.fn("triage.describeServerProcess")(function* (- serverRuntimeStatePath: string,-) {- const state = yield* readPersistedServerRuntimeState(serverRuntimeStatePath);- if (Option.isNone(state)) {- return "not running (no server-runtime.json; the server may never have started here)";- }- const version =- state.value.serverVersion === undefined- ? "version not recorded"- : `version ${state.value.serverVersion}`;- if (!isProcessAlive(state.value.pid)) {- return `not running (state file is stale: pid ${String(state.value.pid)} is dead; last origin ${state.value.origin}, ${version})`;- }- return `running (pid ${String(state.value.pid)}, ${state.value.origin}, ${version})`;-});-const pickAgent = (agents: ReadonlyArray<TriageAgent>) =>Effect.promise(async () => {const readline = NodeReadlinePromises.createInterface({@@ -149,49 +122,22 @@ export const triageCommand = Command.make("triage", {),Command.withHandler((flags) =>Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;-// Triage is a user-facing feature: always the userdata state, never dev.const explicitBaseDir = Option.getOrUndefined(flags.baseDir);const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});- const now = yield* DateTime.now;- const scratchDir = path.join(- paths.stateDir,- "triage",- DateTime.formatIso(now).replaceAll(":", "-").replace(".", "-"),- );- yield* fs.makeDirectory(scratchDir, { recursive: true });-- const contextFilePath = path.join(scratchDir, "context.md");- yield* fs.writeFileString(- contextFilePath,- buildTriageContext({- generatedAt: DateTime.formatIso(now),+ const session = yield* writeTriageSession({+ baseDir,+ paths,+ entry: {+ kind: "cli",cliVersion: packageJson.version,- os: `${yield* HostProcess.Platform} ${yield* HostProcess.Architecture} (${NodeOS.release()})`,- nodeVersion: process.version,launchedAs: yield* resolveCliCommand("triage"),- server: yield* describeServerProcess(paths.serverRuntimeStatePath),- paths: {- stateDir: paths.stateDir,- dbPath: paths.dbPath,- settingsPath: paths.settingsPath,- logsDir: paths.logsDir,- serviceLogPath: path.join(paths.logsDir, BootService.BOOT_SERVICE_LOG_FILE),- desktopBackendLogGlob: path.join(paths.logsDir, "server-child*.log*"),- serverTracePath: paths.serverTracePath,- providerEventLogPath: paths.providerEventLogPath,- terminalLogsDir: paths.terminalLogsDir,- providerStatusCacheDir: paths.providerStatusCacheDir,- secretsDir: paths.secretsDir,- sourceCacheDir: path.join(baseDir, "source"),- },- }),- );+ },+ server: yield* describeServerProcess(paths.serverRuntimeStatePath),+ });const installed: Array<TriageAgent> = [];for (const agent of TRIAGE_AGENTS) {@@ -217,9 +163,8 @@ export const triageCommand = Command.make("triage", {selected = yield* pickAgent(installed);}- // Windows .cmd shims cannot carry multiline argv; keep the playbook on disk for both launch and paste fallback.- const promptFilePath = path.join(scratchDir, "prompt.md");- yield* fs.writeFileString(promptFilePath, buildTriageSeedPrompt(contextFilePath));+ // Windows .cmd shims cannot carry multiline argv; the prompt file also serves as the paste fallback.+ const { sessionDir, promptFilePath, contextFilePath } = session;if (selected === undefined) {yield* Console.log(@@ -242,7 +187,7 @@ export const triageCommand = Command.make("triage", {buildTriageLaunchPrompt(promptFilePath),]);yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);- const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: scratchDir });+ const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: sessionDir });if (exitCode !== 0) {process.exitCode = exitCode;}diff --git a/apps/server/src/cli/triagePrompt.test.ts b/apps/server/src/cli/triagePrompt.test.tsdeleted file mode 100644index 07c3872b699..00000000000--- a/apps/server/src/cli/triagePrompt.test.ts+++ /dev/null@@ -1,53 +0,0 @@-// @effect-diagnostics nodeBuiltinImport:off-import * as NodeFS from "node:fs";-import * as NodePath from "node:path";--import { assert, it } from "@effect/vitest";--import { buildTriageContext, buildTriageLaunchPrompt, TRIAGE_PLAYBOOK } from "./triagePrompt.ts";--it("stays byte-identical to .github/triage/PLAYBOOK.md", () => {- // Older releases fetch the repository playbook.- const canonicalPath = NodePath.join(- import.meta.dirname,- "../../../../.github/triage/PLAYBOOK.md",- );- assert.equal(TRIAGE_PLAYBOOK, NodeFS.readFileSync(canonicalPath, "utf8"));-});--it("launch prompt stays a single argv-safe line naming the prompt file", () => {- // Windows .cmd shims cannot carry multiline argv.- const launch = buildTriageLaunchPrompt(String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);- assert.notInclude(launch, "\n");- assert.include(launch, String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);- assert.isBelow(launch.length, 1_000);-});--it("context file labels the CLI version as the CLI's, not the user's build", () => {- const context = buildTriageContext({- generatedAt: "2026-09-24T00:00:00.000Z",- cliVersion: "0.0.42",- os: "linux x64 (7.2.0)",- nodeVersion: "v26.8.2",- launchedAs: "npx t3 triage",- server: "running (pid 42, http://127.0.0.1:3773, version 0.0.43-nightly.20260923.2173)",- paths: {- stateDir: "/home/u/.t3/userdata",- dbPath: "/home/u/.t3/userdata/state.sqlite",- settingsPath: "/home/u/.t3/userdata/settings.json",- logsDir: "/home/u/.t3/userdata/logs",- serviceLogPath: "/home/u/.t3/userdata/logs/boot-service.log",- desktopBackendLogGlob: "/home/u/.t3/userdata/logs/server-child*.log*",- serverTracePath: "/home/u/.t3/userdata/logs/server.trace.ndjson",- providerEventLogPath: "/home/u/.t3/userdata/logs/provider/events.log",- terminalLogsDir: "/home/u/.t3/userdata/logs/terminals",- providerStatusCacheDir: "/home/u/.t3/caches",- secretsDir: "/home/u/.t3/userdata/secrets",- sourceCacheDir: "/home/u/.t3/source",- },- });- assert.notInclude(context, "Installed version");- assert.notInclude(context, "Release tag");- assert.include(context, "- Triage CLI version: 0.0.42 (");- assert.include(context, "version 0.0.43-nightly.20260923.2173");-});diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex 312556237f5..2b9b1f95b07 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -259,6 +259,7 @@ export const make = Effect.gen(function* () {environmentIcon: true,projectCloneTracking: true,ignoredFileListing: true,+ triage: true,...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),...(serverInstallation === null ? {} : { serverInstallation }),...(serverSelfUpdate === "boot-service" || desktopAppUpdatediff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 88a53889377..f2737254b91 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -83,6 +83,7 @@ const RPC_AGGREGATES = {[WS_METHODS.serverGetResourceTelemetryHistory]: "server",[WS_METHODS.serverRetryResourceTelemetry]: "server",[WS_METHODS.serverCheckOtlpEndpoint]: "server",+ [WS_METHODS.serverPrepareTriage]: "server",[WS_METHODS.serverGetUsageSummary]: "server",[WS_METHODS.serverRefreshUsageRates]: "server",[WS_METHODS.serverSignalProcess]: "server",diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex b84b9eb7856..27e7a4b2e97 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -170,6 +170,7 @@ import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";import * as HostResources from "./resourceTelemetry/HostResources.ts";import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";+import * as TriageService from "./triage/TriageService.ts";import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";@@ -693,6 +694,7 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe(Layer.provideMerge(layerBackground),Layer.provideMerge(layerResourceDiagnostics),Layer.provideMerge(TraceDiagnostics.layer),+ Layer.provideMerge(TriageService.layer.pipe(Layer.provide(GitVcsDriver.layer))),Layer.provideMerge(AnalyticsService.layer),Layer.provideMerge(ExternalLauncher.layer),Layer.provideMerge(RemoteOpenTargets.layer),diff --git a/apps/server/src/testUtils/shardWeights.json b/apps/server/src/testUtils/shardWeights.jsonindex d0f1fafc696..86df1db6d73 100644--- a/apps/server/src/testUtils/shardWeights.json+++ b/apps/server/src/testUtils/shardWeights.json@@ -17,7 +17,6 @@"src/cli/service.test.ts": 0.5,"src/cli/theme.test.ts": 2.1,"src/cli/trace.test.ts": 1.2,- "src/cli/triage.test.ts": 0.5,"src/cli/uninstall.test.ts": 0.5,"src/cli/update.test.ts": 1.7,"src/cloud/CliTokenManager.test.ts": 0.7,@@ -203,6 +202,7 @@"src/textGeneration/OpenCode2TextGeneration.test.ts": 1.4,"src/textGeneration/TextGeneration.test.ts": 1.2,"src/textGeneration/ThreadTitleLinks.test.ts": 0.5,+ "src/triage/triageSession.test.ts": 0.5,"src/usage/UsageLimitSources.test.ts": 0.6,"src/usage/UsageService.test.ts": 2.2,"src/usage/cliproxyApi.test.ts": 0.5,diff --git a/apps/server/src/triage/TriageService.test.ts b/apps/server/src/triage/TriageService.test.tsnew file mode 100644index 00000000000..d3ffc8c91d0--- /dev/null+++ b/apps/server/src/triage/TriageService.test.ts@@ -0,0 +1,162 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { GitCommandError } from "@t3tools/contracts";+import { assert, it } from "@effect/vitest";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Queue from "effect/Queue";+import { ChildProcessSpawner } from "effect/process";++import packageJson from "../../package.json" with { type: "json" };+import * as ServerConfig from "../config.ts";+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";+import * as VcsProcess from "../vcs/VcsProcess.ts";+import * as TriageService from "./TriageService.ts";+import { pickSourceRef } from "./TriageService.ts";++const MAIN = "a1dc856ee61278d0199c36d4bcdef5fdea4d21fe\trefs/heads/main";++it("clones the server's release tag, peeling annotated tags to their commit", () => {+ assert.deepEqual(pickSourceRef(`${MAIN}\n7027b1f\trefs/tags/v0.1.1\n`, "0.1.1"), {+ ref: "v0.1.1",+ commit: "7027b1f",+ });+ assert.deepEqual(+ pickSourceRef(`${MAIN}\n1111111\trefs/tags/v0.1.1\n2222222\trefs/tags/v0.1.1^{}\n`, "0.1.1"),+ { ref: "v0.1.1", commit: "2222222" },+ );+});++it("falls back to main when the server's version has no tag", () => {+ assert.deepEqual(pickSourceRef(`${MAIN}\n`, "0.1.2-dev"), {+ ref: "main",+ commit: "a1dc856ee61278d0199c36d4bcdef5fdea4d21fe",+ });+ assert.isUndefined(pickSourceRef("", "0.1.1"));+});++const TestLayer = GitVcsDriver.layer.pipe(+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-triage-service-" })),+ Layer.provideMerge(VcsProcess.layer),+ Layer.provideMerge(NodeServices.layer),+);++const RELEASE_COMMIT = "7027b1f";++/** The service over a stub git that answers each command with `answer`. */+const makeTriage = (+ answer: (command: string) => Effect.Effect<string, GitCommandError> = (command) =>+ Effect.succeed(+ command === "ls-remote"+ ? `${RELEASE_COMMIT}\trefs/tags/v${packageJson.version}\n`+ : command === "rev-parse"+ ? `${RELEASE_COMMIT}\n`+ : "",+ ),+) =>+ Effect.gen(function* () {+ const git = yield* GitVcsDriver.GitVcsDriver;+ const commands: string[] = [];+ const triage = yield* Layer.build(TriageService.layer).pipe(+ Effect.map(Context.get(TriageService.TriageService)),+ Effect.provideService(GitVcsDriver.GitVcsDriver, {+ ...git,+ execute: (input) => {+ const command = input.args[0] ?? "";+ commands.push(command);+ return answer(command).pipe(+ Effect.map((stdout) => ({+ exitCode: ChildProcessSpawner.ExitCode(0),+ stdout,+ stderr: "",+ stdoutTruncated: false,+ stderrTruncated: false,+ })),+ );+ },+ }),+ );+ return { triage, commands };+ });++const readContext = Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const config = yield* ServerConfig.ServerConfig;+ const sessions = `${config.stateDir}/triage`;+ const [session] = yield* fs.readDirectory(sessions);+ return yield* fs.readFileString(`${sessions}/${session}/context.md`);+});++it.effect("sessions started during a clone share it, and a release tag is looked up once", () =>+ Effect.gen(function* () {+ const fetches = yield* Queue.unbounded<void>();+ const { triage, commands } = yield* makeTriage((command) =>+ command === "fetch"+ ? Queue.offer(fetches, undefined).pipe(Effect.andThen(Effect.never))+ : Effect.succeed(+ command === "ls-remote" ? `${RELEASE_COMMIT}\trefs/tags/v${packageJson.version}\n` : "",+ ),+ );++ yield* triage.prepare({ client: {} });+ yield* triage.prepare({ client: {} });+ yield* Queue.take(fetches);++ assert.deepEqual(+ commands.filter((command) => command === "ls-remote" || command === "init"),+ ["ls-remote", "init"],+ );+ }).pipe(Effect.provide(TestLayer)),+);++it.effect("reuses a finished clone without fetching", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const config = yield* ServerConfig.ServerConfig;+ yield* fs.makeDirectory(`${config.baseDir}/source/${RELEASE_COMMIT}/.git`, {+ recursive: true,+ });+ const { triage, commands } = yield* makeTriage();++ yield* triage.prepare({ client: {} });++ assert.deepEqual(commands, ["ls-remote", "rev-parse"]);+ assert.include(yield* readContext, "The server cloned the source for its own version");+ }).pipe(Effect.provide(TestLayer)),+);++it.effect("still starts triage when the source lookup fails", () =>+ Effect.gen(function* () {+ const { triage } = yield* makeTriage(() =>+ Effect.fail(+ new GitCommandError({+ operation: "TriageService.resolveSourceRef",+ command: "git ls-remote",+ cwd: "/",+ detail: "Could not resolve host: github.com",+ }),+ ),+ );++ const { prompt } = yield* triage.prepare({ client: {} });++ assert.include(prompt, "triage-playbook.md");+ assert.include(yield* readContext, "Could not resolve host: github.com");+ }).pipe(Effect.provide(TestLayer)),+);++it.effect("does not trust a folder without its own .git, even inside a repo at that commit", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const config = yield* ServerConfig.ServerConfig;+ yield* fs.makeDirectory(`${config.baseDir}/source/${RELEASE_COMMIT}`, { recursive: true });+ // The stub answers rev-parse with the commit, as a parent repository could.+ const { triage, commands } = yield* makeTriage();++ yield* triage.prepare({ client: {} });++ assert.notInclude(commands, "rev-parse");+ assert.include(yield* readContext, "is not a complete checkout");+ }).pipe(Effect.provide(TestLayer)),+);diff --git a/apps/server/src/triage/TriageService.ts b/apps/server/src/triage/TriageService.tsnew file mode 100644index 00000000000..f7a93f24a66--- /dev/null+++ b/apps/server/src/triage/TriageService.ts@@ -0,0 +1,216 @@+import {+ type AuthClientPresentationMetadata,+ ServerPrepareTriageError,+ type ServerPrepareTriageInput,+ type ServerPrepareTriageResult,+} from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Layer from "effect/Layer";+import * as Path from "effect/Path";++import packageJson from "../../package.json" with { type: "json" };+import * as ServerConfig from "../config.ts";+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";+import { buildTriageAppPrompt, type TriageSourceClone } from "./triagePrompt.ts";+import { triageSourceCacheDir, writeTriageSession } from "./triageSession.ts";++const T3CODE_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";++// No tty: a credential prompt would hang until the timeout, so git must fail+// instead. An empty GIT_ASKPASS also skips core.askPass and SSH_ASKPASS helpers.+const GIT_ENV = {+ GIT_TERMINAL_PROMPT: "0",+ GIT_ASKPASS: "",+ LC_ALL: "C",+} satisfies NodeJS.ProcessEnv;++/** Starts in-app triage sessions: the same files `t3 triage` writes, plus a source clone. */+export class TriageService extends Context.Service<+ TriageService,+ {+ readonly prepare: (+ input: ServerPrepareTriageInput,+ ) => Effect.Effect<ServerPrepareTriageResult, ServerPrepareTriageError>;+ }+>()("t3/triage/TriageService") {}++const describeClient = (client: AuthClientPresentationMetadata) =>+ [+ client.label ?? "an unknown client",+ client.appVersion === undefined ? undefined : `version ${client.appVersion}`,+ client.os === undefined ? undefined : `on ${client.os}`,+ client.browser === undefined ? undefined : `in ${client.browser}`,+ client.webDeployment === "hosted" ? "(app.t3.codes)" : undefined,+ ]+ .filter((part) => part !== undefined)+ .join(" ");++/** Picks the release tag for `version`, or `main` when the build has no tag. */+export const pickSourceRef = (lsRemoteOutput: string, version: string) => {+ const commits = new Map(+ lsRemoteOutput+ .split("\n")+ .map((line) => line.trim().split("\t"))+ .filter((fields): fields is [string, string] => fields.length === 2)+ .map(([commit, ref]) => [ref, commit]),+ );+ const tag = `v${version}`;+ // Annotated tags list the tag object first and the commit as `^{}`.+ const tagCommit = commits.get(`refs/tags/${tag}^{}`) ?? commits.get(`refs/tags/${tag}`);+ if (tagCommit !== undefined) return { ref: tag, commit: tagCommit };+ const mainCommit = commits.get("refs/heads/main");+ return mainCommit === undefined ? undefined : { ref: "main", commit: mainCommit };+};++const make = Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ const git = yield* GitVcsDriver.GitVcsDriver;+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const sourceDir = triageSourceCacheDir(config.baseDir, path);+ // Beside the cache, not in it: the playbook has agents prune the cache, and a+ // clone in progress must not look like a stale entry. Same filesystem, so the+ // finished clone moves in with a rename.+ const stagingDir = `${sourceDir}-staging`;+ const serverVersion = packageJson.version;++ const runGit = (operation: string, cwd: string, args: ReadonlyArray<string>, timeoutMs: number) =>+ git.execute({ operation: `TriageService.${operation}`, cwd, args, timeoutMs, env: GIT_ENV });++ // Clones outlive the request that started them: a fresh clone takes tens of+ // seconds, and the user is writing their description meanwhile.+ const serviceScope = yield* Effect.scope;+ // Clones a previous server process left half done.+ yield* fs.remove(stagingDir, { recursive: true }).pipe(Effect.ignore);++ // Fetches the exact commit `ls-remote` resolved, so the folder the session+ // names is the one that appears even when main moves meanwhile.+ const cloneSource = Effect.fn("TriageService.cloneSource")(function* (commit: string) {+ yield* fs.makeDirectory(stagingDir, { recursive: true });+ const staging = yield* fs.makeTempDirectory({ directory: stagingDir, prefix: "clone-" });+ const directory = path.join(sourceDir, commit);+ yield* Effect.gen(function* () {+ yield* runGit("initSource", staging, ["init", "--quiet"], 10_000);+ yield* runGit(+ "addSourceRemote",+ staging,+ ["remote", "add", "origin", T3CODE_REPOSITORY_URL],+ 10_000,+ );+ yield* runGit(+ "fetchSource",+ staging,+ ["fetch", "--depth", "1", "--filter=blob:none", "origin", commit],+ 600_000,+ );+ yield* runGit("checkoutSource", staging, ["checkout", "--quiet", "FETCH_HEAD"], 600_000);+ yield* fs.rename(staging, directory).pipe(+ // A concurrent session cloned the same commit first; keep theirs.+ Effect.catch((error) =>+ fs+ .exists(directory)+ .pipe(Effect.flatMap((exists) => (exists ? Effect.void : Effect.fail(error)))),+ ),+ );+ }).pipe(+ // Gone after a successful rename; otherwise a failed or losing clone.+ Effect.ensuring(fs.remove(staging, { recursive: true }).pipe(Effect.ignore)),+ );+ });++ // Release tags never move, so one lookup serves every later session. Builds+ // with no tag track main, which does move, so they look it up each time.+ let releaseSource: { readonly ref: string; readonly commit: string } | undefined;+ const resolveSource = Effect.fn("TriageService.resolveSource")(function* () {+ if (releaseSource !== undefined) return releaseSource;+ const tag = `refs/tags/v${serverVersion}`;+ const listed = yield* runGit(+ "resolveSourceRef",+ sourceDir,+ ["ls-remote", T3CODE_REPOSITORY_URL, tag, `${tag}^{}`, "refs/heads/main"],+ // Triage still starts without source; a dead network should not stall it.+ 5_000,+ );+ const source = pickSourceRef(listed.stdout, serverVersion);+ if (source?.ref !== "main") releaseSource = source;+ return source;+ });++ // Commits with a clone running, so sessions started meanwhile share it.+ const cloning = new Set<string>();++ // The playbook's own layout: one folder per commit under the source cache, so+ // the agent finds and reuses this clone instead of making another. The folder+ // appears only once the clone is complete.+ const startSourceClone = Effect.fn("TriageService.startSourceClone")(function* () {+ yield* fs.makeDirectory(sourceDir, { recursive: true });+ const source = yield* resolveSource();+ if (source === undefined) {+ return {+ _tag: "failed",+ serverVersion,+ reason: "the repository listed neither the release tag nor main.",+ } satisfies TriageSourceClone;+ }+ const directory = path.join(sourceDir, source.commit);+ if (yield* fs.exists(directory)) {+ // Our clones appear only when complete, but an agent may have cloned+ // here by hand and stopped partway.+ // Without its own .git, rev-parse would read a parent repository.+ const head = (yield* fs.exists(path.join(directory, ".git")))+ ? yield* runGit("checkSource", directory, ["rev-parse", "HEAD"], 10_000).pipe(+ Effect.map((result) => result.stdout.trim()),+ Effect.orElseSucceed(() => ""),+ )+ : "";+ return head === source.commit+ ? ({ _tag: "cloned", directory, serverVersion, ...source } as const)+ : ({+ _tag: "failed",+ serverVersion,+ reason: `${directory} exists but is not a complete checkout of ${source.commit}. Remove it first.`,+ } satisfies TriageSourceClone);+ }+ if (!cloning.has(source.commit)) {+ cloning.add(source.commit);+ yield* cloneSource(source.commit).pipe(+ Effect.ignoreCause({ log: true }),+ Effect.ensuring(Effect.sync(() => cloning.delete(source.commit))),+ Effect.forkIn(serviceScope),+ );+ }+ return { _tag: "cloning", directory, serverVersion, ...source } as const;+ });++ const prepare: TriageService["Service"]["prepare"] = Effect.fn("TriageService.prepare")(+ function* (input) {+ const sourceClone = yield* startSourceClone().pipe(+ Effect.catch((error) =>+ Effect.succeed<TriageSourceClone>({+ _tag: "failed",+ serverVersion,+ reason: error.message,+ }),+ ),+ );+ const session = yield* writeTriageSession({+ baseDir: config.baseDir,+ paths: config,+ entry: { kind: "app", client: describeClient(input.client) },+ server: `running (pid ${String(process.pid)}, version ${serverVersion}); this session runs inside it`,+ sourceClone,+ }).pipe(+ Effect.provideService(FileSystem.FileSystem, fs),+ Effect.provideService(Path.Path, path),+ Effect.mapError((cause) => new ServerPrepareTriageError({ cause })),+ );+ return { prompt: buildTriageAppPrompt(session.promptFilePath) };+ },+ );++ return TriageService.of({ prepare });+});++export const layer = Layer.effect(TriageService, make);diff --git a/apps/server/src/triage/triagePrompt.test.ts b/apps/server/src/triage/triagePrompt.test.tsnew file mode 100644index 00000000000..e034ad107fe--- /dev/null+++ b/apps/server/src/triage/triagePrompt.test.ts@@ -0,0 +1,82 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeFS from "node:fs";+import * as NodePath from "node:path";++import { assert, it } from "@effect/vitest";++import {+ buildTriageContext,+ buildTriageLaunchPrompt,+ type TriageContextInput,+ TRIAGE_PLAYBOOK,+} from "./triagePrompt.ts";++it("stays byte-identical to .github/triage/PLAYBOOK.md", () => {+ // Older releases fetch the repository playbook.+ const canonicalPath = NodePath.join(+ import.meta.dirname,+ "../../../../.github/triage/PLAYBOOK.md",+ );+ assert.equal(TRIAGE_PLAYBOOK, NodeFS.readFileSync(canonicalPath, "utf8"));+});++it("launch prompt stays a single argv-safe line naming the prompt file", () => {+ // Windows .cmd shims cannot carry multiline argv.+ const launch = buildTriageLaunchPrompt(String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);+ assert.notInclude(launch, "\n");+ assert.include(launch, String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);+ assert.isBelow(launch.length, 1_000);+});++it("context file labels the CLI version as the CLI's, not the user's build", () => {+ const context = buildTriageContext({+ ...contextInput,+ entry: { kind: "cli", cliVersion: "0.0.42", launchedAs: "npx t3 triage" },+ server: "running (pid 42, http://127.0.0.1:3773, version 0.0.43-nightly.20260923.2173)",+ });+ assert.notInclude(context, "Installed version");+ assert.notInclude(context, "Release tag");+ assert.include(context, "- Triage CLI version: 0.0.42 (");+ assert.include(context, "version 0.0.43-nightly.20260923.2173");+ assert.notInclude(context, "runs inside T3 Code");+});++it("in-app context warns the agent off its own server and points at the clone in progress", () => {+ const context = buildTriageContext({+ ...contextInput,+ entry: { kind: "app", client: "T3 Code Desktop version 0.1.1 on macos" },+ server: "running (pid 42, version 0.1.1); this session runs inside it",+ sourceClone: {+ _tag: "cloning",+ directory: "/home/u/.t3/source/abc123",+ ref: "v0.1.1",+ commit: "abc123",+ serverVersion: "0.1.1",+ },+ });+ assert.notInclude(context, "Triage CLI version");+ assert.include(context, "- Started from: T3 Code Desktop version 0.1.1 on macos (");+ assert.include(context, "## This session runs inside T3 Code");+ assert.include(context, "/home/u/.t3/source/abc123 (v0.1.1, commit abc123)");+ assert.include(context, "Wait for it instead of\ncloning again.");+});++const contextInput = {+ generatedAt: "2026-09-24T00:00:00.000Z",+ os: "linux x64 (7.2.0)",+ nodeVersion: "v26.8.2",+ paths: {+ stateDir: "/home/u/.t3/userdata",+ dbPath: "/home/u/.t3/userdata/state.sqlite",+ settingsPath: "/home/u/.t3/userdata/settings.json",+ logsDir: "/home/u/.t3/userdata/logs",+ serviceLogPath: "/home/u/.t3/userdata/logs/boot-service.log",+ desktopBackendLogGlob: "/home/u/.t3/userdata/logs/server-child*.log*",+ serverTracePath: "/home/u/.t3/userdata/logs/server.trace.ndjson",+ providerEventLogPath: "/home/u/.t3/userdata/logs/provider/events.log",+ terminalLogsDir: "/home/u/.t3/userdata/logs/terminals",+ providerStatusCacheDir: "/home/u/.t3/caches",+ secretsDir: "/home/u/.t3/userdata/secrets",+ sourceCacheDir: "/home/u/.t3/source",+ },+} satisfies Omit<TriageContextInput, "entry" | "server">;diff --git a/apps/server/src/cli/triagePrompt.ts b/apps/server/src/triage/triagePrompt.tssimilarity index 69%rename from apps/server/src/cli/triagePrompt.tsrename to apps/server/src/triage/triagePrompt.tsindex 7188c101f8c..5c937abdb89 100644--- a/apps/server/src/cli/triagePrompt.ts+++ b/apps/server/src/triage/triagePrompt.ts@@ -1,3 +1,5 @@+import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";+/** Keep TRIAGE_PLAYBOOK byte-identical to .github/triage/PLAYBOOK.md after unescaping backticks and backslashes. */export const TRIAGE_PLAYBOOK = `# T3 Code triage playbook@@ -13,8 +15,8 @@ provided alongside this playbook. Everything machine-specific lives there, not h## 1. Ask what went wrong-Your first message to the user: ask them to describe what went wrong, in their own-words. Ask them to paste screenshots directly into this session if they have any.+Unless the user already described it, your first message asks what went wrong, in+their own words. Ask them to paste screenshots directly into this session if they have any.Ask follow-up questions when the description is vague. Good repro steps are the mostvaluable thing you can extract from this conversation.@@ -147,30 +149,61 @@ user's environment and evidence instead of filing a new issue. A confirmedduplicate with fresh evidence is more useful than a second thread.`;+/** Where the session started: the `t3 triage` CLI, or "Triage an issue" in a client. */+export type TriageEntry =+ | { readonly kind: "cli"; readonly cliVersion: string; readonly launchedAs: string }+ | { readonly kind: "app"; readonly client: string };+/** Windows .cmd shims cannot carry a multiline playbook in argv; point to the file instead. */export const buildTriageLaunchPrompt = (promptFilePath: string) =>`Read the file "${promptFilePath}" and follow its instructions exactly: it is your T3 Code triage playbook, and it starts with asking the user what went wrong.`;-export const buildTriageSeedPrompt = (contextFilePath: string) => `A T3 Code user is \-having a problem with their install and started this session with \`t3 triage\`.+/**+ * The composer text an in-app session opens with. The file link renders as a+ * chip, and the user writes what went wrong after it, so the first turn+ * already carries the description.+ */+export const buildTriageAppPrompt = (promptFilePath: string) =>+ `Read ${serializeComposerFileLink(promptFilePath)} and follow it. `;++export const buildTriageSeedPrompt = (input: {+ readonly contextFilePath: string;+ readonly entry: TriageEntry;+}) => `A T3 Code user is having a problem with their install and started this \+session ${input.entry.kind === "cli" ? "with `t3 triage`" : "from the T3 Code app"}.Machine facts (versions, OS, paths, server liveness) are in the triage context file:- ${contextFilePath}+ ${input.contextFilePath}-Follow the playbook below, starting by asking the user what went wrong.+${+ input.entry.kind === "cli"+ ? "Follow the playbook below, starting by asking the user what went wrong."+ : "Follow the playbook below. The message that sent you here may already describe what went wrong; if it does not, start by asking."+}---${TRIAGE_PLAYBOOK}`;+/** A clone the server made before the session started, or why it could not. */+export type TriageSourceClone =+ | {+ readonly _tag: "cloned" | "cloning";+ readonly directory: string;+ readonly ref: string;+ readonly commit: string;+ readonly serverVersion: string;+ }+ | { readonly _tag: "failed"; readonly serverVersion: string; readonly reason: string };+export interface TriageContextInput {readonly generatedAt: string;- readonly cliVersion: string;+ readonly entry: TriageEntry;readonly os: string;readonly nodeVersion: string;- readonly launchedAs: string;readonly server: string;+ readonly sourceClone?: TriageSourceClone | undefined;readonly paths: {readonly stateDir: string;readonly dbPath: string;@@ -187,17 +220,74 @@ export interface TriageContextInput {};}-export const buildTriageContext = (input: TriageContextInput) => `# T3 Code triage context+const entryLines = (entry: TriageEntry) =>+ entry.kind === "cli"+ ? {+ generatedBy: "`t3 triage`",+ before: `- Triage CLI version: ${entry.cliVersion} (the \`t3\` that ran this command; the bug may have happened on another build)`,+ after: `- CLI launched as: ${entry.launchedAs}`,+ }+ : {+ generatedBy: "the T3 Code app",+ before: `- Started from: ${entry.client} (the client the user pressed "Triage an issue" in; the bug may have happened on another device)`,+ after: undefined,+ };++const sourceSection = (clone: TriageSourceClone) => {+ if (clone._tag === "failed") {+ return `+## Source++The server could not clone the source for its version (${clone.serverVersion}): ${clone.reason}+Clone it as step 4 describes.+`;+ }+ const verb = clone._tag === "cloned" ? "The server cloned" : "The server is cloning";+ const what =+ clone.ref === "main"+ ? `main, since its version (${clone.serverVersion}) has no release tag`+ : `the source for its own version (${clone.serverVersion})`;+ const wait =+ clone._tag === "cloned"+ ? ""+ : `+The folder appears only when the clone is complete. Wait for it instead of+cloning again. If it has not appeared after a few minutes, clone as step 4+describes.+`;+ return `+## Source-Generated by \`t3 triage\` at ${input.generatedAt}.+${verb} ${what}:-- Triage CLI version: ${input.cliVersion} (the \`t3\` that ran this command; the bug may have happened on another build)+ ${clone.directory} (${clone.ref}, commit ${clone.commit})+${wait}+Use it when the bug happened on this server's build. When it happened on another+build, clone that version as step 4 describes.+`;+};++const IN_APP_SECTION = `+## This session runs inside T3 Code++You are a thread inside the T3 Code server described above. Stopping,+restarting, or killing that server, its service, or the desktop app ends this+session. When a fix needs one of those, give the user the exact steps and let+them do it. The database is in use by that server: read it, never lock it.+`;++export const buildTriageContext = (input: TriageContextInput) => {+ const entry = entryLines(input.entry);+ return `# T3 Code triage context++Generated by ${entry.generatedBy} at ${input.generatedAt}.++${entry.before}- OS: ${input.os}- Node: ${input.nodeVersion}-- CLI launched as: ${input.launchedAs}-- Server process: ${input.server}+${entry.after === undefined ? "" : `${entry.after}\n`}- Server process: ${input.server}- Repo: https://github.com/pingdotgg/t3code-+${input.entry.kind === "app" ? IN_APP_SECTION : ""}${input.sourceClone === undefined ? "" : sourceSection(input.sourceClone)}## Paths- State dir: ${input.paths.stateDir}@@ -213,3 +303,4 @@ Generated by \`t3 triage\` at ${input.generatedAt}.- Secrets dir (NEVER read this): ${input.paths.secretsDir}- Source cache dir (clone the repo here): ${input.paths.sourceCacheDir}`;+};diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/triage/triageSession.test.tssimilarity index 95%rename from apps/server/src/cli/triage.test.tsrename to apps/server/src/triage/triageSession.test.tsindex 7443c2425ac..6826ebd16bf 100644--- a/apps/server/src/cli/triage.test.ts+++ b/apps/server/src/triage/triageSession.test.ts@@ -9,7 +9,7 @@ import {makePersistedServerRuntimeState,persistServerRuntimeState,} from "../serverRuntimeState.ts";-import { describeServerProcess } from "./triage.ts";+import { describeServerProcess } from "./triageSession.ts";it.effect("reports the version the running server recorded, not the CLI's", () =>Effect.gen(function* () {diff --git a/apps/server/src/triage/triageSession.ts b/apps/server/src/triage/triageSession.tsnew file mode 100644index 00000000000..14654cf7d28--- /dev/null+++ b/apps/server/src/triage/triageSession.ts@@ -0,0 +1,100 @@+// @effect-diagnostics nodeBuiltinImport:off+import * as NodeOS from "node:os";++import { TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";+import * as HostProcess from "@t3tools/shared/HostProcess";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Path from "effect/Path";++import * as BootService from "../cloud/bootService.ts";+import type * as ServerConfig from "../config.ts";+import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";+import {+ buildTriageContext,+ buildTriageSeedPrompt,+ type TriageEntry,+ type TriageSourceClone,+} from "./triagePrompt.ts";++export const describeServerProcess = Effect.fn("triage.describeServerProcess")(function* (+ serverRuntimeStatePath: string,+) {+ const state = yield* readPersistedServerRuntimeState(serverRuntimeStatePath);+ if (Option.isNone(state)) {+ return "not running (no server-runtime.json; the server may never have started here)";+ }+ const version =+ state.value.serverVersion === undefined+ ? "version not recorded"+ : `version ${state.value.serverVersion}`;+ if (!isProcessAlive(state.value.pid)) {+ return `not running (state file is stale: pid ${String(state.value.pid)} is dead; last origin ${state.value.origin}, ${version})`;+ }+ return `running (pid ${String(state.value.pid)}, ${state.value.origin}, ${version})`;+});++/** The source cache the playbook clones into, one subdirectory per commit. */+export const triageSourceCacheDir = (baseDir: string, path: Path.Path) =>+ path.join(baseDir, "source");++/**+ * Writes `context.md` and the playbook prompt into a fresh `<stateDir>/triage/<time>`+ * folder. Both `t3 triage` and the in-app entry point start from these files.+ */+export const writeTriageSession = Effect.fn("triage.writeTriageSession")(function* (input: {+ readonly baseDir: string;+ readonly paths: ServerConfig.ServerDerivedPaths;+ readonly entry: TriageEntry;+ readonly server: string;+ readonly sourceClone?: TriageSourceClone | undefined;+}) {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const { paths } = input;++ const now = yield* DateTime.now;+ const sessionDir = path.join(+ paths.stateDir,+ "triage",+ DateTime.formatIso(now).replaceAll(":", "-").replace(".", "-"),+ );+ yield* fs.makeDirectory(sessionDir, { recursive: true });++ const contextFilePath = path.join(sessionDir, "context.md");+ yield* fs.writeFileString(+ contextFilePath,+ buildTriageContext({+ generatedAt: DateTime.formatIso(now),+ entry: input.entry,+ os: `${yield* HostProcess.Platform} ${yield* HostProcess.Architecture} (${NodeOS.release()})`,+ nodeVersion: process.version,+ server: input.server,+ sourceClone: input.sourceClone,+ paths: {+ stateDir: paths.stateDir,+ dbPath: paths.dbPath,+ settingsPath: paths.settingsPath,+ logsDir: paths.logsDir,+ serviceLogPath: path.join(paths.logsDir, BootService.BOOT_SERVICE_LOG_FILE),+ desktopBackendLogGlob: path.join(paths.logsDir, "server-child*.log*"),+ serverTracePath: paths.serverTracePath,+ providerEventLogPath: paths.providerEventLogPath,+ terminalLogsDir: paths.terminalLogsDir,+ providerStatusCacheDir: paths.providerStatusCacheDir,+ secretsDir: paths.secretsDir,+ sourceCacheDir: triageSourceCacheDir(input.baseDir, path),+ },+ }),+ );++ const promptFilePath = path.join(sessionDir, TRIAGE_PROMPT_FILE_NAME);+ yield* fs.writeFileString(+ promptFilePath,+ buildTriageSeedPrompt({ contextFilePath, entry: input.entry }),+ );++ return { sessionDir, contextFilePath, promptFilePath };+});diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.tsindex 3f3c8718e4c..fc5d1ca5274 100644--- a/apps/server/src/ws.test.ts+++ b/apps/server/src/ws.test.ts@@ -100,6 +100,7 @@ import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";+import * as TriageService from "./triage/TriageService.ts";import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";import * as ServerSecretStore from "./auth/ServerSecretStore.ts";import * as ServerConfigModule from "./config.ts";@@ -399,6 +400,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(Layer.mock(ServerSecretStore.ServerSecretStore)({}),Layer.mock(WorkspacePaths.WorkspacePaths)({}),Layer.mock(TraceDiagnostics.TraceDiagnostics)({}),+ Layer.mock(TriageService.TriageService)({}),Layer.mock(ProjectFaviconResolver.ProjectFaviconResolver)({}),Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex f686ca000db..37e38e66245 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -240,6 +240,7 @@ import { commandFeatureUsage, featureUsage } from "./telemetry/FeatureUsage.ts";import type { TelemetryOwner } from "./telemetry/Identify.ts";import * as UsageService from "./usage/UsageService.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";+import * as TriageService from "./triage/TriageService.ts";import * as PullRequestService from "./pullRequest/PullRequestService.ts";import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts";import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts";@@ -1376,6 +1377,7 @@ export const layerWsRpc = (const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;const sessions = yield* SessionStore.SessionStore;const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;+ const triage = yield* TriageService.TriageService;const hostResources = yield* HostResources.HostResources;const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;@@ -2580,6 +2582,7 @@ export const layerWsRpc = ([WS_METHODS.serverRefreshUsageRates]: (_input) => usage.refreshRates,[WS_METHODS.serverRetryResourceTelemetry]: (_input) => resourceTelemetry.retry,[WS_METHODS.serverCheckOtlpEndpoint]: (input) => otlpEndpointCheck.check(input),+ [WS_METHODS.serverPrepareTriage]: (input) => triage.prepare(input),[WS_METHODS.serverSignalProcess]: (input) => processDiagnostics.signal(input),[WS_METHODS.serverReportClientActivity]: (input, metadata) =>Ref.update(rpcClientIds, (clientIds) => {diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex a74736bfc59..c55f8924233 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -52,6 +52,7 @@ import {import { useLocation, useNavigate } from "@tanstack/react-router";import {ArrowLeftIcon,+ BugIcon,ChartNoAxesColumnIcon,CheckIcon,ChevronRightIcon,@@ -107,6 +108,8 @@ import { sourceControlEnvironment } from "../state/sourceControl";import { useAtomCommand } from "../state/use-atom-command";import { useAtomQueryRunner } from "../state/use-atom-query-runner";import { useScratchProject } from "../hooks/useScratchProject";+import { useStartTriage } from "../hooks/useStartTriage";+import { pickTriageEnvironment } from "../lib/triageTarget";import { useNewProject } from "../hooks/useNewProject";import { isScratchProject } from "@t3tools/client-runtime/state/projects";import {@@ -394,6 +397,7 @@ function OpenCommandPaletteDialog(props: {reportFailure: false,});const { scratchEnvironmentId, scratchWorkspaceRootFor, startScratchThread } = useScratchProject();+ const startTriage = useStartTriage();const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, {reportFailure: false,});@@ -632,6 +636,20 @@ function OpenCommandPaletteDialog(props: {const scratchTargetEnvironmentId = scratchEnvironmentId(currentProjectEnvironmentId ?? primaryEnvironmentId,);+ const supportsTriage = (environmentId: EnvironmentId | null) =>+ environments.find((environment) => environment.environmentId === environmentId)?.serverConfig+ ?.environment.capabilities.triage === true;+ const triageEnvironmentId = pickTriageEnvironment({+ onScreen: currentProjectEnvironmentId,+ primary: primaryEnvironmentId,+ connected: environments+ .filter((environment) => environment.connection.phase === "connected")+ .map((environment) => environment.environmentId),+ supportsTriage,+ });+ const canTriage =+ useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) &&+ supportsTriage(triageEnvironmentId);const currentProjectCwd = currentProjectId? (projectCwdById.get(currentProjectId) ?? null): null;@@ -1199,6 +1217,18 @@ function OpenCommandPaletteDialog(props: {});}+ if (triageEnvironmentId !== null && canTriage) {+ actionItems.push({+ kind: "action",+ value: "action:triage",+ searchTerms: ["triage", "bug", "issue", "report", "broken", "debug", "help", "support"],+ title: "Triage an issue",+ description: "An agent investigates a T3 Code problem and helps file an issue",+ icon: <BugIcon className={ITEM_ICON_CLASS} />,+ run: () => startTriage(triageEnvironmentId),+ });+ }+if (activeThreadKey !== null && supportsThreadFind) {actionItems.push({kind: "action",diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsxindex 46fed2ddc00..67fabfe570f 100644--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx@@ -12,6 +12,7 @@ import { shortcutLabelForCommand } from "~/keybindings";import { primaryServerKeybindingsAtom } from "~/state/server";import { useNewThreadHandler } from "~/hooks/useHandleNewThread";import { useScratchProject } from "~/hooks/useScratchProject";+import { isTriagePrompt } from "~/hooks/useStartTriage";import { useClientSettings } from "~/hooks/useSettings";import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";import {@@ -42,6 +43,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { InlineButton } from "../ui/button";import { DraftProjectName } from "./DraftProjectName";import { DraftHeroProjectHeading } from "./DraftHeroProjectHeading";+import { TriageDraftHero } from "./TriageDraftHero";import { resolveProjectSettings } from "@t3tools/shared/projectSettings";const ADD_PROJECT_VALUE = "add-project";@@ -72,6 +74,10 @@ export function DraftHeroHeadline({(store) => store.setLogicalProjectDraftThreadId,);const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);+ // A boolean, so typing in a draft does not re-render the hero.+ const isTriageDraftPrompt = useComposerDraftStore((store) =>+ draftId ? isTriagePrompt(store.getComposerDraft(draftId)?.prompt ?? "") : false,+ );const applyStickyState = useComposerDraftStore((store) => store.applyStickyState);const setModelSelection = useComposerDraftStore((store) => store.setModelSelection);const openAddProject = () => openCommandPalette({ open: "add-project" });@@ -336,6 +342,18 @@ export function DraftHeroHeadline({</Tooltip>) : null;+ if (isScratchDraft && isTriageDraftPrompt) {+ const environment = environments.find(+ (entry) => entry.environmentId === activeProject.environmentId,+ );+ return (+ <TriageDraftHero+ machineLabel={environment?.label ?? null}+ serverVersion={environment?.serverConfig?.environment.serverVersion ?? null}+ />+ );+ }+return (<div className="mx-auto flex w-full max-w-5xl flex-col items-center">{hasResolvedProject && !isScratchDraft ? (diff --git a/apps/web/src/components/chat/TriageDraftHero.tsx b/apps/web/src/components/chat/TriageDraftHero.tsxnew file mode 100644index 00000000000..c8d3d8528df--- /dev/null+++ b/apps/web/src/components/chat/TriageDraftHero.tsx@@ -0,0 +1,59 @@+import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";+import { TRIAGE_CLI_COMMAND } from "~/hooks/useStartTriage";++import { InlineButton } from "../ui/button";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";++/**+ * The empty-draft hero for a triage session, in place of "What should we work on?".+ * Keeps the regular hero's heading-plus-one-line rhythm above the composer.+ */+export function TriageDraftHero(props: {+ readonly machineLabel: string | null;+ readonly serverVersion: string | null;+}) {+ const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 1500, target: "command" });+ return (+ <div className="mx-auto flex w-full max-w-5xl flex-col items-center">+ <h1 className="w-full text-center font-normal text-2xl text-foreground tracking-tight sm:text-3xl">+ What went wrong?+ </h1>+ <p className="mt-2 flex h-6 w-full items-center justify-center gap-1.5 text-sm">+ <Tooltip>+ <TooltipTrigger+ render={<span tabIndex={0} className="min-w-0 truncate font-medium text-foreground" />}+ >+ {props.machineLabel ?? "This machine"}+ {props.serverVersion === null ? null : (+ <span className="ml-1.5 font-normal text-muted-foreground">+ v{props.serverVersion}+ </span>+ )}+ </TooltipTrigger>+ <TooltipPopup side="bottom">+ The agent reads T3 Code's logs and source here, and asks before it applies a fix or+ posts anything.+ </TooltipPopup>+ </Tooltip>+ <span aria-hidden className="text-muted-foreground">+ ·+ </span>+ <Tooltip>+ <TooltipTrigger+ render={+ <InlineButton+ tone="muted"+ className="pointer-events-auto"+ onClick={() => copyToClipboard(TRIAGE_CLI_COMMAND, undefined)}+ />+ }+ >+ {isCopied ? "Copied" : "or run"}+ {isCopied ? null : <code className="ml-1 font-mono text-xs">{TRIAGE_CLI_COMMAND}</code>}+ </TooltipTrigger>+ <TooltipPopup side="bottom">Copy command, for a terminal</TooltipPopup>+ </Tooltip>+ </p>+ </div>+ );+}diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.tsindex 4ac7fa26e3c..e60ed172e92 100644--- a/apps/web/src/connection/platform.ts+++ b/apps/web/src/connection/platform.ts@@ -151,7 +151,7 @@ const layerWakeups = Wakeups.layer({),});-function clientMetadata() {+export function currentClientMetadata() {return clientPresentationMetadata({appVersion: APP_VERSION,hosted: isHostedStaticApp(),@@ -325,7 +325,7 @@ const analyticsDevice = {const layerCapabilities = Layer.effectContext(Effect.sync(() => {const presentation = ClientCapabilities.ClientPresentation.of({- metadata: clientMetadata(),+ metadata: currentClientMetadata(),});const cloudSession = ClientCapabilities.CloudSession.of({identity: Effect.sync(() =>@@ -462,7 +462,7 @@ const loadSecondaryConnectionRegistration = Effect.fn(httpBaseUrl,credential: entry.bootstrapToken,scopes: AuthStandardClientScopes,- clientMetadata: clientMetadata(),+ clientMetadata: currentClientMetadata(),}).pipe(Effect.mapError(mapRemoteEnvironmentError));// Desktop operations need the pool backend id to reach the owning instance; RPC uses the environment id.const connectionId = desktopLocalConnectionId(entry.id);diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.tsindex ac18db8d7c5..195f3c37a07 100644--- a/apps/web/src/hooks/useHandleNewThread.test.ts+++ b/apps/web/src/hooks/useHandleNewThread.test.ts@@ -18,6 +18,8 @@ const testState = vi.hoisted(() => {readonly promotedTo: null;readonly threadId: string;} | null = null;+ let openDraftRoute: { readonly kind: "draft"; readonly draftId: string } | null = null;+ let draftsWithUserText = new Set<string>();const router = {state: {location: { href: "/" },@@ -28,14 +30,26 @@ const testState = vi.hoisted(() => {}),};const draftStore = {- getComposerDraft: vi.fn(() => ({})),+ getComposerDraft: vi.fn((draftId: string) => ({ draftId })),getDraftSessionByLogicalProjectKey: vi.fn(() => storedDraft),- getDraftSession: vi.fn(() => null),+ getDraftSession: vi.fn(() =>+ openDraftRoute === null+ ? null+ : {+ logicalProjectKey: "remote-project",+ promotedTo: null,+ threadId: "thread-open",+ createdAt: "2026-01-01T00:00:00.000Z",+ runtimeMode: "full-access",+ interactionMode: "default",+ },+ ),getDraftThread: vi.fn(() => null),applyStickyState: vi.fn(),setDraftThreadContext: vi.fn(),setLogicalProjectDraftThreadId: vi.fn(),setModelSelection: vi.fn(),+ setPrompt: vi.fn(),};return {@@ -56,6 +70,17 @@ const testState = vi.hoisted(() => {removeProject() {projectRemoved = true;},+ hasUserText: (draft: { readonly draftId?: string } | null | undefined) =>+ draft?.draftId !== undefined && draftsWithUserText.has(draft.draftId),+ giveUserText(draftId: string) {+ draftsWithUserText = new Set([...draftsWithUserText, draftId]);+ },+ get openDraftRoute() {+ return openDraftRoute;+ },+ openEmptyDraft(draftId: string) {+ openDraftRoute = { kind: "draft", draftId };+ },get targetSettings() {return targetSettings;},@@ -67,6 +92,8 @@ const testState = vi.hoisted(() => {},) {storedDraft = nextStoredDraft;+ openDraftRoute = null;+ draftsWithUserText = new Set();projectRemoved = false;connectedEnvironmentIds = ["environment-primary", "environment-ssh"];targetSettings = {@@ -79,6 +106,7 @@ const testState = vi.hoisted(() => {router.navigate.mockClear();draftStore.setDraftThreadContext.mockClear();draftStore.setLogicalProjectDraftThreadId.mockClear();+ draftStore.setPrompt.mockClear();projectFileRead = new Promise<null>((resolve) => {completeProjectFileRead = resolve;});@@ -161,7 +189,8 @@ vi.mock("../composerDraftStore", () => {getState: () => testState.draftStore,});return {- composerDraftHasUserContent: () => false,+ composerDraftHasUserContent: (draft: { readonly draftId?: string } | null | undefined) =>+ testState.hasUserText(draft),markPromotedDraftThreadByRef: vi.fn(),useComposerDraftStore,};@@ -208,7 +237,9 @@ vi.mock("../state/server", () => ({environmentServerConfigsAtom: {},primaryServerSettingsAtom: "primary-settings",}));-vi.mock("../threadRoutes", () => ({ resolveThreadRouteTarget: () => null }));+vi.mock("../threadRoutes", () => ({+ resolveThreadRouteTarget: () => testState.openDraftRoute,+}));vi.mock("../uiStateStore", () => ({legacyProjectCwdPreferenceKey: () => "remote-project",useUiStateStore: () => [],@@ -246,6 +277,25 @@ describe.each([expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled();});+ it("sets the prompt before the draft shows", async () => {+ testState.reset(draft);+ const pendingOpen = useNewThreadHandler()(+ { environmentId: "environment-ssh", projectId: "project-remote" } as never,+ { prompt: "Read the playbook. " },+ );++ testState.completeProjectFileRead(null);+ const opened = await pendingOpen;++ expect(testState.draftStore.setPrompt).toHaveBeenCalledWith(+ opened?.draftId,+ "Read the playbook. ",+ );+ expect(testState.draftStore.setPrompt.mock.invocationCallOrder[0]).toBeLessThan(+ testState.router.navigate.mock.invocationCallOrder[0] ?? 0,+ );+ });+it("abandons a delayed draft open when the project is removed meanwhile", async () => {testState.reset(draft);const pendingOpen = useNewThreadHandler()(@@ -263,6 +313,44 @@ describe.each([});describe("useNewThreadHandler", () => {+ it("keeps the text of a draft that gained some while it waited", async () => {+ testState.reset(null);+ const raced = {+ draftId: "draft-raced",+ environmentId: "environment-ssh",+ promotedTo: null,+ threadId: "thread-raced",+ };+ testState.draftStore.getDraftSessionByLogicalProjectKey+ .mockReturnValueOnce(null)+ .mockReturnValueOnce(raced as never);+ testState.giveUserText("draft-raced");++ const opened = await useNewThreadHandler()(+ { environmentId: "environment-ssh", projectId: "project-remote" } as never,+ { prompt: "Read the playbook. " },+ );++ expect(opened?.draftId).toBe("draft-raced");+ expect(testState.draftStore.setPrompt).not.toHaveBeenCalled();+ });++ it("seeds the prompt into the empty draft that is already open", async () => {+ testState.reset(null);+ testState.openEmptyDraft("draft-open");++ const opened = await useNewThreadHandler()(+ { environmentId: "environment-ssh", projectId: "project-remote" } as never,+ { prompt: "Read the playbook. " },+ );++ expect(opened?.draftId).toBe("draft-open");+ expect(testState.draftStore.setPrompt).toHaveBeenCalledWith(+ "draft-open",+ "Read the playbook. ",+ );+ });+it("opens the draft without waiting on a project file from an offline machine", async () => {testState.reset(null, { envMode: null, startFromOrigin: false });testState.disconnect("environment-ssh");diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.tsindex 90a45540b24..90990ae563f 100644--- a/apps/web/src/hooks/useHandleNewThread.ts+++ b/apps/web/src/hooks/useHandleNewThread.ts@@ -81,6 +81,8 @@ export function createNewThreadHandler(router: AnyRouter) {envMode?: DraftThreadEnvMode;startFromOrigin?: boolean;replace?: boolean;+ /** Composer text for the draft, set before it shows. A draft with user text keeps it. */+ prompt?: string;},): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {const projects = readProjects();@@ -98,7 +100,14 @@ export function createNewThreadHandler(router: AnyRouter) {setDraftThreadContext,setLogicalProjectDraftThreadId,setModelSelection,+ setPrompt,} = useComposerDraftStore.getState();+ // Never over text the user wrote: a draft can gain some while this awaits.+ const seedPrompt = (draftId: DraftId) => {+ if (options?.prompt === undefined) return;+ if (composerDraftHasUserContent(getComposerDraft(draftId))) return;+ setPrompt(draftId, options.prompt);+ };const requestingRouteHref = router.state.location.href;const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref;const currentRouteTarget = getCurrentRouteTarget();@@ -286,6 +295,7 @@ export function createNewThreadHandler(router: AnyRouter) {draftId: emptyStoredDraftThread.draftId,threadId: emptyStoredDraftThread.threadId,};+ seedPrompt(emptyStoredDraftThread.draftId);const routeTargetAfterWrites = getCurrentRouteTarget();if (routeTargetAfterWrites?.kind === "draft" &&@@ -324,6 +334,7 @@ export function createNewThreadHandler(router: AnyRouter) {interactionMode: latestActiveDraftThread.interactionMode,...pickExplicitWorkspaceOptions(options),});+ seedPrompt(currentRouteTarget.draftId);return Promise.resolve({draftId: currentRouteTarget.draftId,threadId: latestActiveDraftThread.threadId,@@ -352,6 +363,7 @@ export function createNewThreadHandler(router: AnyRouter) {interactionMode: racedDraft.interactionMode,...pickExplicitWorkspaceOptions(options),});+ seedPrompt(racedDraft.draftId);await router.navigate({to: "/draft/$draftId",params: { draftId: racedDraft.draftId },@@ -379,6 +391,7 @@ export function createNewThreadHandler(router: AnyRouter) {if (modelSelectionOverride) {setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true });}+ seedPrompt(draftId);await router.navigate({to: "/draft/$draftId",params: { draftId },diff --git a/apps/web/src/hooks/useStartTriage.ts b/apps/web/src/hooks/useStartTriage.tsnew file mode 100644index 00000000000..7d6671bf3d2--- /dev/null+++ b/apps/web/src/hooks/useStartTriage.ts@@ -0,0 +1,107 @@+import { scopeProjectRef } from "@t3tools/client-runtime/environment";+import {+ type AtomCommandResult,+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { type EnvironmentId, TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";+import { useRouter } from "@tanstack/react-router";++import { stackedThreadToast, toastManager } from "~/components/ui/toast";+import { currentClientMetadata } from "~/connection/platform";+import { projectEnvironment } from "~/state/projects";+import { serverEnvironment } from "~/state/server";+import { useAtomCommand } from "~/state/use-atom-command";+import { writeTextToClipboard } from "./useCopyToClipboard";+import { useNewThreadHandler } from "./useHandleNewThread";+import { useScratchProject } from "./useScratchProject";++export const TRIAGE_CLI_COMMAND = "npx t3 triage";++const copyTriageCliCommand = () =>+ writeTextToClipboard(TRIAGE_CLI_COMMAND, "command").catch(() =>+ toastManager.add({+ type: "error",+ title: `Could not copy. Type ${TRIAGE_CLI_COMMAND} instead.`,+ }),+ );++/** A draft is a triage draft while its message still links the playbook file. */+export const isTriagePrompt = (prompt: string) => prompt.includes(`[${TRIAGE_PROMPT_FILE_NAME}](`);++/**+ * In-app `t3 triage`: the server writes the session files and starts cloning+ * the matching source, then a No project draft opens with the playbook linked.+ * The draft hero explains the rest; the user picks a provider and describes+ * the problem.+ */+export function useStartTriage() {+ const router = useRouter();+ const { scratchWorkspaceRootFor } = useScratchProject();+ const handleNewThread = useNewThreadHandler();+ const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });+ const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });++ // With no draft to show, a toast is the only place to point at the CLI.+ const fail = (description: string) =>+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Could not start triage",+ description: `${description} Run ${TRIAGE_CLI_COMMAND} in a terminal on that machine instead.`,+ timeout: 0,+ actionProps: { children: "Copy command", onClick: () => void copyTriageCliCommand() },+ // "Copy command" is the copy that helps here, not the error text.+ data: { hideCopyButton: true },+ }),+ );+ const failWith = (+ result: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,+ ) => {+ if (isAtomCommandInterrupted(result)) return;+ const error = squashAtomCommandFailure(result);+ fail(error instanceof Error ? error.message : "An error occurred.");+ };++ // `routeChanged` tells the steps the user went elsewhere while they waited;+ // the draft then stays closed instead of pulling them away.+ const openTriageDraft = async (environmentId: EnvironmentId, routeChanged: () => boolean) => {+ const prepared = await prepare({+ environmentId,+ input: { client: currentClientMetadata() },+ });+ if (prepared._tag === "Failure") return failWith(prepared);+ const project = await openScratch({ environmentId, input: {} });+ if (project._tag === "Failure") return failWith(project);+ if (routeChanged()) return;+ // A null result means the user went elsewhere; only a throw is a failure.+ await handleNewThread(scopeProjectRef(project.value.environmentId, project.value.id), {+ prompt: prepared.value.prompt,+ }).catch(() => fail("T3 Code could not open a new thread."));+ };++ return async (environmentId: EnvironmentId) => {+ if (scratchWorkspaceRootFor(environmentId) === null) {+ fail("This machine cannot start threads without a project.");+ return;+ }+ const requestingRouteHref = router.state.location.href;+ // The palette is already closed, and a slow network can hold up the source+ // lookup, so say something when the draft does not open at once.+ let pendingToastId: ReturnType<typeof toastManager.add> | undefined;+ const pendingTimer = setTimeout(() => {+ pendingToastId = toastManager.add({+ type: "loading",+ title: "Starting triage…",+ timeout: 0,+ });+ }, 400);+ await openTriageDraft(+ environmentId,+ () => router.state.location.href !== requestingRouteHref,+ ).finally(() => {+ clearTimeout(pendingTimer);+ if (pendingToastId !== undefined) toastManager.close(pendingToastId);+ });+ };+}diff --git a/apps/web/src/lib/triageTarget.test.ts b/apps/web/src/lib/triageTarget.test.tsnew file mode 100644index 00000000000..52057314dbc--- /dev/null+++ b/apps/web/src/lib/triageTarget.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vite-plus/test";++import { pickTriageEnvironment } from "./triageTarget";++describe("pickTriageEnvironment", () => {+ it("skips a primary machine whose server lacks triage", () => {+ expect(+ pickTriageEnvironment({+ onScreen: null,+ primary: "old-primary",+ connected: ["old-primary", "new-remote"],+ supportsTriage: (environmentId) => environmentId === "new-remote",+ }),+ ).toBe("new-remote");+ });++ it("prefers a capable primary over other capable machines", () => {+ expect(+ pickTriageEnvironment({+ onScreen: null,+ primary: "primary",+ connected: ["remote", "primary"],+ supportsTriage: () => true,+ }),+ ).toBe("primary");+ });+});diff --git a/apps/web/src/lib/triageTarget.ts b/apps/web/src/lib/triageTarget.tsnew file mode 100644index 00000000000..e7233b5f11a--- /dev/null+++ b/apps/web/src/lib/triageTarget.ts@@ -0,0 +1,16 @@+/**+ * The machine triage runs on: the one on screen, else the primary if it+ * supports triage, else the first connected machine that does. Without No+ * project threads the action still shows and explains the terminal fallback,+ * so this does not check for them.+ */+export function pickTriageEnvironment<Id extends string>(input: {+ readonly onScreen: Id | null;+ readonly primary: Id | null;+ readonly connected: ReadonlyArray<Id>;+ readonly supportsTriage: (environmentId: Id) => boolean;+}): Id | null {+ if (input.onScreen !== null) return input.onScreen;+ if (input.primary !== null && input.supportsTriage(input.primary)) return input.primary;+ return input.connected.find(input.supportsTriage) ?? null;+}diff --git a/docs/README.md b/docs/README.mdindex 33f53eb0054..af3c45ce567 100644--- a/docs/README.md+++ b/docs/README.md@@ -24,6 +24,7 @@- [Outside agents (MCP)](./user/outside-agents.md)- [Running in the background](./user/background-service.md)- [Updating T3 Code](./user/updating.md)+- [Triage an issue](./user/triage.md)- Provider guides: [Codex](./user/providers-codex.md) · [Claude](./user/providers-claude.md) · [OpenCode](./user/providers-opencode.md) · [Antigravity](./user/providers-antigravity.md) · [Pi](./user/providers-pi.md) · [Muse Code](./user/providers-muse.md) · [fx](./user/providers-fx.md)---diff --git a/docs/user/triage.md b/docs/user/triage.mdnew file mode 100644index 00000000000..c66bac0738e--- /dev/null+++ b/docs/user/triage.md@@ -0,0 +1,29 @@+# Triage an issue++Triage lets your own coding agent investigate a T3 Code problem. The agent+reads the logs and state of the machine, checks the T3 Code source for that+version, finds known issues, and can help you write a good GitHub issue. It asks+before it applies a fix or posts anything.++## In the app++Open the command palette and choose **Triage an issue**. A new thread with no+project opens, with the triage playbook linked in the message. Choose any+provider, describe what went wrong after the link, and send. T3 Code gets the+source for the server's version while you write.++Triage runs on the machine of the thread or draft that you have open. With+nothing open, it uses your primary machine if that supports triage, or else the+first connected machine that does. The new thread shows the machine name, and on+mobile the palette row shows it before you start. The agent runs inside that T3+Code server, so it gives you any restart steps and does not do them itself.++## In a terminal++If the app does not start, or triage does not work in the app, run:++```sh+npx t3 triage+```++It starts Claude Code or Codex in your terminal with the same instructions.diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 77db29b9e94..6b77c2a185f 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -1154,6 +1154,11 @@ export function createServerEnvironmentAtoms<R, E>(tag: WS_METHODS.serverRunStorageCleanup,concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },}),+ prepareTriage: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:prepare-triage",+ tag: WS_METHODS.serverPrepareTriage,+ concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },+ }),databaseStorage,databaseCompactionRecommendations,storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.tsindex b2d66d902e1..af940776004 100644--- a/packages/contracts/src/clientRpcPermissions.ts+++ b/packages/contracts/src/clientRpcPermissions.ts@@ -47,6 +47,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {[WS_METHODS.vcsSwitchRef]: AuthSourceControlWriteScope,[WS_METHODS.vcsInit]: AuthSourceControlWriteScope,+ // Starts an agent session on this environment that can read its logs and database.+ [WS_METHODS.serverPrepareTriage]: AuthOrchestrationOperateScope,[WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope,[WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope,[WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope,diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 0cd36339bca..2caef71c14d 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -148,6 +148,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({(`linkOrigin`). Another environment links to this one only when it isset, since without it that work could change the user's own threads. */linkFence: Schema.optionalKey(Schema.Boolean),+ /** Server answers server.prepareTriage. */+ triage: Schema.optionalKey(Schema.Boolean),});export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 8a9a32cc5f9..00b8bcced3b 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -313,6 +313,9 @@ import {ServerConfigStreamEvent,DesktopUpdateCommitInput,OtlpEndpointCheckInput,+ ServerPrepareTriageError,+ ServerPrepareTriageInput,+ ServerPrepareTriageResult,OtlpEndpointCheckResult,ServerConfig,ServerProviderUpdateError,@@ -524,6 +527,7 @@ export const WS_METHODS = {serverGetResourceTelemetryHistory: "server.getResourceTelemetryHistory",serverRetryResourceTelemetry: "server.retryResourceTelemetry",serverCheckOtlpEndpoint: "server.checkOtlpEndpoint",+ serverPrepareTriage: "server.prepareTriage",serverSignalProcess: "server.signalProcess",serverReportClientActivity: "server.reportClientActivity",serverReportHostPowerState: "server.reportHostPowerState",@@ -946,6 +950,12 @@ const WsServerCheckOtlpEndpointRpc = Rpc.make(WS_METHODS.serverCheckOtlpEndpointerror: EnvironmentAuthorizationError,});+const WsServerPrepareTriageRpc = Rpc.make(WS_METHODS.serverPrepareTriage, {+ payload: ServerPrepareTriageInput,+ success: ServerPrepareTriageResult,+ error: Schema.Union([ServerPrepareTriageError, EnvironmentAuthorizationError]),+});+const WsServerGetUsageSummaryRpc = Rpc.make(WS_METHODS.serverGetUsageSummary, {payload: UsageSummaryInput,success: UsageSummary,@@ -2013,6 +2023,7 @@ export const WsRpcGroup = RpcGroup.make(WsServerGetResourceTelemetryHistoryRpc,WsServerRetryResourceTelemetryRpc,WsServerCheckOtlpEndpointRpc,+ WsServerPrepareTriageRpc,WsServerGetUsageSummaryRpc,WsServerRefreshUsageRatesRpc,WsServerSignalProcessRpc,diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.tsindex c14b4b4b24e..ed037c2c6b5 100644--- a/packages/contracts/src/server.ts+++ b/packages/contracts/src/server.ts@@ -6,7 +6,7 @@ import {ExecutionEnvironmentDescriptor,ServerSelfUpdateMethod,} from "./environment.ts";-import { ServerAuthDescriptor } from "./auth.ts";+import { AuthClientPresentationMetadata, ServerAuthDescriptor } from "./auth.ts";import {ForwardCompatibleArray,IsoDateTime,@@ -314,6 +314,33 @@ export const OtlpEndpointCheckResult = Schema.Union([]);export type OtlpEndpointCheckResult = typeof OtlpEndpointCheckResult.Type;+/** The client tells the server what it is, so the triage context can name it. */+export const ServerPrepareTriageInput = Schema.Struct({+ client: AuthClientPresentationMetadata,+});+export type ServerPrepareTriageInput = typeof ServerPrepareTriageInput.Type;++export const ServerPrepareTriageResult = Schema.Struct({+ /** Composer text that links the session's prompt file. */+ prompt: Schema.String,+});+export type ServerPrepareTriageResult = typeof ServerPrepareTriageResult.Type;++/**+ * The prompt file links as a chip in the user's message; clients spot a triage+ * draft by it.+ */+export const TRIAGE_PROMPT_FILE_NAME = "triage-playbook.md";++export class ServerPrepareTriageError extends Schema.TaggedError<ServerPrepareTriageError>()(+ "ServerPrepareTriageError",+ { cause: Schema.optional(Schema.Defect()) },+) {+ override get message(): string {+ return "Could not write the triage session files.";+ }+}+export const ServerTraceDiagnosticsErrorKind = Schema.Literals(["trace-file-not-found","trace-file-read-failed",