The best way to control Claude Code, Codex and more from any computer or phone
feat: triage an issue from the command palette, no terminal needed (#22753)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 27, 2026 at 16:42 UTC
7e884b2df619d5a41570736e9e251b88a87bc31f
36 files changed
+1324
-148
.github/triage/PLAYBOOK.md
+2
-2
@@ -11,8 +11,8 @@ provided alongside this playbook. Everything machine-specific lives there, not h
11
12
## 1. Ask what went wrong
13
14
-Your first message to the user: ask them to describe what went wrong, in their own
15
-words. Ask them to paste screenshots directly into this session if they have any.
14
+Unless the user already described it, your first message asks what went wrong, in
15
+their own words. Ask them to paste screenshots directly into this session if they have any.
16
Ask follow-up questions when the description is vague. Good repro steps are the most
17
valuable thing you can extract from this conversation.
18
apps/mobile/src/features/keyboard/CommandPalette.tsx
+42
-1
@@ -1,3 +1,4 @@
1
+import { useAtomValue } from "@effect/atom-react";
2
import { uuidv4 } from "../../lib/uuid";
3
import { useNavigation } from "@react-navigation/native";
4
import {
@@ -41,15 +42,25 @@ import { deriveBottomControlInsets } from "../../lib/reserved-regions";
42
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
43
import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
44
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
44
-import { useProjects, useThreadShell, useThreadShells } from "../../state/entities";
45
+import {
46
+ useProjects,
47
+ useServerConfigs,
48
+ useThreadShell,
49
+ useThreadShells,
50
+} from "../../state/entities";
51
import { useThreadSearch } from "../../state/queries";
52
import { requestThreadMessageJump } from "../threads/threadMessageJump";
53
import { threadEnvironment } from "../../state/threads";
54
import { useAtomCommand } from "../../state/use-atom-command";
55
+import { serverEnvironment } from "../../state/server";
56
import { useWorkspaceEnvironments } from "../../state/workspace";
57
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
58
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
59
import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";
60
+import { pickTriageEnvironment } from "../triage/triageTarget";
61
+import { useStartTriage } from "../triage/useStartTriage";
62
+import { useNewTaskFlow } from "../threads/new-task-flow-provider";
63
+import { useActiveNewTask } from "../../state/active-new-task";
64
import {
65
filterCommandPaletteItems,
66
nextPaletteIndex,
@@ -256,6 +267,22 @@ export function CommandPalette(props: {
267
query.startsWith(">") ? "" : query,
268
environmentLabels === undefined ? {} : { environmentLabels },
269
);
270
+ const serverConfigs = useServerConfigs();
271
+ const startTriage = useStartTriage();
272
+ const newTaskFlow = useNewTaskFlow();
273
+ const draftEnvironmentId =
274
+ useActiveNewTask() === null ? null : (newTaskFlow.selectedProject?.environmentId ?? null);
275
+ const triageEnvironmentId = pickTriageEnvironment({
276
+ // The route names the machine even before the thread shell loads.
277
+ onScreen: activeThreadRef?.environmentId ?? draftEnvironmentId,
278
+ connected: searchEnvironmentIds,
279
+ supportsTriage: (environmentId) =>
280
+ serverConfigs.get(environmentId)?.environment.capabilities.triage === true,
281
+ });
282
+ const canTriage =
283
+ useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) &&
284
+ triageEnvironmentId !== null &&
285
+ serverConfigs.get(triageEnvironmentId)?.environment.capabilities.triage === true;
286
const contentMatchByKey = useMemo(
287
() =>
288
new Map(
@@ -324,6 +351,17 @@ export function CommandPalette(props: {
351
run: () => openSettings(navigation, "SettingsArchive"),
352
},
353
];
354
+ if (canTriage) {
355
+ actions.push({
356
+ key: "triage",
357
+ kind: "action",
358
+ title: "Triage an issue",
359
+ // Mobile has no triage hero, so name the machine before it starts.
360
+ detail: `On ${savedConnectionsById[triageEnvironmentId]?.environmentLabel ?? "this machine"}`,
361
+ searchTerms: ["triage", "bug", "issue", "report", "broken", "debug", "help", "support"],
362
+ run: () => void startTriage(triageEnvironmentId),
363
+ });
364
+ }
365
const projectByKey = new Map(
366
projects.map((project) => [scopedProjectKey(project.environmentId, project.id), project]),
367
);
@@ -430,12 +468,15 @@ export function CommandPalette(props: {
468
activeThread,
469
activeThreadRef,
470
environments.length,
471
+ canTriage,
472
navigation,
473
projects,
474
runCommand,
475
savedConnectionsById,
476
selectDetail,
477
+ startTriage,
478
threads,
479
+ triageEnvironmentId,
480
]);
481
const rankedMessageKeys = useMemo(() => {
482
const subjectByKey = new Map(
apps/mobile/src/features/triage/triageTarget.test.ts
new
+25
@@ -0,0 +1,25 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { pickTriageEnvironment } from "./triageTarget";
4
+
5
+describe("pickTriageEnvironment", () => {
6
+ it("triages the machine on screen", () => {
7
+ expect(
8
+ pickTriageEnvironment({
9
+ onScreen: "laptop",
10
+ connected: ["desktop", "laptop"],
11
+ supportsTriage: () => true,
12
+ }),
13
+ ).toBe("laptop");
14
+ });
15
+
16
+ it("with nothing on screen, skips connected machines whose server lacks triage", () => {
17
+ expect(
18
+ pickTriageEnvironment({
19
+ onScreen: null,
20
+ connected: ["old-server", "new-server"],
21
+ supportsTriage: (environmentId) => environmentId === "new-server",
22
+ }),
23
+ ).toBe("new-server");
24
+ });
25
+});
apps/mobile/src/features/triage/triageTarget.ts
new
+11
@@ -0,0 +1,11 @@
1
+/**
2
+ * The machine triage runs on: the one on screen, else the first connected
3
+ * machine whose server supports triage. The palette row names the pick.
4
+ */
5
+export function pickTriageEnvironment<Id extends string>(input: {
6
+ readonly onScreen: Id | null;
7
+ readonly connected: ReadonlyArray<Id>;
8
+ readonly supportsTriage: (environmentId: Id) => boolean;
9
+}): Id | null {
10
+ return input.onScreen ?? input.connected.find(input.supportsTriage) ?? null;
11
+}
apps/mobile/src/features/triage/useStartTriage.ts
new
+106
@@ -0,0 +1,106 @@
1
+import {
2
+ isAtomCommandInterrupted,
3
+ squashAtomCommandFailure,
4
+} from "@t3tools/client-runtime/state/runtime";
5
+import type { EnvironmentId } from "@t3tools/contracts";
6
+import { useNavigation } from "@react-navigation/native";
7
+import * as Clipboard from "expo-clipboard";
8
+import Constants from "expo-constants";
9
+
10
+import * as Dialog from "../../components/ui/Dialog";
11
+import { authClientMetadata } from "../../lib/authClientMetadata";
12
+import { projectEnvironment } from "../../state/projects";
13
+import { serverEnvironment } from "../../state/server";
14
+import { useAtomCommand } from "../../state/use-atom-command";
15
+import {
16
+ createNewTaskDraft,
17
+ setComposerDraftText,
18
+ waitForComposerDraftsLoaded,
19
+} from "../../state/use-composer-drafts";
20
+import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
21
+
22
+const CLI_COMMAND = "npx t3 triage";
23
+
24
+/**
25
+ * In-app `t3 triage`, as on web: the server writes the session files and
26
+ * clones the matching source, then a No project draft opens with the prompt.
27
+ */
28
+export function useStartTriage() {
29
+ const navigation = useNavigation();
30
+ const selectDetail = useSelectWorkspaceDetail();
31
+ const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
32
+ const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
33
+
34
+ const fail = (message: string) =>
35
+ Dialog.alert(
36
+ "Could not start triage",
37
+ `${message} Run ${CLI_COMMAND} in a terminal on that machine instead.`,
38
+ [
39
+ {
40
+ text: "Copy command",
41
+ onPress: () =>
42
+ void Clipboard.setStringAsync(CLI_COMMAND).catch(() =>
43
+ Dialog.alert("Could not copy", `Type ${CLI_COMMAND} instead.`),
44
+ ),
45
+ },
46
+ { text: "OK", style: "cancel" },
47
+ ],
48
+ );
49
+ const errorMessage = (error: unknown, fallback: string) =>
50
+ error instanceof Error ? error.message : fallback;
51
+
52
+ const activeRoute = () => {
53
+ const state = navigation.getState();
54
+ return state?.routes[state.index];
55
+ };
56
+
57
+ return async (environmentId: EnvironmentId) => {
58
+ // If the user goes elsewhere while this waits, the draft stays closed
59
+ // instead of pulling them away. Split view changes params, not the route.
60
+ const startRoute = activeRoute();
61
+ const routeChanged = () => {
62
+ const route = activeRoute();
63
+ if (route === startRoute) return false;
64
+ if (route === undefined || startRoute === undefined) return true;
65
+ return route.key !== startRoute.key || route.params !== startRoute.params;
66
+ };
67
+ const scratch = await openScratch({ environmentId, input: {} });
68
+ if (scratch._tag === "Failure") {
69
+ if (!isAtomCommandInterrupted(scratch)) {
70
+ fail(
71
+ errorMessage(
72
+ squashAtomCommandFailure(scratch),
73
+ "This machine cannot start threads without a project.",
74
+ ),
75
+ );
76
+ }
77
+ return;
78
+ }
79
+ const prepared = await prepare({
80
+ environmentId,
81
+ input: { client: authClientMetadata(Constants.expoConfig?.version) },
82
+ });
83
+ if (prepared._tag === "Failure") {
84
+ if (!isAtomCommandInterrupted(prepared)) {
85
+ fail(errorMessage(squashAtomCommandFailure(prepared), "The server could not prepare it."));
86
+ }
87
+ return;
88
+ }
89
+ try {
90
+ await waitForComposerDraftsLoaded();
91
+ } catch {
92
+ fail("Drafts could not be loaded.");
93
+ return;
94
+ }
95
+ if (routeChanged()) return;
96
+ const draftId = createNewTaskDraft({
97
+ environmentId,
98
+ projectId: scratch.value.id,
99
+ });
100
+ setComposerDraftText(draftId, prepared.value.prompt);
101
+ selectDetail({
102
+ name: "Thread",
103
+ params: { draft: { environmentId, projectId: scratch.value.id, title: "Triage", draftId } },
104
+ });
105
+ };
106
+}
apps/server/src/auth/RpcAuthorization.test.ts
+6
@@ -43,6 +43,12 @@ describe("RPC authorization scopes", () => {
43
}
44
});
45
46
+ it("keeps triage, which seeds an agent that reads logs and the database, behind operate scope", () => {
47
+ expect(requiredScopeForRpcMethod(WS_METHODS.serverPrepareTriage)).toBe(
48
+ AuthOrchestrationOperateScope,
49
+ );
50
+ });
51
+
52
it("separates passive terminal observation from operations that can change a shell", () => {
53
for (const method of [
54
WS_METHODS.terminalObserve,
apps/server/src/cli/triage.ts
+13
-68
@@ -1,33 +1,23 @@
1
// @effect-diagnostics nodeBuiltinImport:off
2
import * as NodeChildProcess from "node:child_process";
3
-import * as NodeOS from "node:os";
3
import * as NodeReadlinePromises from "node:readline/promises";
4
6
-import * as HostProcess from "@t3tools/shared/HostProcess";
5
import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
6
import * as Config from "effect/Config";
7
import * as Console from "effect/Console";
10
-import * as DateTime from "effect/DateTime";
8
import * as Effect from "effect/Effect";
12
-import * as FileSystem from "effect/FileSystem";
9
import * as Option from "effect/Option";
14
-import * as Path from "effect/Path";
10
import * as Schema from "effect/Schema";
11
import { Command, Flag } from "effect/cli";
12
13
import packageJson from "../../package.json" with { type: "json" };
19
-import * as BootService from "../cloud/bootService.ts";
14
import * as ServerConfig from "../config.ts";
15
import { resolveBaseDir } from "../os-jank.ts";
22
-import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
16
+import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts";
17
+import { describeServerProcess, writeTriageSession } from "../triage/triageSession.ts";
18
import { baseDirFlag } from "./config.ts";
19
import { interactiveStdin } from "./consoleStdin.ts";
20
import { resolveCliCommand } from "./invocation.ts";
26
-import {
27
- buildTriageContext,
28
- buildTriageLaunchPrompt,
29
- buildTriageSeedPrompt,
30
-} from "./triagePrompt.ts";
21
22
interface TriageAgent {
23
readonly id: "claude" | "codex";
@@ -67,23 +57,6 @@ export class TriageAgentSpawnError extends Schema.TaggedError<TriageAgentSpawnEr
57
}
58
}
59
70
-export const describeServerProcess = Effect.fn("triage.describeServerProcess")(function* (
71
- serverRuntimeStatePath: string,
72
-) {
73
- const state = yield* readPersistedServerRuntimeState(serverRuntimeStatePath);
74
- if (Option.isNone(state)) {
75
- return "not running (no server-runtime.json; the server may never have started here)";
76
- }
77
- const version =
78
- state.value.serverVersion === undefined
79
- ? "version not recorded"
80
- : `version ${state.value.serverVersion}`;
81
- if (!isProcessAlive(state.value.pid)) {
82
- return `not running (state file is stale: pid ${String(state.value.pid)} is dead; last origin ${state.value.origin}, ${version})`;
83
- }
84
- return `running (pid ${String(state.value.pid)}, ${state.value.origin}, ${version})`;
85
-});
86
-
60
const pickAgent = (agents: ReadonlyArray<TriageAgent>) =>
61
Effect.promise(async () => {
62
const readline = NodeReadlinePromises.createInterface({
@@ -149,49 +122,22 @@ export const triageCommand = Command.make("triage", {
122
),
123
Command.withHandler((flags) =>
124
Effect.gen(function* () {
152
- const fs = yield* FileSystem.FileSystem;
153
- const path = yield* Path.Path;
154
-
125
// Triage is a user-facing feature: always the userdata state, never dev.
126
const explicitBaseDir = Option.getOrUndefined(flags.baseDir);
127
const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
128
const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome));
129
const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {});
130
161
- const now = yield* DateTime.now;
162
- const scratchDir = path.join(
163
- paths.stateDir,
164
- "triage",
165
- DateTime.formatIso(now).replaceAll(":", "-").replace(".", "-"),
166
- );
167
- yield* fs.makeDirectory(scratchDir, { recursive: true });
168
-
169
- const contextFilePath = path.join(scratchDir, "context.md");
170
- yield* fs.writeFileString(
171
- contextFilePath,
172
- buildTriageContext({
173
- generatedAt: DateTime.formatIso(now),
131
+ const session = yield* writeTriageSession({
132
+ baseDir,
133
+ paths,
134
+ entry: {
135
+ kind: "cli",
136
cliVersion: packageJson.version,
175
- os: `${yield* HostProcess.Platform} ${yield* HostProcess.Architecture} (${NodeOS.release()})`,
176
- nodeVersion: process.version,
137
launchedAs: yield* resolveCliCommand("triage"),
178
- server: yield* describeServerProcess(paths.serverRuntimeStatePath),
179
- paths: {
180
- stateDir: paths.stateDir,
181
- dbPath: paths.dbPath,
182
- settingsPath: paths.settingsPath,
183
- logsDir: paths.logsDir,
184
- serviceLogPath: path.join(paths.logsDir, BootService.BOOT_SERVICE_LOG_FILE),
185
- desktopBackendLogGlob: path.join(paths.logsDir, "server-child*.log*"),
186
- serverTracePath: paths.serverTracePath,
187
- providerEventLogPath: paths.providerEventLogPath,
188
- terminalLogsDir: paths.terminalLogsDir,
189
- providerStatusCacheDir: paths.providerStatusCacheDir,
190
- secretsDir: paths.secretsDir,
191
- sourceCacheDir: path.join(baseDir, "source"),
192
- },
193
- }),
194
- );
138
+ },
139
+ server: yield* describeServerProcess(paths.serverRuntimeStatePath),
140
+ });
141
142
const installed: Array<TriageAgent> = [];
143
for (const agent of TRIAGE_AGENTS) {
@@ -217,9 +163,8 @@ export const triageCommand = Command.make("triage", {
163
selected = yield* pickAgent(installed);
164
}
165
220
- // Windows .cmd shims cannot carry multiline argv; keep the playbook on disk for both launch and paste fallback.
221
- const promptFilePath = path.join(scratchDir, "prompt.md");
222
- yield* fs.writeFileString(promptFilePath, buildTriageSeedPrompt(contextFilePath));
166
+ // Windows .cmd shims cannot carry multiline argv; the prompt file also serves as the paste fallback.
167
+ const { sessionDir, promptFilePath, contextFilePath } = session;
168
169
if (selected === undefined) {
170
yield* Console.log(
@@ -242,7 +187,7 @@ export const triageCommand = Command.make("triage", {
187
buildTriageLaunchPrompt(promptFilePath),
188
]);
189
yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`);
245
- const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: scratchDir });
190
+ const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: sessionDir });
191
if (exitCode !== 0) {
192
process.exitCode = exitCode;
193
}
apps/server/src/cli/triagePrompt.test.ts
deleted
-53
@@ -1,53 +0,0 @@
1
-// @effect-diagnostics nodeBuiltinImport:off
2
-import * as NodeFS from "node:fs";
3
-import * as NodePath from "node:path";
4
-
5
-import { assert, it } from "@effect/vitest";
6
-
7
-import { buildTriageContext, buildTriageLaunchPrompt, TRIAGE_PLAYBOOK } from "./triagePrompt.ts";
8
-
9
-it("stays byte-identical to .github/triage/PLAYBOOK.md", () => {
10
- // Older releases fetch the repository playbook.
11
- const canonicalPath = NodePath.join(
12
- import.meta.dirname,
13
- "../../../../.github/triage/PLAYBOOK.md",
14
- );
15
- assert.equal(TRIAGE_PLAYBOOK, NodeFS.readFileSync(canonicalPath, "utf8"));
16
-});
17
-
18
-it("launch prompt stays a single argv-safe line naming the prompt file", () => {
19
- // Windows .cmd shims cannot carry multiline argv.
20
- const launch = buildTriageLaunchPrompt(String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);
21
- assert.notInclude(launch, "\n");
22
- assert.include(launch, String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);
23
- assert.isBelow(launch.length, 1_000);
24
-});
25
-
26
-it("context file labels the CLI version as the CLI's, not the user's build", () => {
27
- const context = buildTriageContext({
28
- generatedAt: "2026-09-24T00:00:00.000Z",
29
- cliVersion: "0.0.42",
30
- os: "linux x64 (7.2.0)",
31
- nodeVersion: "v26.8.2",
32
- launchedAs: "npx t3 triage",
33
- server: "running (pid 42, http://127.0.0.1:3773, version 0.0.43-nightly.20260923.2173)",
34
- paths: {
35
- stateDir: "/home/u/.t3/userdata",
36
- dbPath: "/home/u/.t3/userdata/state.sqlite",
37
- settingsPath: "/home/u/.t3/userdata/settings.json",
38
- logsDir: "/home/u/.t3/userdata/logs",
39
- serviceLogPath: "/home/u/.t3/userdata/logs/boot-service.log",
40
- desktopBackendLogGlob: "/home/u/.t3/userdata/logs/server-child*.log*",
41
- serverTracePath: "/home/u/.t3/userdata/logs/server.trace.ndjson",
42
- providerEventLogPath: "/home/u/.t3/userdata/logs/provider/events.log",
43
- terminalLogsDir: "/home/u/.t3/userdata/logs/terminals",
44
- providerStatusCacheDir: "/home/u/.t3/caches",
45
- secretsDir: "/home/u/.t3/userdata/secrets",
46
- sourceCacheDir: "/home/u/.t3/source",
47
- },
48
- });
49
- assert.notInclude(context, "Installed version");
50
- assert.notInclude(context, "Release tag");
51
- assert.include(context, "- Triage CLI version: 0.0.42 (");
52
- assert.include(context, "version 0.0.43-nightly.20260923.2173");
53
-});
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -259,6 +259,7 @@ export const make = Effect.gen(function* () {
259
environmentIcon: true,
260
projectCloneTracking: true,
261
ignoredFileListing: true,
262
+ triage: true,
263
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
264
...(serverInstallation === null ? {} : { serverInstallation }),
265
...(serverSelfUpdate === "boot-service" || desktopAppUpdate
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -83,6 +83,7 @@ const RPC_AGGREGATES = {
83
[WS_METHODS.serverGetResourceTelemetryHistory]: "server",
84
[WS_METHODS.serverRetryResourceTelemetry]: "server",
85
[WS_METHODS.serverCheckOtlpEndpoint]: "server",
86
+ [WS_METHODS.serverPrepareTriage]: "server",
87
[WS_METHODS.serverGetUsageSummary]: "server",
88
[WS_METHODS.serverRefreshUsageRates]: "server",
89
[WS_METHODS.serverSignalProcess]: "server",
apps/server/src/server.ts
+2
@@ -170,6 +170,7 @@ import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
170
import * as HostResources from "./resourceTelemetry/HostResources.ts";
171
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
172
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
173
+import * as TriageService from "./triage/TriageService.ts";
174
import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
175
import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
176
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
@@ -693,6 +694,7 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe(
694
Layer.provideMerge(layerBackground),
695
Layer.provideMerge(layerResourceDiagnostics),
696
Layer.provideMerge(TraceDiagnostics.layer),
697
+ Layer.provideMerge(TriageService.layer.pipe(Layer.provide(GitVcsDriver.layer))),
698
Layer.provideMerge(AnalyticsService.layer),
699
Layer.provideMerge(ExternalLauncher.layer),
700
Layer.provideMerge(RemoteOpenTargets.layer),
apps/server/src/testUtils/shardWeights.json
+1
-1
@@ -17,7 +17,6 @@
17
"src/cli/service.test.ts": 0.5,
18
"src/cli/theme.test.ts": 2.1,
19
"src/cli/trace.test.ts": 1.2,
20
- "src/cli/triage.test.ts": 0.5,
20
"src/cli/uninstall.test.ts": 0.5,
21
"src/cli/update.test.ts": 1.7,
22
"src/cloud/CliTokenManager.test.ts": 0.7,
@@ -203,6 +202,7 @@
202
"src/textGeneration/OpenCode2TextGeneration.test.ts": 1.4,
203
"src/textGeneration/TextGeneration.test.ts": 1.2,
204
"src/textGeneration/ThreadTitleLinks.test.ts": 0.5,
205
+ "src/triage/triageSession.test.ts": 0.5,
206
"src/usage/UsageLimitSources.test.ts": 0.6,
207
"src/usage/UsageService.test.ts": 2.2,
208
"src/usage/cliproxyApi.test.ts": 0.5,
apps/server/src/triage/TriageService.test.ts
new
+162
@@ -0,0 +1,162 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { GitCommandError } from "@t3tools/contracts";
3
+import { assert, it } from "@effect/vitest";
4
+import * as Context from "effect/Context";
5
+import * as Effect from "effect/Effect";
6
+import * as FileSystem from "effect/FileSystem";
7
+import * as Layer from "effect/Layer";
8
+import * as Queue from "effect/Queue";
9
+import { ChildProcessSpawner } from "effect/process";
10
+
11
+import packageJson from "../../package.json" with { type: "json" };
12
+import * as ServerConfig from "../config.ts";
13
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
14
+import * as VcsProcess from "../vcs/VcsProcess.ts";
15
+import * as TriageService from "./TriageService.ts";
16
+import { pickSourceRef } from "./TriageService.ts";
17
+
18
+const MAIN = "a1dc856ee61278d0199c36d4bcdef5fdea4d21fe\trefs/heads/main";
19
+
20
+it("clones the server's release tag, peeling annotated tags to their commit", () => {
21
+ assert.deepEqual(pickSourceRef(`${MAIN}\n7027b1f\trefs/tags/v0.1.1\n`, "0.1.1"), {
22
+ ref: "v0.1.1",
23
+ commit: "7027b1f",
24
+ });
25
+ assert.deepEqual(
26
+ pickSourceRef(`${MAIN}\n1111111\trefs/tags/v0.1.1\n2222222\trefs/tags/v0.1.1^{}\n`, "0.1.1"),
27
+ { ref: "v0.1.1", commit: "2222222" },
28
+ );
29
+});
30
+
31
+it("falls back to main when the server's version has no tag", () => {
32
+ assert.deepEqual(pickSourceRef(`${MAIN}\n`, "0.1.2-dev"), {
33
+ ref: "main",
34
+ commit: "a1dc856ee61278d0199c36d4bcdef5fdea4d21fe",
35
+ });
36
+ assert.isUndefined(pickSourceRef("", "0.1.1"));
37
+});
38
+
39
+const TestLayer = GitVcsDriver.layer.pipe(
40
+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-triage-service-" })),
41
+ Layer.provideMerge(VcsProcess.layer),
42
+ Layer.provideMerge(NodeServices.layer),
43
+);
44
+
45
+const RELEASE_COMMIT = "7027b1f";
46
+
47
+/** The service over a stub git that answers each command with `answer`. */
48
+const makeTriage = (
49
+ answer: (command: string) => Effect.Effect<string, GitCommandError> = (command) =>
50
+ Effect.succeed(
51
+ command === "ls-remote"
52
+ ? `${RELEASE_COMMIT}\trefs/tags/v${packageJson.version}\n`
53
+ : command === "rev-parse"
54
+ ? `${RELEASE_COMMIT}\n`
55
+ : "",
56
+ ),
57
+) =>
58
+ Effect.gen(function* () {
59
+ const git = yield* GitVcsDriver.GitVcsDriver;
60
+ const commands: string[] = [];
61
+ const triage = yield* Layer.build(TriageService.layer).pipe(
62
+ Effect.map(Context.get(TriageService.TriageService)),
63
+ Effect.provideService(GitVcsDriver.GitVcsDriver, {
64
+ ...git,
65
+ execute: (input) => {
66
+ const command = input.args[0] ?? "";
67
+ commands.push(command);
68
+ return answer(command).pipe(
69
+ Effect.map((stdout) => ({
70
+ exitCode: ChildProcessSpawner.ExitCode(0),
71
+ stdout,
72
+ stderr: "",
73
+ stdoutTruncated: false,
74
+ stderrTruncated: false,
75
+ })),
76
+ );
77
+ },
78
+ }),
79
+ );
80
+ return { triage, commands };
81
+ });
82
+
83
+const readContext = Effect.gen(function* () {
84
+ const fs = yield* FileSystem.FileSystem;
85
+ const config = yield* ServerConfig.ServerConfig;
86
+ const sessions = `${config.stateDir}/triage`;
87
+ const [session] = yield* fs.readDirectory(sessions);
88
+ return yield* fs.readFileString(`${sessions}/${session}/context.md`);
89
+});
90
+
91
+it.effect("sessions started during a clone share it, and a release tag is looked up once", () =>
92
+ Effect.gen(function* () {
93
+ const fetches = yield* Queue.unbounded<void>();
94
+ const { triage, commands } = yield* makeTriage((command) =>
95
+ command === "fetch"
96
+ ? Queue.offer(fetches, undefined).pipe(Effect.andThen(Effect.never))
97
+ : Effect.succeed(
98
+ command === "ls-remote" ? `${RELEASE_COMMIT}\trefs/tags/v${packageJson.version}\n` : "",
99
+ ),
100
+ );
101
+
102
+ yield* triage.prepare({ client: {} });
103
+ yield* triage.prepare({ client: {} });
104
+ yield* Queue.take(fetches);
105
+
106
+ assert.deepEqual(
107
+ commands.filter((command) => command === "ls-remote" || command === "init"),
108
+ ["ls-remote", "init"],
109
+ );
110
+ }).pipe(Effect.provide(TestLayer)),
111
+);
112
+
113
+it.effect("reuses a finished clone without fetching", () =>
114
+ Effect.gen(function* () {
115
+ const fs = yield* FileSystem.FileSystem;
116
+ const config = yield* ServerConfig.ServerConfig;
117
+ yield* fs.makeDirectory(`${config.baseDir}/source/${RELEASE_COMMIT}/.git`, {
118
+ recursive: true,
119
+ });
120
+ const { triage, commands } = yield* makeTriage();
121
+
122
+ yield* triage.prepare({ client: {} });
123
+
124
+ assert.deepEqual(commands, ["ls-remote", "rev-parse"]);
125
+ assert.include(yield* readContext, "The server cloned the source for its own version");
126
+ }).pipe(Effect.provide(TestLayer)),
127
+);
128
+
129
+it.effect("still starts triage when the source lookup fails", () =>
130
+ Effect.gen(function* () {
131
+ const { triage } = yield* makeTriage(() =>
132
+ Effect.fail(
133
+ new GitCommandError({
134
+ operation: "TriageService.resolveSourceRef",
135
+ command: "git ls-remote",
136
+ cwd: "/",
137
+ detail: "Could not resolve host: github.com",
138
+ }),
139
+ ),
140
+ );
141
+
142
+ const { prompt } = yield* triage.prepare({ client: {} });
143
+
144
+ assert.include(prompt, "triage-playbook.md");
145
+ assert.include(yield* readContext, "Could not resolve host: github.com");
146
+ }).pipe(Effect.provide(TestLayer)),
147
+);
148
+
149
+it.effect("does not trust a folder without its own .git, even inside a repo at that commit", () =>
150
+ Effect.gen(function* () {
151
+ const fs = yield* FileSystem.FileSystem;
152
+ const config = yield* ServerConfig.ServerConfig;
153
+ yield* fs.makeDirectory(`${config.baseDir}/source/${RELEASE_COMMIT}`, { recursive: true });
154
+ // The stub answers rev-parse with the commit, as a parent repository could.
155
+ const { triage, commands } = yield* makeTriage();
156
+
157
+ yield* triage.prepare({ client: {} });
158
+
159
+ assert.notInclude(commands, "rev-parse");
160
+ assert.include(yield* readContext, "is not a complete checkout");
161
+ }).pipe(Effect.provide(TestLayer)),
162
+);
apps/server/src/triage/TriageService.ts
new
+216
@@ -0,0 +1,216 @@
1
+import {
2
+ type AuthClientPresentationMetadata,
3
+ ServerPrepareTriageError,
4
+ type ServerPrepareTriageInput,
5
+ type ServerPrepareTriageResult,
6
+} from "@t3tools/contracts";
7
+import * as Context from "effect/Context";
8
+import * as Effect from "effect/Effect";
9
+import * as FileSystem from "effect/FileSystem";
10
+import * as Layer from "effect/Layer";
11
+import * as Path from "effect/Path";
12
+
13
+import packageJson from "../../package.json" with { type: "json" };
14
+import * as ServerConfig from "../config.ts";
15
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
16
+import { buildTriageAppPrompt, type TriageSourceClone } from "./triagePrompt.ts";
17
+import { triageSourceCacheDir, writeTriageSession } from "./triageSession.ts";
18
+
19
+const T3CODE_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
20
+
21
+// No tty: a credential prompt would hang until the timeout, so git must fail
22
+// instead. An empty GIT_ASKPASS also skips core.askPass and SSH_ASKPASS helpers.
23
+const GIT_ENV = {
24
+ GIT_TERMINAL_PROMPT: "0",
25
+ GIT_ASKPASS: "",
26
+ LC_ALL: "C",
27
+} satisfies NodeJS.ProcessEnv;
28
+
29
+/** Starts in-app triage sessions: the same files `t3 triage` writes, plus a source clone. */
30
+export class TriageService extends Context.Service<
31
+ TriageService,
32
+ {
33
+ readonly prepare: (
34
+ input: ServerPrepareTriageInput,
35
+ ) => Effect.Effect<ServerPrepareTriageResult, ServerPrepareTriageError>;
36
+ }
37
+>()("t3/triage/TriageService") {}
38
+
39
+const describeClient = (client: AuthClientPresentationMetadata) =>
40
+ [
41
+ client.label ?? "an unknown client",
42
+ client.appVersion === undefined ? undefined : `version ${client.appVersion}`,
43
+ client.os === undefined ? undefined : `on ${client.os}`,
44
+ client.browser === undefined ? undefined : `in ${client.browser}`,
45
+ client.webDeployment === "hosted" ? "(app.t3.codes)" : undefined,
46
+ ]
47
+ .filter((part) => part !== undefined)
48
+ .join(" ");
49
+
50
+/** Picks the release tag for `version`, or `main` when the build has no tag. */
51
+export const pickSourceRef = (lsRemoteOutput: string, version: string) => {
52
+ const commits = new Map(
53
+ lsRemoteOutput
54
+ .split("\n")
55
+ .map((line) => line.trim().split("\t"))
56
+ .filter((fields): fields is [string, string] => fields.length === 2)
57
+ .map(([commit, ref]) => [ref, commit]),
58
+ );
59
+ const tag = `v${version}`;
60
+ // Annotated tags list the tag object first and the commit as `^{}`.
61
+ const tagCommit = commits.get(`refs/tags/${tag}^{}`) ?? commits.get(`refs/tags/${tag}`);
62
+ if (tagCommit !== undefined) return { ref: tag, commit: tagCommit };
63
+ const mainCommit = commits.get("refs/heads/main");
64
+ return mainCommit === undefined ? undefined : { ref: "main", commit: mainCommit };
65
+};
66
+
67
+const make = Effect.gen(function* () {
68
+ const config = yield* ServerConfig.ServerConfig;
69
+ const git = yield* GitVcsDriver.GitVcsDriver;
70
+ const fs = yield* FileSystem.FileSystem;
71
+ const path = yield* Path.Path;
72
+ const sourceDir = triageSourceCacheDir(config.baseDir, path);
73
+ // Beside the cache, not in it: the playbook has agents prune the cache, and a
74
+ // clone in progress must not look like a stale entry. Same filesystem, so the
75
+ // finished clone moves in with a rename.
76
+ const stagingDir = `${sourceDir}-staging`;
77
+ const serverVersion = packageJson.version;
78
+
79
+ const runGit = (operation: string, cwd: string, args: ReadonlyArray<string>, timeoutMs: number) =>
80
+ git.execute({ operation: `TriageService.${operation}`, cwd, args, timeoutMs, env: GIT_ENV });
81
+
82
+ // Clones outlive the request that started them: a fresh clone takes tens of
83
+ // seconds, and the user is writing their description meanwhile.
84
+ const serviceScope = yield* Effect.scope;
85
+ // Clones a previous server process left half done.
86
+ yield* fs.remove(stagingDir, { recursive: true }).pipe(Effect.ignore);
87
+
88
+ // Fetches the exact commit `ls-remote` resolved, so the folder the session
89
+ // names is the one that appears even when main moves meanwhile.
90
+ const cloneSource = Effect.fn("TriageService.cloneSource")(function* (commit: string) {
91
+ yield* fs.makeDirectory(stagingDir, { recursive: true });
92
+ const staging = yield* fs.makeTempDirectory({ directory: stagingDir, prefix: "clone-" });
93
+ const directory = path.join(sourceDir, commit);
94
+ yield* Effect.gen(function* () {
95
+ yield* runGit("initSource", staging, ["init", "--quiet"], 10_000);
96
+ yield* runGit(
97
+ "addSourceRemote",
98
+ staging,
99
+ ["remote", "add", "origin", T3CODE_REPOSITORY_URL],
100
+ 10_000,
101
+ );
102
+ yield* runGit(
103
+ "fetchSource",
104
+ staging,
105
+ ["fetch", "--depth", "1", "--filter=blob:none", "origin", commit],
106
+ 600_000,
107
+ );
108
+ yield* runGit("checkoutSource", staging, ["checkout", "--quiet", "FETCH_HEAD"], 600_000);
109
+ yield* fs.rename(staging, directory).pipe(
110
+ // A concurrent session cloned the same commit first; keep theirs.
111
+ Effect.catch((error) =>
112
+ fs
113
+ .exists(directory)
114
+ .pipe(Effect.flatMap((exists) => (exists ? Effect.void : Effect.fail(error)))),
115
+ ),
116
+ );
117
+ }).pipe(
118
+ // Gone after a successful rename; otherwise a failed or losing clone.
119
+ Effect.ensuring(fs.remove(staging, { recursive: true }).pipe(Effect.ignore)),
120
+ );
121
+ });
122
+
123
+ // Release tags never move, so one lookup serves every later session. Builds
124
+ // with no tag track main, which does move, so they look it up each time.
125
+ let releaseSource: { readonly ref: string; readonly commit: string } | undefined;
126
+ const resolveSource = Effect.fn("TriageService.resolveSource")(function* () {
127
+ if (releaseSource !== undefined) return releaseSource;
128
+ const tag = `refs/tags/v${serverVersion}`;
129
+ const listed = yield* runGit(
130
+ "resolveSourceRef",
131
+ sourceDir,
132
+ ["ls-remote", T3CODE_REPOSITORY_URL, tag, `${tag}^{}`, "refs/heads/main"],
133
+ // Triage still starts without source; a dead network should not stall it.
134
+ 5_000,
135
+ );
136
+ const source = pickSourceRef(listed.stdout, serverVersion);
137
+ if (source?.ref !== "main") releaseSource = source;
138
+ return source;
139
+ });
140
+
141
+ // Commits with a clone running, so sessions started meanwhile share it.
142
+ const cloning = new Set<string>();
143
+
144
+ // The playbook's own layout: one folder per commit under the source cache, so
145
+ // the agent finds and reuses this clone instead of making another. The folder
146
+ // appears only once the clone is complete.
147
+ const startSourceClone = Effect.fn("TriageService.startSourceClone")(function* () {
148
+ yield* fs.makeDirectory(sourceDir, { recursive: true });
149
+ const source = yield* resolveSource();
150
+ if (source === undefined) {
151
+ return {
152
+ _tag: "failed",
153
+ serverVersion,
154
+ reason: "the repository listed neither the release tag nor main.",
155
+ } satisfies TriageSourceClone;
156
+ }
157
+ const directory = path.join(sourceDir, source.commit);
158
+ if (yield* fs.exists(directory)) {
159
+ // Our clones appear only when complete, but an agent may have cloned
160
+ // here by hand and stopped partway.
161
+ // Without its own .git, rev-parse would read a parent repository.
162
+ const head = (yield* fs.exists(path.join(directory, ".git")))
163
+ ? yield* runGit("checkSource", directory, ["rev-parse", "HEAD"], 10_000).pipe(
164
+ Effect.map((result) => result.stdout.trim()),
165
+ Effect.orElseSucceed(() => ""),
166
+ )
167
+ : "";
168
+ return head === source.commit
169
+ ? ({ _tag: "cloned", directory, serverVersion, ...source } as const)
170
+ : ({
171
+ _tag: "failed",
172
+ serverVersion,
173
+ reason: `${directory} exists but is not a complete checkout of ${source.commit}. Remove it first.`,
174
+ } satisfies TriageSourceClone);
175
+ }
176
+ if (!cloning.has(source.commit)) {
177
+ cloning.add(source.commit);
178
+ yield* cloneSource(source.commit).pipe(
179
+ Effect.ignoreCause({ log: true }),
180
+ Effect.ensuring(Effect.sync(() => cloning.delete(source.commit))),
181
+ Effect.forkIn(serviceScope),
182
+ );
183
+ }
184
+ return { _tag: "cloning", directory, serverVersion, ...source } as const;
185
+ });
186
+
187
+ const prepare: TriageService["Service"]["prepare"] = Effect.fn("TriageService.prepare")(
188
+ function* (input) {
189
+ const sourceClone = yield* startSourceClone().pipe(
190
+ Effect.catch((error) =>
191
+ Effect.succeed<TriageSourceClone>({
192
+ _tag: "failed",
193
+ serverVersion,
194
+ reason: error.message,
195
+ }),
196
+ ),
197
+ );
198
+ const session = yield* writeTriageSession({
199
+ baseDir: config.baseDir,
200
+ paths: config,
201
+ entry: { kind: "app", client: describeClient(input.client) },
202
+ server: `running (pid ${String(process.pid)}, version ${serverVersion}); this session runs inside it`,
203
+ sourceClone,
204
+ }).pipe(
205
+ Effect.provideService(FileSystem.FileSystem, fs),
206
+ Effect.provideService(Path.Path, path),
207
+ Effect.mapError((cause) => new ServerPrepareTriageError({ cause })),
208
+ );
209
+ return { prompt: buildTriageAppPrompt(session.promptFilePath) };
210
+ },
211
+ );
212
+
213
+ return TriageService.of({ prepare });
214
+});
215
+
216
+export const layer = Layer.effect(TriageService, make);
apps/server/src/triage/triagePrompt.test.ts
new
+82
@@ -0,0 +1,82 @@
1
+// @effect-diagnostics nodeBuiltinImport:off
2
+import * as NodeFS from "node:fs";
3
+import * as NodePath from "node:path";
4
+
5
+import { assert, it } from "@effect/vitest";
6
+
7
+import {
8
+ buildTriageContext,
9
+ buildTriageLaunchPrompt,
10
+ type TriageContextInput,
11
+ TRIAGE_PLAYBOOK,
12
+} from "./triagePrompt.ts";
13
+
14
+it("stays byte-identical to .github/triage/PLAYBOOK.md", () => {
15
+ // Older releases fetch the repository playbook.
16
+ const canonicalPath = NodePath.join(
17
+ import.meta.dirname,
18
+ "../../../../.github/triage/PLAYBOOK.md",
19
+ );
20
+ assert.equal(TRIAGE_PLAYBOOK, NodeFS.readFileSync(canonicalPath, "utf8"));
21
+});
22
+
23
+it("launch prompt stays a single argv-safe line naming the prompt file", () => {
24
+ // Windows .cmd shims cannot carry multiline argv.
25
+ const launch = buildTriageLaunchPrompt(String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);
26
+ assert.notInclude(launch, "\n");
27
+ assert.include(launch, String.raw`C:\Users\a b\.t3\userdata\triage\x\prompt.md`);
28
+ assert.isBelow(launch.length, 1_000);
29
+});
30
+
31
+it("context file labels the CLI version as the CLI's, not the user's build", () => {
32
+ const context = buildTriageContext({
33
+ ...contextInput,
34
+ entry: { kind: "cli", cliVersion: "0.0.42", launchedAs: "npx t3 triage" },
35
+ server: "running (pid 42, http://127.0.0.1:3773, version 0.0.43-nightly.20260923.2173)",
36
+ });
37
+ assert.notInclude(context, "Installed version");
38
+ assert.notInclude(context, "Release tag");
39
+ assert.include(context, "- Triage CLI version: 0.0.42 (");
40
+ assert.include(context, "version 0.0.43-nightly.20260923.2173");
41
+ assert.notInclude(context, "runs inside T3 Code");
42
+});
43
+
44
+it("in-app context warns the agent off its own server and points at the clone in progress", () => {
45
+ const context = buildTriageContext({
46
+ ...contextInput,
47
+ entry: { kind: "app", client: "T3 Code Desktop version 0.1.1 on macos" },
48
+ server: "running (pid 42, version 0.1.1); this session runs inside it",
49
+ sourceClone: {
50
+ _tag: "cloning",
51
+ directory: "/home/u/.t3/source/abc123",
52
+ ref: "v0.1.1",
53
+ commit: "abc123",
54
+ serverVersion: "0.1.1",
55
+ },
56
+ });
57
+ assert.notInclude(context, "Triage CLI version");
58
+ assert.include(context, "- Started from: T3 Code Desktop version 0.1.1 on macos (");
59
+ assert.include(context, "## This session runs inside T3 Code");
60
+ assert.include(context, "/home/u/.t3/source/abc123 (v0.1.1, commit abc123)");
61
+ assert.include(context, "Wait for it instead of\ncloning again.");
62
+});
63
+
64
+const contextInput = {
65
+ generatedAt: "2026-09-24T00:00:00.000Z",
66
+ os: "linux x64 (7.2.0)",
67
+ nodeVersion: "v26.8.2",
68
+ paths: {
69
+ stateDir: "/home/u/.t3/userdata",
70
+ dbPath: "/home/u/.t3/userdata/state.sqlite",
71
+ settingsPath: "/home/u/.t3/userdata/settings.json",
72
+ logsDir: "/home/u/.t3/userdata/logs",
73
+ serviceLogPath: "/home/u/.t3/userdata/logs/boot-service.log",
74
+ desktopBackendLogGlob: "/home/u/.t3/userdata/logs/server-child*.log*",
75
+ serverTracePath: "/home/u/.t3/userdata/logs/server.trace.ndjson",
76
+ providerEventLogPath: "/home/u/.t3/userdata/logs/provider/events.log",
77
+ terminalLogsDir: "/home/u/.t3/userdata/logs/terminals",
78
+ providerStatusCacheDir: "/home/u/.t3/caches",
79
+ secretsDir: "/home/u/.t3/userdata/secrets",
80
+ sourceCacheDir: "/home/u/.t3/source",
81
+ },
82
+} satisfies Omit<TriageContextInput, "entry" | "server">;
apps/server/src/triage/triagePrompt.ts
renamed
+105
-14
@@ -1,3 +1,5 @@
1
+import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
2
+
3
/** Keep TRIAGE_PLAYBOOK byte-identical to .github/triage/PLAYBOOK.md after unescaping backticks and backslashes. */
4
5
export const TRIAGE_PLAYBOOK = `# T3 Code triage playbook
@@ -13,8 +15,8 @@ provided alongside this playbook. Everything machine-specific lives there, not h
15
16
## 1. Ask what went wrong
17
16
-Your first message to the user: ask them to describe what went wrong, in their own
17
-words. Ask them to paste screenshots directly into this session if they have any.
18
+Unless the user already described it, your first message asks what went wrong, in
19
+their own words. Ask them to paste screenshots directly into this session if they have any.
20
Ask follow-up questions when the description is vague. Good repro steps are the most
21
valuable thing you can extract from this conversation.
22
@@ -147,30 +149,61 @@ user's environment and evidence instead of filing a new issue. A confirmed
149
duplicate with fresh evidence is more useful than a second thread.
150
`;
151
152
+/** Where the session started: the `t3 triage` CLI, or "Triage an issue" in a client. */
153
+export type TriageEntry =
154
+ | { readonly kind: "cli"; readonly cliVersion: string; readonly launchedAs: string }
155
+ | { readonly kind: "app"; readonly client: string };
156
+
157
/** Windows .cmd shims cannot carry a multiline playbook in argv; point to the file instead. */
158
export const buildTriageLaunchPrompt = (promptFilePath: string) =>
159
`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.`;
160
154
-export const buildTriageSeedPrompt = (contextFilePath: string) => `A T3 Code user is \
155
-having a problem with their install and started this session with \`t3 triage\`.
161
+/**
162
+ * The composer text an in-app session opens with. The file link renders as a
163
+ * chip, and the user writes what went wrong after it, so the first turn
164
+ * already carries the description.
165
+ */
166
+export const buildTriageAppPrompt = (promptFilePath: string) =>
167
+ `Read ${serializeComposerFileLink(promptFilePath)} and follow it. `;
168
+
169
+export const buildTriageSeedPrompt = (input: {
170
+ readonly contextFilePath: string;
171
+ readonly entry: TriageEntry;
172
+}) => `A T3 Code user is having a problem with their install and started this \
173
+session ${input.entry.kind === "cli" ? "with `t3 triage`" : "from the T3 Code app"}.
174
175
Machine facts (versions, OS, paths, server liveness) are in the triage context file:
176
159
- ${contextFilePath}
177
+ ${input.contextFilePath}
178
161
-Follow the playbook below, starting by asking the user what went wrong.
179
+${
180
+ input.entry.kind === "cli"
181
+ ? "Follow the playbook below, starting by asking the user what went wrong."
182
+ : "Follow the playbook below. The message that sent you here may already describe what went wrong; if it does not, start by asking."
183
+}
184
185
---
186
187
${TRIAGE_PLAYBOOK}`;
188
189
+/** A clone the server made before the session started, or why it could not. */
190
+export type TriageSourceClone =
191
+ | {
192
+ readonly _tag: "cloned" | "cloning";
193
+ readonly directory: string;
194
+ readonly ref: string;
195
+ readonly commit: string;
196
+ readonly serverVersion: string;
197
+ }
198
+ | { readonly _tag: "failed"; readonly serverVersion: string; readonly reason: string };
199
+
200
export interface TriageContextInput {
201
readonly generatedAt: string;
169
- readonly cliVersion: string;
202
+ readonly entry: TriageEntry;
203
readonly os: string;
204
readonly nodeVersion: string;
172
- readonly launchedAs: string;
205
readonly server: string;
206
+ readonly sourceClone?: TriageSourceClone | undefined;
207
readonly paths: {
208
readonly stateDir: string;
209
readonly dbPath: string;
@@ -187,17 +220,74 @@ export interface TriageContextInput {
220
};
221
}
222
190
-export const buildTriageContext = (input: TriageContextInput) => `# T3 Code triage context
223
+const entryLines = (entry: TriageEntry) =>
224
+ entry.kind === "cli"
225
+ ? {
226
+ generatedBy: "`t3 triage`",
227
+ before: `- Triage CLI version: ${entry.cliVersion} (the \`t3\` that ran this command; the bug may have happened on another build)`,
228
+ after: `- CLI launched as: ${entry.launchedAs}`,
229
+ }
230
+ : {
231
+ generatedBy: "the T3 Code app",
232
+ before: `- Started from: ${entry.client} (the client the user pressed "Triage an issue" in; the bug may have happened on another device)`,
233
+ after: undefined,
234
+ };
235
+
236
+const sourceSection = (clone: TriageSourceClone) => {
237
+ if (clone._tag === "failed") {
238
+ return `
239
+## Source
240
+
241
+The server could not clone the source for its version (${clone.serverVersion}): ${clone.reason}
242
+Clone it as step 4 describes.
243
+`;
244
+ }
245
+ const verb = clone._tag === "cloned" ? "The server cloned" : "The server is cloning";
246
+ const what =
247
+ clone.ref === "main"
248
+ ? `main, since its version (${clone.serverVersion}) has no release tag`
249
+ : `the source for its own version (${clone.serverVersion})`;
250
+ const wait =
251
+ clone._tag === "cloned"
252
+ ? ""
253
+ : `
254
+The folder appears only when the clone is complete. Wait for it instead of
255
+cloning again. If it has not appeared after a few minutes, clone as step 4
256
+describes.
257
+`;
258
+ return `
259
+## Source
260
192
-Generated by \`t3 triage\` at ${input.generatedAt}.
261
+${verb} ${what}:
262
194
-- Triage CLI version: ${input.cliVersion} (the \`t3\` that ran this command; the bug may have happened on another build)
263
+ ${clone.directory} (${clone.ref}, commit ${clone.commit})
264
+${wait}
265
+Use it when the bug happened on this server's build. When it happened on another
266
+build, clone that version as step 4 describes.
267
+`;
268
+};
269
+
270
+const IN_APP_SECTION = `
271
+## This session runs inside T3 Code
272
+
273
+You are a thread inside the T3 Code server described above. Stopping,
274
+restarting, or killing that server, its service, or the desktop app ends this
275
+session. When a fix needs one of those, give the user the exact steps and let
276
+them do it. The database is in use by that server: read it, never lock it.
277
+`;
278
+
279
+export const buildTriageContext = (input: TriageContextInput) => {
280
+ const entry = entryLines(input.entry);
281
+ return `# T3 Code triage context
282
+
283
+Generated by ${entry.generatedBy} at ${input.generatedAt}.
284
+
285
+${entry.before}
286
- OS: ${input.os}
287
- Node: ${input.nodeVersion}
197
-- CLI launched as: ${input.launchedAs}
198
-- Server process: ${input.server}
288
+${entry.after === undefined ? "" : `${entry.after}\n`}- Server process: ${input.server}
289
- Repo: https://github.com/pingdotgg/t3code
200
-
290
+${input.entry.kind === "app" ? IN_APP_SECTION : ""}${input.sourceClone === undefined ? "" : sourceSection(input.sourceClone)}
291
## Paths
292
293
- State dir: ${input.paths.stateDir}
@@ -213,3 +303,4 @@ Generated by \`t3 triage\` at ${input.generatedAt}.
303
- Secrets dir (NEVER read this): ${input.paths.secretsDir}
304
- Source cache dir (clone the repo here): ${input.paths.sourceCacheDir}
305
`;
306
+};
apps/server/src/triage/triageSession.test.ts
renamed
+1
-1
@@ -9,7 +9,7 @@ import {
9
makePersistedServerRuntimeState,
10
persistServerRuntimeState,
11
} from "../serverRuntimeState.ts";
12
-import { describeServerProcess } from "./triage.ts";
12
+import { describeServerProcess } from "./triageSession.ts";
13
14
it.effect("reports the version the running server recorded, not the CLI's", () =>
15
Effect.gen(function* () {
apps/server/src/triage/triageSession.ts
new
+100
@@ -0,0 +1,100 @@
1
+// @effect-diagnostics nodeBuiltinImport:off
2
+import * as NodeOS from "node:os";
3
+
4
+import { TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
5
+import * as HostProcess from "@t3tools/shared/HostProcess";
6
+import * as DateTime from "effect/DateTime";
7
+import * as Effect from "effect/Effect";
8
+import * as FileSystem from "effect/FileSystem";
9
+import * as Option from "effect/Option";
10
+import * as Path from "effect/Path";
11
+
12
+import * as BootService from "../cloud/bootService.ts";
13
+import type * as ServerConfig from "../config.ts";
14
+import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
15
+import {
16
+ buildTriageContext,
17
+ buildTriageSeedPrompt,
18
+ type TriageEntry,
19
+ type TriageSourceClone,
20
+} from "./triagePrompt.ts";
21
+
22
+export const describeServerProcess = Effect.fn("triage.describeServerProcess")(function* (
23
+ serverRuntimeStatePath: string,
24
+) {
25
+ const state = yield* readPersistedServerRuntimeState(serverRuntimeStatePath);
26
+ if (Option.isNone(state)) {
27
+ return "not running (no server-runtime.json; the server may never have started here)";
28
+ }
29
+ const version =
30
+ state.value.serverVersion === undefined
31
+ ? "version not recorded"
32
+ : `version ${state.value.serverVersion}`;
33
+ if (!isProcessAlive(state.value.pid)) {
34
+ return `not running (state file is stale: pid ${String(state.value.pid)} is dead; last origin ${state.value.origin}, ${version})`;
35
+ }
36
+ return `running (pid ${String(state.value.pid)}, ${state.value.origin}, ${version})`;
37
+});
38
+
39
+/** The source cache the playbook clones into, one subdirectory per commit. */
40
+export const triageSourceCacheDir = (baseDir: string, path: Path.Path) =>
41
+ path.join(baseDir, "source");
42
+
43
+/**
44
+ * Writes `context.md` and the playbook prompt into a fresh `<stateDir>/triage/<time>`
45
+ * folder. Both `t3 triage` and the in-app entry point start from these files.
46
+ */
47
+export const writeTriageSession = Effect.fn("triage.writeTriageSession")(function* (input: {
48
+ readonly baseDir: string;
49
+ readonly paths: ServerConfig.ServerDerivedPaths;
50
+ readonly entry: TriageEntry;
51
+ readonly server: string;
52
+ readonly sourceClone?: TriageSourceClone | undefined;
53
+}) {
54
+ const fs = yield* FileSystem.FileSystem;
55
+ const path = yield* Path.Path;
56
+ const { paths } = input;
57
+
58
+ const now = yield* DateTime.now;
59
+ const sessionDir = path.join(
60
+ paths.stateDir,
61
+ "triage",
62
+ DateTime.formatIso(now).replaceAll(":", "-").replace(".", "-"),
63
+ );
64
+ yield* fs.makeDirectory(sessionDir, { recursive: true });
65
+
66
+ const contextFilePath = path.join(sessionDir, "context.md");
67
+ yield* fs.writeFileString(
68
+ contextFilePath,
69
+ buildTriageContext({
70
+ generatedAt: DateTime.formatIso(now),
71
+ entry: input.entry,
72
+ os: `${yield* HostProcess.Platform} ${yield* HostProcess.Architecture} (${NodeOS.release()})`,
73
+ nodeVersion: process.version,
74
+ server: input.server,
75
+ sourceClone: input.sourceClone,
76
+ paths: {
77
+ stateDir: paths.stateDir,
78
+ dbPath: paths.dbPath,
79
+ settingsPath: paths.settingsPath,
80
+ logsDir: paths.logsDir,
81
+ serviceLogPath: path.join(paths.logsDir, BootService.BOOT_SERVICE_LOG_FILE),
82
+ desktopBackendLogGlob: path.join(paths.logsDir, "server-child*.log*"),
83
+ serverTracePath: paths.serverTracePath,
84
+ providerEventLogPath: paths.providerEventLogPath,
85
+ terminalLogsDir: paths.terminalLogsDir,
86
+ providerStatusCacheDir: paths.providerStatusCacheDir,
87
+ secretsDir: paths.secretsDir,
88
+ sourceCacheDir: triageSourceCacheDir(input.baseDir, path),
89
+ },
90
+ }),
91
+ );
92
+
93
+ const promptFilePath = path.join(sessionDir, TRIAGE_PROMPT_FILE_NAME);
94
+ yield* fs.writeFileString(
95
+ promptFilePath,
96
+ buildTriageSeedPrompt({ contextFilePath, entry: input.entry }),
97
+ );
98
+
99
+ return { sessionDir, contextFilePath, promptFilePath };
100
+});
apps/server/src/ws.test.ts
+2
@@ -100,6 +100,7 @@ import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
100
import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
101
import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
102
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
103
+import * as TriageService from "./triage/TriageService.ts";
104
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
105
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
106
import * as ServerConfigModule from "./config.ts";
@@ -399,6 +400,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
400
Layer.mock(ServerSecretStore.ServerSecretStore)({}),
401
Layer.mock(WorkspacePaths.WorkspacePaths)({}),
402
Layer.mock(TraceDiagnostics.TraceDiagnostics)({}),
403
+ Layer.mock(TriageService.TriageService)({}),
404
Layer.mock(ProjectFaviconResolver.ProjectFaviconResolver)({}),
405
Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
406
Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}),
apps/server/src/ws.ts
+3
@@ -240,6 +240,7 @@ import { commandFeatureUsage, featureUsage } from "./telemetry/FeatureUsage.ts";
240
import type { TelemetryOwner } from "./telemetry/Identify.ts";
241
import * as UsageService from "./usage/UsageService.ts";
242
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
243
+import * as TriageService from "./triage/TriageService.ts";
244
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
245
import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts";
246
import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts";
@@ -1376,6 +1377,7 @@ export const layerWsRpc = (
1377
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
1378
const sessions = yield* SessionStore.SessionStore;
1379
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
1380
+ const triage = yield* TriageService.TriageService;
1381
const hostResources = yield* HostResources.HostResources;
1382
const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
1383
const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;
@@ -2580,6 +2582,7 @@ export const layerWsRpc = (
2582
[WS_METHODS.serverRefreshUsageRates]: (_input) => usage.refreshRates,
2583
[WS_METHODS.serverRetryResourceTelemetry]: (_input) => resourceTelemetry.retry,
2584
[WS_METHODS.serverCheckOtlpEndpoint]: (input) => otlpEndpointCheck.check(input),
2585
+ [WS_METHODS.serverPrepareTriage]: (input) => triage.prepare(input),
2586
[WS_METHODS.serverSignalProcess]: (input) => processDiagnostics.signal(input),
2587
[WS_METHODS.serverReportClientActivity]: (input, metadata) =>
2588
Ref.update(rpcClientIds, (clientIds) => {
apps/web/src/components/CommandPalette.tsx
+30
@@ -52,6 +52,7 @@ import {
52
import { useLocation, useNavigate } from "@tanstack/react-router";
53
import {
54
ArrowLeftIcon,
55
+ BugIcon,
56
ChartNoAxesColumnIcon,
57
CheckIcon,
58
ChevronRightIcon,
@@ -107,6 +108,8 @@ import { sourceControlEnvironment } from "../state/sourceControl";
108
import { useAtomCommand } from "../state/use-atom-command";
109
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
110
import { useScratchProject } from "../hooks/useScratchProject";
111
+import { useStartTriage } from "../hooks/useStartTriage";
112
+import { pickTriageEnvironment } from "../lib/triageTarget";
113
import { useNewProject } from "../hooks/useNewProject";
114
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
115
import {
@@ -394,6 +397,7 @@ function OpenCommandPaletteDialog(props: {
397
reportFailure: false,
398
});
399
const { scratchEnvironmentId, scratchWorkspaceRootFor, startScratchThread } = useScratchProject();
400
+ const startTriage = useStartTriage();
401
const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, {
402
reportFailure: false,
403
});
@@ -632,6 +636,20 @@ function OpenCommandPaletteDialog(props: {
636
const scratchTargetEnvironmentId = scratchEnvironmentId(
637
currentProjectEnvironmentId ?? primaryEnvironmentId,
638
);
639
+ const supportsTriage = (environmentId: EnvironmentId | null) =>
640
+ environments.find((environment) => environment.environmentId === environmentId)?.serverConfig
641
+ ?.environment.capabilities.triage === true;
642
+ const triageEnvironmentId = pickTriageEnvironment({
643
+ onScreen: currentProjectEnvironmentId,
644
+ primary: primaryEnvironmentId,
645
+ connected: environments
646
+ .filter((environment) => environment.connection.phase === "connected")
647
+ .map((environment) => environment.environmentId),
648
+ supportsTriage,
649
+ });
650
+ const canTriage =
651
+ useAtomValue(serverEnvironment.prepareTriage.permissionAtom(triageEnvironmentId)) &&
652
+ supportsTriage(triageEnvironmentId);
653
const currentProjectCwd = currentProjectId
654
? (projectCwdById.get(currentProjectId) ?? null)
655
: null;
@@ -1199,6 +1217,18 @@ function OpenCommandPaletteDialog(props: {
1217
});
1218
}
1219
1220
+ if (triageEnvironmentId !== null && canTriage) {
1221
+ actionItems.push({
1222
+ kind: "action",
1223
+ value: "action:triage",
1224
+ searchTerms: ["triage", "bug", "issue", "report", "broken", "debug", "help", "support"],
1225
+ title: "Triage an issue",
1226
+ description: "An agent investigates a T3 Code problem and helps file an issue",
1227
+ icon: <BugIcon className={ITEM_ICON_CLASS} />,
1228
+ run: () => startTriage(triageEnvironmentId),
1229
+ });
1230
+ }
1231
+
1232
if (activeThreadKey !== null && supportsThreadFind) {
1233
actionItems.push({
1234
kind: "action",
apps/web/src/components/chat/DraftHeroHeadline.tsx
+18
@@ -12,6 +12,7 @@ import { shortcutLabelForCommand } from "~/keybindings";
12
import { primaryServerKeybindingsAtom } from "~/state/server";
13
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
14
import { useScratchProject } from "~/hooks/useScratchProject";
15
+import { isTriagePrompt } from "~/hooks/useStartTriage";
16
import { useClientSettings } from "~/hooks/useSettings";
17
import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";
18
import {
@@ -42,6 +43,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
43
import { InlineButton } from "../ui/button";
44
import { DraftProjectName } from "./DraftProjectName";
45
import { DraftHeroProjectHeading } from "./DraftHeroProjectHeading";
46
+import { TriageDraftHero } from "./TriageDraftHero";
47
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
48
49
const ADD_PROJECT_VALUE = "add-project";
@@ -72,6 +74,10 @@ export function DraftHeroHeadline({
74
(store) => store.setLogicalProjectDraftThreadId,
75
);
76
const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
77
+ // A boolean, so typing in a draft does not re-render the hero.
78
+ const isTriageDraftPrompt = useComposerDraftStore((store) =>
79
+ draftId ? isTriagePrompt(store.getComposerDraft(draftId)?.prompt ?? "") : false,
80
+ );
81
const applyStickyState = useComposerDraftStore((store) => store.applyStickyState);
82
const setModelSelection = useComposerDraftStore((store) => store.setModelSelection);
83
const openAddProject = () => openCommandPalette({ open: "add-project" });
@@ -336,6 +342,18 @@ export function DraftHeroHeadline({
342
</Tooltip>
343
) : null;
344
345
+ if (isScratchDraft && isTriageDraftPrompt) {
346
+ const environment = environments.find(
347
+ (entry) => entry.environmentId === activeProject.environmentId,
348
+ );
349
+ return (
350
+ <TriageDraftHero
351
+ machineLabel={environment?.label ?? null}
352
+ serverVersion={environment?.serverConfig?.environment.serverVersion ?? null}
353
+ />
354
+ );
355
+ }
356
+
357
return (
358
<div className="mx-auto flex w-full max-w-5xl flex-col items-center">
359
{hasResolvedProject && !isScratchDraft ? (
apps/web/src/components/chat/TriageDraftHero.tsx
new
+59
@@ -0,0 +1,59 @@
1
+import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
2
+import { TRIAGE_CLI_COMMAND } from "~/hooks/useStartTriage";
3
+
4
+import { InlineButton } from "../ui/button";
5
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
6
+
7
+/**
8
+ * The empty-draft hero for a triage session, in place of "What should we work on?".
9
+ * Keeps the regular hero's heading-plus-one-line rhythm above the composer.
10
+ */
11
+export function TriageDraftHero(props: {
12
+ readonly machineLabel: string | null;
13
+ readonly serverVersion: string | null;
14
+}) {
15
+ const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 1500, target: "command" });
16
+ return (
17
+ <div className="mx-auto flex w-full max-w-5xl flex-col items-center">
18
+ <h1 className="w-full text-center font-normal text-2xl text-foreground tracking-tight sm:text-3xl">
19
+ What went wrong?
20
+ </h1>
21
+ <p className="mt-2 flex h-6 w-full items-center justify-center gap-1.5 text-sm">
22
+ <Tooltip>
23
+ <TooltipTrigger
24
+ render={<span tabIndex={0} className="min-w-0 truncate font-medium text-foreground" />}
25
+ >
26
+ {props.machineLabel ?? "This machine"}
27
+ {props.serverVersion === null ? null : (
28
+ <span className="ml-1.5 font-normal text-muted-foreground">
29
+ v{props.serverVersion}
30
+ </span>
31
+ )}
32
+ </TooltipTrigger>
33
+ <TooltipPopup side="bottom">
34
+ The agent reads T3 Code's logs and source here, and asks before it applies a fix or
35
+ posts anything.
36
+ </TooltipPopup>
37
+ </Tooltip>
38
+ <span aria-hidden className="text-muted-foreground">
39
+ ·
40
+ </span>
41
+ <Tooltip>
42
+ <TooltipTrigger
43
+ render={
44
+ <InlineButton
45
+ tone="muted"
46
+ className="pointer-events-auto"
47
+ onClick={() => copyToClipboard(TRIAGE_CLI_COMMAND, undefined)}
48
+ />
49
+ }
50
+ >
51
+ {isCopied ? "Copied" : "or run"}
52
+ {isCopied ? null : <code className="ml-1 font-mono text-xs">{TRIAGE_CLI_COMMAND}</code>}
53
+ </TooltipTrigger>
54
+ <TooltipPopup side="bottom">Copy command, for a terminal</TooltipPopup>
55
+ </Tooltip>
56
+ </p>
57
+ </div>
58
+ );
59
+}
apps/web/src/connection/platform.ts
+3
-3
@@ -151,7 +151,7 @@ const layerWakeups = Wakeups.layer({
151
),
152
});
153
154
-function clientMetadata() {
154
+export function currentClientMetadata() {
155
return clientPresentationMetadata({
156
appVersion: APP_VERSION,
157
hosted: isHostedStaticApp(),
@@ -325,7 +325,7 @@ const analyticsDevice = {
325
const layerCapabilities = Layer.effectContext(
326
Effect.sync(() => {
327
const presentation = ClientCapabilities.ClientPresentation.of({
328
- metadata: clientMetadata(),
328
+ metadata: currentClientMetadata(),
329
});
330
const cloudSession = ClientCapabilities.CloudSession.of({
331
identity: Effect.sync(() =>
@@ -462,7 +462,7 @@ const loadSecondaryConnectionRegistration = Effect.fn(
462
httpBaseUrl,
463
credential: entry.bootstrapToken,
464
scopes: AuthStandardClientScopes,
465
- clientMetadata: clientMetadata(),
465
+ clientMetadata: currentClientMetadata(),
466
}).pipe(Effect.mapError(mapRemoteEnvironmentError));
467
// Desktop operations need the pool backend id to reach the owning instance; RPC uses the environment id.
468
const connectionId = desktopLocalConnectionId(entry.id);
apps/web/src/hooks/useHandleNewThread.test.ts
+92
-4
@@ -18,6 +18,8 @@ const testState = vi.hoisted(() => {
18
readonly promotedTo: null;
19
readonly threadId: string;
20
} | null = null;
21
+ let openDraftRoute: { readonly kind: "draft"; readonly draftId: string } | null = null;
22
+ let draftsWithUserText = new Set<string>();
23
const router = {
24
state: {
25
location: { href: "/" },
@@ -28,14 +30,26 @@ const testState = vi.hoisted(() => {
30
}),
31
};
32
const draftStore = {
31
- getComposerDraft: vi.fn(() => ({})),
33
+ getComposerDraft: vi.fn((draftId: string) => ({ draftId })),
34
getDraftSessionByLogicalProjectKey: vi.fn(() => storedDraft),
33
- getDraftSession: vi.fn(() => null),
35
+ getDraftSession: vi.fn(() =>
36
+ openDraftRoute === null
37
+ ? null
38
+ : {
39
+ logicalProjectKey: "remote-project",
40
+ promotedTo: null,
41
+ threadId: "thread-open",
42
+ createdAt: "2026-01-01T00:00:00.000Z",
43
+ runtimeMode: "full-access",
44
+ interactionMode: "default",
45
+ },
46
+ ),
47
getDraftThread: vi.fn(() => null),
48
applyStickyState: vi.fn(),
49
setDraftThreadContext: vi.fn(),
50
setLogicalProjectDraftThreadId: vi.fn(),
51
setModelSelection: vi.fn(),
52
+ setPrompt: vi.fn(),
53
};
54
55
return {
@@ -56,6 +70,17 @@ const testState = vi.hoisted(() => {
70
removeProject() {
71
projectRemoved = true;
72
},
73
+ hasUserText: (draft: { readonly draftId?: string } | null | undefined) =>
74
+ draft?.draftId !== undefined && draftsWithUserText.has(draft.draftId),
75
+ giveUserText(draftId: string) {
76
+ draftsWithUserText = new Set([...draftsWithUserText, draftId]);
77
+ },
78
+ get openDraftRoute() {
79
+ return openDraftRoute;
80
+ },
81
+ openEmptyDraft(draftId: string) {
82
+ openDraftRoute = { kind: "draft", draftId };
83
+ },
84
get targetSettings() {
85
return targetSettings;
86
},
@@ -67,6 +92,8 @@ const testState = vi.hoisted(() => {
92
},
93
) {
94
storedDraft = nextStoredDraft;
95
+ openDraftRoute = null;
96
+ draftsWithUserText = new Set();
97
projectRemoved = false;
98
connectedEnvironmentIds = ["environment-primary", "environment-ssh"];
99
targetSettings = {
@@ -79,6 +106,7 @@ const testState = vi.hoisted(() => {
106
router.navigate.mockClear();
107
draftStore.setDraftThreadContext.mockClear();
108
draftStore.setLogicalProjectDraftThreadId.mockClear();
109
+ draftStore.setPrompt.mockClear();
110
projectFileRead = new Promise<null>((resolve) => {
111
completeProjectFileRead = resolve;
112
});
@@ -161,7 +189,8 @@ vi.mock("../composerDraftStore", () => {
189
getState: () => testState.draftStore,
190
});
191
return {
164
- composerDraftHasUserContent: () => false,
192
+ composerDraftHasUserContent: (draft: { readonly draftId?: string } | null | undefined) =>
193
+ testState.hasUserText(draft),
194
markPromotedDraftThreadByRef: vi.fn(),
195
useComposerDraftStore,
196
};
@@ -208,7 +237,9 @@ vi.mock("../state/server", () => ({
237
environmentServerConfigsAtom: {},
238
primaryServerSettingsAtom: "primary-settings",
239
}));
211
-vi.mock("../threadRoutes", () => ({ resolveThreadRouteTarget: () => null }));
240
+vi.mock("../threadRoutes", () => ({
241
+ resolveThreadRouteTarget: () => testState.openDraftRoute,
242
+}));
243
vi.mock("../uiStateStore", () => ({
244
legacyProjectCwdPreferenceKey: () => "remote-project",
245
useUiStateStore: () => [],
@@ -246,6 +277,25 @@ describe.each([
277
expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled();
278
});
279
280
+ it("sets the prompt before the draft shows", async () => {
281
+ testState.reset(draft);
282
+ const pendingOpen = useNewThreadHandler()(
283
+ { environmentId: "environment-ssh", projectId: "project-remote" } as never,
284
+ { prompt: "Read the playbook. " },
285
+ );
286
+
287
+ testState.completeProjectFileRead(null);
288
+ const opened = await pendingOpen;
289
+
290
+ expect(testState.draftStore.setPrompt).toHaveBeenCalledWith(
291
+ opened?.draftId,
292
+ "Read the playbook. ",
293
+ );
294
+ expect(testState.draftStore.setPrompt.mock.invocationCallOrder[0]).toBeLessThan(
295
+ testState.router.navigate.mock.invocationCallOrder[0] ?? 0,
296
+ );
297
+ });
298
+
299
it("abandons a delayed draft open when the project is removed meanwhile", async () => {
300
testState.reset(draft);
301
const pendingOpen = useNewThreadHandler()(
@@ -263,6 +313,44 @@ describe.each([
313
});
314
315
describe("useNewThreadHandler", () => {
316
+ it("keeps the text of a draft that gained some while it waited", async () => {
317
+ testState.reset(null);
318
+ const raced = {
319
+ draftId: "draft-raced",
320
+ environmentId: "environment-ssh",
321
+ promotedTo: null,
322
+ threadId: "thread-raced",
323
+ };
324
+ testState.draftStore.getDraftSessionByLogicalProjectKey
325
+ .mockReturnValueOnce(null)
326
+ .mockReturnValueOnce(raced as never);
327
+ testState.giveUserText("draft-raced");
328
+
329
+ const opened = await useNewThreadHandler()(
330
+ { environmentId: "environment-ssh", projectId: "project-remote" } as never,
331
+ { prompt: "Read the playbook. " },
332
+ );
333
+
334
+ expect(opened?.draftId).toBe("draft-raced");
335
+ expect(testState.draftStore.setPrompt).not.toHaveBeenCalled();
336
+ });
337
+
338
+ it("seeds the prompt into the empty draft that is already open", async () => {
339
+ testState.reset(null);
340
+ testState.openEmptyDraft("draft-open");
341
+
342
+ const opened = await useNewThreadHandler()(
343
+ { environmentId: "environment-ssh", projectId: "project-remote" } as never,
344
+ { prompt: "Read the playbook. " },
345
+ );
346
+
347
+ expect(opened?.draftId).toBe("draft-open");
348
+ expect(testState.draftStore.setPrompt).toHaveBeenCalledWith(
349
+ "draft-open",
350
+ "Read the playbook. ",
351
+ );
352
+ });
353
+
354
it("opens the draft without waiting on a project file from an offline machine", async () => {
355
testState.reset(null, { envMode: null, startFromOrigin: false });
356
testState.disconnect("environment-ssh");
apps/web/src/hooks/useHandleNewThread.ts
+13
@@ -81,6 +81,8 @@ export function createNewThreadHandler(router: AnyRouter) {
81
envMode?: DraftThreadEnvMode;
82
startFromOrigin?: boolean;
83
replace?: boolean;
84
+ /** Composer text for the draft, set before it shows. A draft with user text keeps it. */
85
+ prompt?: string;
86
},
87
): Promise<{ draftId: DraftId; threadId: ThreadId } | null> => {
88
const projects = readProjects();
@@ -98,7 +100,14 @@ export function createNewThreadHandler(router: AnyRouter) {
100
setDraftThreadContext,
101
setLogicalProjectDraftThreadId,
102
setModelSelection,
103
+ setPrompt,
104
} = useComposerDraftStore.getState();
105
+ // Never over text the user wrote: a draft can gain some while this awaits.
106
+ const seedPrompt = (draftId: DraftId) => {
107
+ if (options?.prompt === undefined) return;
108
+ if (composerDraftHasUserContent(getComposerDraft(draftId))) return;
109
+ setPrompt(draftId, options.prompt);
110
+ };
111
const requestingRouteHref = router.state.location.href;
112
const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref;
113
const currentRouteTarget = getCurrentRouteTarget();
@@ -286,6 +295,7 @@ export function createNewThreadHandler(router: AnyRouter) {
295
draftId: emptyStoredDraftThread.draftId,
296
threadId: emptyStoredDraftThread.threadId,
297
};
298
+ seedPrompt(emptyStoredDraftThread.draftId);
299
const routeTargetAfterWrites = getCurrentRouteTarget();
300
if (
301
routeTargetAfterWrites?.kind === "draft" &&
@@ -324,6 +334,7 @@ export function createNewThreadHandler(router: AnyRouter) {
334
interactionMode: latestActiveDraftThread.interactionMode,
335
...pickExplicitWorkspaceOptions(options),
336
});
337
+ seedPrompt(currentRouteTarget.draftId);
338
return Promise.resolve({
339
draftId: currentRouteTarget.draftId,
340
threadId: latestActiveDraftThread.threadId,
@@ -352,6 +363,7 @@ export function createNewThreadHandler(router: AnyRouter) {
363
interactionMode: racedDraft.interactionMode,
364
...pickExplicitWorkspaceOptions(options),
365
});
366
+ seedPrompt(racedDraft.draftId);
367
await router.navigate({
368
to: "/draft/$draftId",
369
params: { draftId: racedDraft.draftId },
@@ -379,6 +391,7 @@ export function createNewThreadHandler(router: AnyRouter) {
391
if (modelSelectionOverride) {
392
setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true });
393
}
394
+ seedPrompt(draftId);
395
await router.navigate({
396
to: "/draft/$draftId",
397
params: { draftId },
apps/web/src/hooks/useStartTriage.ts
new
+107
@@ -0,0 +1,107 @@
1
+import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2
+import {
3
+ type AtomCommandResult,
4
+ isAtomCommandInterrupted,
5
+ squashAtomCommandFailure,
6
+} from "@t3tools/client-runtime/state/runtime";
7
+import { type EnvironmentId, TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts";
8
+import { useRouter } from "@tanstack/react-router";
9
+
10
+import { stackedThreadToast, toastManager } from "~/components/ui/toast";
11
+import { currentClientMetadata } from "~/connection/platform";
12
+import { projectEnvironment } from "~/state/projects";
13
+import { serverEnvironment } from "~/state/server";
14
+import { useAtomCommand } from "~/state/use-atom-command";
15
+import { writeTextToClipboard } from "./useCopyToClipboard";
16
+import { useNewThreadHandler } from "./useHandleNewThread";
17
+import { useScratchProject } from "./useScratchProject";
18
+
19
+export const TRIAGE_CLI_COMMAND = "npx t3 triage";
20
+
21
+const copyTriageCliCommand = () =>
22
+ writeTextToClipboard(TRIAGE_CLI_COMMAND, "command").catch(() =>
23
+ toastManager.add({
24
+ type: "error",
25
+ title: `Could not copy. Type ${TRIAGE_CLI_COMMAND} instead.`,
26
+ }),
27
+ );
28
+
29
+/** A draft is a triage draft while its message still links the playbook file. */
30
+export const isTriagePrompt = (prompt: string) => prompt.includes(`[${TRIAGE_PROMPT_FILE_NAME}](`);
31
+
32
+/**
33
+ * In-app `t3 triage`: the server writes the session files and starts cloning
34
+ * the matching source, then a No project draft opens with the playbook linked.
35
+ * The draft hero explains the rest; the user picks a provider and describes
36
+ * the problem.
37
+ */
38
+export function useStartTriage() {
39
+ const router = useRouter();
40
+ const { scratchWorkspaceRootFor } = useScratchProject();
41
+ const handleNewThread = useNewThreadHandler();
42
+ const prepare = useAtomCommand(serverEnvironment.prepareTriage, { reportFailure: false });
43
+ const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false });
44
+
45
+ // With no draft to show, a toast is the only place to point at the CLI.
46
+ const fail = (description: string) =>
47
+ toastManager.add(
48
+ stackedThreadToast({
49
+ type: "error",
50
+ title: "Could not start triage",
51
+ description: `${description} Run ${TRIAGE_CLI_COMMAND} in a terminal on that machine instead.`,
52
+ timeout: 0,
53
+ actionProps: { children: "Copy command", onClick: () => void copyTriageCliCommand() },
54
+ // "Copy command" is the copy that helps here, not the error text.
55
+ data: { hideCopyButton: true },
56
+ }),
57
+ );
58
+ const failWith = (
59
+ result: Extract<AtomCommandResult<unknown, unknown>, { readonly _tag: "Failure" }>,
60
+ ) => {
61
+ if (isAtomCommandInterrupted(result)) return;
62
+ const error = squashAtomCommandFailure(result);
63
+ fail(error instanceof Error ? error.message : "An error occurred.");
64
+ };
65
+
66
+ // `routeChanged` tells the steps the user went elsewhere while they waited;
67
+ // the draft then stays closed instead of pulling them away.
68
+ const openTriageDraft = async (environmentId: EnvironmentId, routeChanged: () => boolean) => {
69
+ const prepared = await prepare({
70
+ environmentId,
71
+ input: { client: currentClientMetadata() },
72
+ });
73
+ if (prepared._tag === "Failure") return failWith(prepared);
74
+ const project = await openScratch({ environmentId, input: {} });
75
+ if (project._tag === "Failure") return failWith(project);
76
+ if (routeChanged()) return;
77
+ // A null result means the user went elsewhere; only a throw is a failure.
78
+ await handleNewThread(scopeProjectRef(project.value.environmentId, project.value.id), {
79
+ prompt: prepared.value.prompt,
80
+ }).catch(() => fail("T3 Code could not open a new thread."));
81
+ };
82
+
83
+ return async (environmentId: EnvironmentId) => {
84
+ if (scratchWorkspaceRootFor(environmentId) === null) {
85
+ fail("This machine cannot start threads without a project.");
86
+ return;
87
+ }
88
+ const requestingRouteHref = router.state.location.href;
89
+ // The palette is already closed, and a slow network can hold up the source
90
+ // lookup, so say something when the draft does not open at once.
91
+ let pendingToastId: ReturnType<typeof toastManager.add> | undefined;
92
+ const pendingTimer = setTimeout(() => {
93
+ pendingToastId = toastManager.add({
94
+ type: "loading",
95
+ title: "Starting triage…",
96
+ timeout: 0,
97
+ });
98
+ }, 400);
99
+ await openTriageDraft(
100
+ environmentId,
101
+ () => router.state.location.href !== requestingRouteHref,
102
+ ).finally(() => {
103
+ clearTimeout(pendingTimer);
104
+ if (pendingToastId !== undefined) toastManager.close(pendingToastId);
105
+ });
106
+ };
107
+}
apps/web/src/lib/triageTarget.test.ts
new
+27
@@ -0,0 +1,27 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+
3
+import { pickTriageEnvironment } from "./triageTarget";
4
+
5
+describe("pickTriageEnvironment", () => {
6
+ it("skips a primary machine whose server lacks triage", () => {
7
+ expect(
8
+ pickTriageEnvironment({
9
+ onScreen: null,
10
+ primary: "old-primary",
11
+ connected: ["old-primary", "new-remote"],
12
+ supportsTriage: (environmentId) => environmentId === "new-remote",
13
+ }),
14
+ ).toBe("new-remote");
15
+ });
16
+
17
+ it("prefers a capable primary over other capable machines", () => {
18
+ expect(
19
+ pickTriageEnvironment({
20
+ onScreen: null,
21
+ primary: "primary",
22
+ connected: ["remote", "primary"],
23
+ supportsTriage: () => true,
24
+ }),
25
+ ).toBe("primary");
26
+ });
27
+});
apps/web/src/lib/triageTarget.ts
new
+16
@@ -0,0 +1,16 @@
1
+/**
2
+ * The machine triage runs on: the one on screen, else the primary if it
3
+ * supports triage, else the first connected machine that does. Without No
4
+ * project threads the action still shows and explains the terminal fallback,
5
+ * so this does not check for them.
6
+ */
7
+export function pickTriageEnvironment<Id extends string>(input: {
8
+ readonly onScreen: Id | null;
9
+ readonly primary: Id | null;
10
+ readonly connected: ReadonlyArray<Id>;
11
+ readonly supportsTriage: (environmentId: Id) => boolean;
12
+}): Id | null {
13
+ if (input.onScreen !== null) return input.onScreen;
14
+ if (input.primary !== null && input.supportsTriage(input.primary)) return input.primary;
15
+ return input.connected.find(input.supportsTriage) ?? null;
16
+}
docs/README.md
+1
@@ -24,6 +24,7 @@
24
- [Outside agents (MCP)](./user/outside-agents.md)
25
- [Running in the background](./user/background-service.md)
26
- [Updating T3 Code](./user/updating.md)
27
+- [Triage an issue](./user/triage.md)
28
- 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)
29
30
---
docs/user/triage.md
new
+29
@@ -0,0 +1,29 @@
1
+# Triage an issue
2
+
3
+Triage lets your own coding agent investigate a T3 Code problem. The agent
4
+reads the logs and state of the machine, checks the T3 Code source for that
5
+version, finds known issues, and can help you write a good GitHub issue. It asks
6
+before it applies a fix or posts anything.
7
+
8
+## In the app
9
+
10
+Open the command palette and choose **Triage an issue**. A new thread with no
11
+project opens, with the triage playbook linked in the message. Choose any
12
+provider, describe what went wrong after the link, and send. T3 Code gets the
13
+source for the server's version while you write.
14
+
15
+Triage runs on the machine of the thread or draft that you have open. With
16
+nothing open, it uses your primary machine if that supports triage, or else the
17
+first connected machine that does. The new thread shows the machine name, and on
18
+mobile the palette row shows it before you start. The agent runs inside that T3
19
+Code server, so it gives you any restart steps and does not do them itself.
20
+
21
+## In a terminal
22
+
23
+If the app does not start, or triage does not work in the app, run:
24
+
25
+```sh
26
+npx t3 triage
27
+```
28
+
29
+It starts Claude Code or Codex in your terminal with the same instructions.
packages/client-runtime/src/state/server.ts
+5
@@ -1154,6 +1154,11 @@ export function createServerEnvironmentAtoms<R, E>(
1154
tag: WS_METHODS.serverRunStorageCleanup,
1155
concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1156
}),
1157
+ prepareTriage: createEnvironmentRpcCommand(runtime, {
1158
+ label: "environment-data:server:prepare-triage",
1159
+ tag: WS_METHODS.serverPrepareTriage,
1160
+ concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1161
+ }),
1162
databaseStorage,
1163
databaseCompactionRecommendations,
1164
storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
packages/contracts/src/clientRpcPermissions.ts
+2
@@ -47,6 +47,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
47
[WS_METHODS.vcsSwitchRef]: AuthSourceControlWriteScope,
48
[WS_METHODS.vcsInit]: AuthSourceControlWriteScope,
49
50
+ // Starts an agent session on this environment that can read its logs and database.
51
+ [WS_METHODS.serverPrepareTriage]: AuthOrchestrationOperateScope,
52
[WS_METHODS.scheduledTasksUpsert]: AuthOrchestrationOperateScope,
53
[WS_METHODS.scheduledTasksSetEnabled]: AuthOrchestrationOperateScope,
54
[WS_METHODS.scheduledTasksDelete]: AuthOrchestrationOperateScope,
packages/contracts/src/environment.ts
+2
@@ -148,6 +148,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
148
(`linkOrigin`). Another environment links to this one only when it is
149
set, since without it that work could change the user's own threads. */
150
linkFence: Schema.optionalKey(Schema.Boolean),
151
+ /** Server answers server.prepareTriage. */
152
+ triage: Schema.optionalKey(Schema.Boolean),
153
});
154
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
155
packages/contracts/src/rpc.ts
+11
@@ -313,6 +313,9 @@ import {
313
ServerConfigStreamEvent,
314
DesktopUpdateCommitInput,
315
OtlpEndpointCheckInput,
316
+ ServerPrepareTriageError,
317
+ ServerPrepareTriageInput,
318
+ ServerPrepareTriageResult,
319
OtlpEndpointCheckResult,
320
ServerConfig,
321
ServerProviderUpdateError,
@@ -524,6 +527,7 @@ export const WS_METHODS = {
527
serverGetResourceTelemetryHistory: "server.getResourceTelemetryHistory",
528
serverRetryResourceTelemetry: "server.retryResourceTelemetry",
529
serverCheckOtlpEndpoint: "server.checkOtlpEndpoint",
530
+ serverPrepareTriage: "server.prepareTriage",
531
serverSignalProcess: "server.signalProcess",
532
serverReportClientActivity: "server.reportClientActivity",
533
serverReportHostPowerState: "server.reportHostPowerState",
@@ -946,6 +950,12 @@ const WsServerCheckOtlpEndpointRpc = Rpc.make(WS_METHODS.serverCheckOtlpEndpoint
950
error: EnvironmentAuthorizationError,
951
});
952
953
+const WsServerPrepareTriageRpc = Rpc.make(WS_METHODS.serverPrepareTriage, {
954
+ payload: ServerPrepareTriageInput,
955
+ success: ServerPrepareTriageResult,
956
+ error: Schema.Union([ServerPrepareTriageError, EnvironmentAuthorizationError]),
957
+});
958
+
959
const WsServerGetUsageSummaryRpc = Rpc.make(WS_METHODS.serverGetUsageSummary, {
960
payload: UsageSummaryInput,
961
success: UsageSummary,
@@ -2013,6 +2023,7 @@ export const WsRpcGroup = RpcGroup.make(
2023
WsServerGetResourceTelemetryHistoryRpc,
2024
WsServerRetryResourceTelemetryRpc,
2025
WsServerCheckOtlpEndpointRpc,
2026
+ WsServerPrepareTriageRpc,
2027
WsServerGetUsageSummaryRpc,
2028
WsServerRefreshUsageRatesRpc,
2029
WsServerSignalProcessRpc,
packages/contracts/src/server.ts
+28
-1
@@ -6,7 +6,7 @@ import {
6
ExecutionEnvironmentDescriptor,
7
ServerSelfUpdateMethod,
8
} from "./environment.ts";
9
-import { ServerAuthDescriptor } from "./auth.ts";
9
+import { AuthClientPresentationMetadata, ServerAuthDescriptor } from "./auth.ts";
10
import {
11
ForwardCompatibleArray,
12
IsoDateTime,
@@ -314,6 +314,33 @@ export const OtlpEndpointCheckResult = Schema.Union([
314
]);
315
export type OtlpEndpointCheckResult = typeof OtlpEndpointCheckResult.Type;
316
317
+/** The client tells the server what it is, so the triage context can name it. */
318
+export const ServerPrepareTriageInput = Schema.Struct({
319
+ client: AuthClientPresentationMetadata,
320
+});
321
+export type ServerPrepareTriageInput = typeof ServerPrepareTriageInput.Type;
322
+
323
+export const ServerPrepareTriageResult = Schema.Struct({
324
+ /** Composer text that links the session's prompt file. */
325
+ prompt: Schema.String,
326
+});
327
+export type ServerPrepareTriageResult = typeof ServerPrepareTriageResult.Type;
328
+
329
+/**
330
+ * The prompt file links as a chip in the user's message; clients spot a triage
331
+ * draft by it.
332
+ */
333
+export const TRIAGE_PROMPT_FILE_NAME = "triage-playbook.md";
334
+
335
+export class ServerPrepareTriageError extends Schema.TaggedError<ServerPrepareTriageError>()(
336
+ "ServerPrepareTriageError",
337
+ { cause: Schema.optional(Schema.Defect()) },
338
+) {
339
+ override get message(): string {
340
+ return "Could not write the triage session files.";
341
+ }
342
+}
343
+
344
export const ServerTraceDiagnosticsErrorKind = Schema.Literals([
345
"trace-file-not-found",
346
"trace-file-read-failed",