Compare commits

..
Author SHA1 Message Date
t3-code[bot]andZortos 82ad879504 fix: load Cursor plugin MCP servers
Co-authored-by: Zortos <[email protected]>
2026-08-12 19:23:56 +00:00
t3-code[bot]andmaria 8d24b5131f fix(web): open modified PR clicks in browser (#6278)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-12 14:32:44 -04:00
Exotic 770946d026 fix(web): render tooltips above dropdowns (#6241) 2026-08-12 14:32:20 -04:00
8601797233 fix(web): align update toast release notes link (#6322)
Co-authored-by: t3-code[bot] <219304759+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
Co-authored-by: Exotic <[email protected]>
2026-08-12 14:32:10 -04:00
Exotic b73232bdd3 feat(web): reset sidebar width on double click (#6320) 2026-08-12 10:07:39 -04:00
Wout Stiens f131228a59 fix(web): theme Clerk surfaces (#6300) 2026-08-12 19:36:04 +05:30
t3-code[bot]andWout Stiens e321667b10 fix(web): prevent changed files header overlap (#6314)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-12 08:56:13 -04:00
Julius Marminge 849bac8946 fix(connect): preserve CLI OAuth parameters through browser sign-in (#6285) 2026-08-12 12:58:34 +02:00
t3-code[bot]andUtkarsh Patil 6fd088af9f fix(web): align mobile onboarding header (#6293)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 16:07:44 +05:30
Wout Stiens b54bfc9312 feat(web): a better right panel empty state (#6258) 2026-08-12 15:28:46 +05:30
Nick Anisimovandshivam e1378a1f4d fix(mobile): keep ordered lists inside user bubbles (#6154)
Co-authored-by: shivam <[email protected]>
2026-08-12 14:39:51 +05:30
40 changed files with 858 additions and 635 deletions

No files matched your search

@@ -104,6 +104,10 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
includeOrderedLists: Platform.OS === "android",
} as const;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
@@ -888,7 +892,7 @@ function renderFeedEntry(
// children during the unclamped pass and never moves them once the width
// is clamped, so the paragraphs around the block end up drawn on top of
// each other. Pinning the width removes that pass.
const hasWideBlock = hasWideMarkdownBlock(message.text);
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
@@ -17,6 +17,30 @@ describe("hasWideMarkdownBlock", () => {
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
});
it("detects top-level and blockquoted ordered-list markers", () => {
expect(hasWideMarkdownBlock("1. One\n2. Two\n3. Three\n4. Four\n5. Five")).toBe(true);
expect(hasWideMarkdownBlock("before\n3) Three")).toBe(true);
expect(hasWideMarkdownBlock("> 1. One\n> 2. Two")).toBe(true);
expect(hasWideMarkdownBlock("> > 3) Three")).toBe(true);
});
it("detects nested ordered lists without treating indented code as a list", () => {
expect(hasWideMarkdownBlock("- Parent\n 1. Child\n 2. Child")).toBe(true);
expect(hasWideMarkdownBlock("> - Parent\n> 1. Child")).toBe(true);
expect(hasWideMarkdownBlock(" 1. indented code")).toBe(false);
expect(hasWideMarkdownBlock(" - code-like bullet\n 1. indented code")).toBe(false);
});
it("can limit ordered-list width pinning to Android", () => {
const orderedList = "1. One\n2. Two";
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: true })).toBe(true);
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: false })).toBe(false);
expect(hasWideMarkdownBlock("```\ncode\n```", { includeOrderedLists: false })).toBe(true);
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |", { includeOrderedLists: false })).toBe(
true,
);
});
it("detects GFM tables", () => {
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
+60 -8
View File
@@ -1,9 +1,10 @@
/**
* Detects markdown that the JS renderer draws as a standalone block View
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
* Detects markdown that the JS renderer draws as a block requiring a definite
* user-bubble width — fenced code blocks, GFM tables, and ordered lists.
*
* Those blocks report an intrinsic width equal to their widest line, which is
* effectively unbounded. A user bubble sizes itself from its content
* Fenced code blocks and tables report an intrinsic width equal to their
* widest line, which is effectively unbounded. A user bubble sizes itself
* from its content
* (`maxWidth` with no `width`), so Android lays the bubble's children out
* during the unclamped intrinsic pass — where the surrounding paragraphs
* collapse to a single line — and never repositions them once the width is
@@ -12,12 +13,57 @@
* intrinsic pass entirely, which is the same reason review-comment bubbles
* already carry an explicit width.
*
* Indented (four-space) code blocks are deliberately not detected: they are
* vanishingly rare in chat input and the check would fire on ordinary nested
* list continuations.
* Ordered lists hit the same Android layout bug because each item contains a
* flexing content column inside a shrink-to-fit row.
*
* A four-space ordered marker is only treated as a list when the preceding
* non-empty line is a less-indented list item. This keeps standalone indented
* code out of the heuristic while covering nested lists.
*/
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
// Trades some precision for a simple check, favoring false positives over false
// negatives: list-shaped paragraph may get a wider bubble
const ORDERED_LIST_ITEM = /^ {0,3}\d{1,9}[.)](?:[ \t]+|$)/;
const INDENTED_ORDERED_LIST_ITEM = /^( {4,})\d{1,9}[.)](?:[ \t]+|$)/;
const ANY_LIST_ITEM = /^( *)(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/;
const BLOCKQUOTE_PREFIX = /^ {0,3}>[ \t]?/;
export interface WideMarkdownBlockOptions {
readonly includeOrderedLists?: boolean;
}
function stripBlockquotePrefixes(line: string): string {
let content = line;
while (BLOCKQUOTE_PREFIX.test(content)) {
content = content.replace(BLOCKQUOTE_PREFIX, "");
}
return content;
}
function hasOrderedListItem(text: string): boolean {
let previousNonEmptyLine: string | null = null;
for (const rawLine of text.split("\n")) {
const line = stripBlockquotePrefixes(rawLine);
if (ORDERED_LIST_ITEM.test(line)) {
return true;
}
const nestedMatch = INDENTED_ORDERED_LIST_ITEM.exec(line);
const parentMatch =
previousNonEmptyLine === null ? null : ANY_LIST_ITEM.exec(previousNonEmptyLine);
if (nestedMatch && parentMatch && parentMatch[1].length < nestedMatch[1].length) {
return true;
}
if (line.trim().length > 0) {
previousNonEmptyLine = line;
}
}
return false;
}
function isTableDelimiterRow(line: string): boolean {
const trimmed = line.trim();
@@ -27,10 +73,16 @@ function isTableDelimiterRow(line: string): boolean {
return /^[|\-: \t]+$/.test(trimmed);
}
export function hasWideMarkdownBlock(text: string): boolean {
export function hasWideMarkdownBlock(
text: string,
options: WideMarkdownBlockOptions = {},
): boolean {
if (FENCED_CODE_BLOCK.test(text)) {
return true;
}
if (options.includeOrderedLists !== false && hasOrderedListItem(text)) {
return true;
}
if (!text.includes("|")) {
return false;
}
+1 -5
View File
@@ -5,7 +5,6 @@ import {
type RelayClientInstallProgressStage,
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as RelayClient from "@t3tools/shared/relayClient";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
@@ -695,11 +694,8 @@ export const connectCommand = Command.make("connect", {
// fail the command, just tell the user what happened and move on.
const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);
if (background) {
const platform = yield* HostProcessPlatform;
yield* Console.log(
platform === "darwin"
? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."
: "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
"\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",
);
return;
}
+2 -2
View File
@@ -29,9 +29,9 @@ it("gives a direct repair command for a stale service", () => {
);
});
it("explains where the service is supported", () => {
it("explains service availability without systemd", () => {
assert.include(
formatServiceStatus({ ...status, supported: false, installed: false }, "0.0.29"),
"Supported on: Linux with systemd, macOS with launchd",
"Supported on: Linux with systemd",
);
});
+3 -10
View File
@@ -1,4 +1,3 @@
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -49,7 +48,7 @@ export function formatServiceStatus(
cliVersion: string,
): string {
if (!status.supported) {
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";
return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd";
}
if (!status.installed) {
return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`.";
@@ -153,18 +152,12 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {
yield* Console.log("T3 Code is already set up to run in the background on this machine.");
return true;
}
// A LaunchAgent starts at login and dies at logout; there is no
// enable-linger equivalent on macOS. Do not promise more than that.
const platform = yield* HostProcessPlatform;
const wanted = yield* Prompt.run(
Prompt.confirm({
message: installed
? "The installed T3 Code service needs an update or repair. Update it now?"
: platform === "darwin"
? "Run T3 Code in the background whenever you log in to this Mac? " +
"It stays reachable through T3 Connect while you are logged in."
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
: "Run T3 Code in the background whenever this machine boots? " +
"It stays reachable through T3 Connect even after you log out.",
initial: true,
}),
);
+9 -7
View File
@@ -26,7 +26,6 @@ import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
checkConnectAuthCode,
connectCallbackUrl,
} from "@t3tools/shared/connectAuth";
@@ -367,6 +366,7 @@ export const make = Effect.gen(function* () {
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const hostedAppUrl = yield* hostedAppUrlConfig;
const { verifier, challenge, state } = yield* makePkceRequest;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
@@ -392,19 +392,21 @@ export const make = Effect.gen(function* () {
Layer.provide(
NodeHttpServer.layer(NodeHttp.createServer, {
host: "127.0.0.1",
port: 34338,
port: metadata.loopbackPort,
disablePreemptiveShutdown: true,
}),
),
Layer.build,
);
const authorizationUrl = buildConnectClerkAuthorizeUrl({
authorizationEndpoint: metadata.authorizationEndpoint,
clientId: metadata.clientId,
redirectUri: metadata.redirectUri,
scopes: metadata.scopes,
// The hosted /connect page establishes a Clerk session before forwarding
// the request to /oauth/authorize with the loopback redirect URI. Sending
// a signed-out browser to /oauth/authorize directly loses the authorize
// parameters across Clerk's sign-in redirect (#5051).
const authorizationUrl = buildConnectAuthorizeRequestUrl({
hostedAppUrl,
state,
challenge,
loopbackPort: metadata.loopbackPort,
});
yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
const authorization = yield* waitForLoopbackAuthorization({
+4 -143
View File
@@ -4,10 +4,8 @@ import {
HostProcessArguments,
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -49,51 +47,6 @@ it("survives the kernel OOM-killing a greedy agent child", () => {
expect(unit).toContain("OOMPolicy=continue");
});
const macPlan = {
nodePath: "/opt/homebrew/bin/node",
launcherPath: "/Users/theo/.t3/runtime/service-launcher.mjs",
baseDir: "/Users/theo/.t3",
logPath: "/Users/theo/.t3/userdata/logs/boot-service.log",
unitPath: "/Users/theo/Library/LaunchAgents/com.t3tools.t3code.service.plist",
};
it("keeps launchd pinned to the stable launcher rather than a versioned server", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain("<string>/opt/homebrew/bin/node</string>");
expect(plist).toContain("<string>/Users/theo/.t3/runtime/service-launcher.mjs</string>");
expect(plist).not.toContain("versions/1.2.3");
});
it("restarts the launch agent on the systemd cadence", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain("<key>RunAtLoad</key>\n <true/>");
expect(plist).toContain("<key>KeepAlive</key>\n <true/>");
expect(plist).toContain("<key>ThrottleInterval</key>\n <integer>5</integer>");
expect(plist).toContain("<key>ExitTimeOut</key>\n <integer>90</integer>");
});
it("appends both stdio streams to the boot service log", () => {
const plist = BootService.renderBootServicePlist(macPlan, { homeDir: "/Users/theo" });
expect(plist).toContain(
"<key>StandardOutPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
);
expect(plist).toContain(
"<key>StandardErrorPath</key>\n <string>/Users/theo/.t3/userdata/logs/boot-service.log</string>",
);
});
it("escapes XML in host paths", () => {
const plist = BootService.renderBootServicePlist(
{ ...macPlan, baseDir: "/Users/theo/T3 & <Co>" },
{ homeDir: "/Users/theo" },
);
expect(plist).toContain("<string>/Users/theo/T3 &amp; &lt;Co&gt;</string>");
});
const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
platform: NodeJS.Platform = "linux",
usePinnedLauncher = false,
@@ -115,14 +68,12 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
yield* fs.writeFileString(runtime.sentinelPath, "1.2.3\n");
const commands: string[] = [];
const timeouts = new Map<string, unknown>();
const control: { failCommand: string | undefined } = { failCommand: undefined };
const runner = ProcessRunner.ProcessRunner.of({
run: (input) =>
Effect.sync(() => {
const command = `${input.command} ${input.args.join(" ")}`;
commands.push(command);
timeouts.set(command, input.timeout);
return {
stdout: input.args[1] === "--version" ? "t3 v1.2.3\n" : "",
stderr: "",
@@ -148,20 +99,19 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* (
Effect.provide(
Layer.mergeAll(
Layer.succeed(HostProcessPlatform, platform),
Layer.succeed(HostProcessUserId, 501),
Layer.succeed(HostProcessExecutablePath, "/usr/bin/node"),
Layer.succeed(HostProcessArguments, ["/usr/bin/node", path.join(home, "bin.mjs")]),
ConfigProvider.layer(ConfigProvider.fromEnv({ env: { HOME: home } })),
),
),
);
return { service, fs, statePath, commands, timeouts, control };
return { service, fs, statePath, commands, control };
});
it.layer(NodeServices.layer)("boot service install", (it) => {
it.effect("installs, reports current state, and uninstalls", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands, timeouts } = yield* makeHarness();
const { service, fs, statePath, commands } = yield* makeHarness();
const plan = yield* service.install;
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
@@ -187,11 +137,6 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
// The stop can block up to systemd's 90s TimeoutStopSec; the runner's
// 60s default would cancel it mid-shutdown.
expect(timeouts.get("systemctl --user disable --now t3code.service")).toEqual(
Duration.seconds(120),
);
}),
);
@@ -250,95 +195,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => {
}),
);
it.effect("fails closed on Windows", () =>
it.effect("fails closed off Linux", () =>
Effect.gen(function* () {
const { service } = yield* makeHarness("win32");
const { service } = yield* makeHarness("darwin");
expect((yield* service.status).supported).toBe(false);
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUnsupportedError");
}),
);
it.effect("installs, reports current state, and uninstalls on macOS", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands, timeouts } = yield* makeHarness("darwin");
const plan = yield* service.install;
expect(plan.unitPath.endsWith("Library/LaunchAgents/com.t3tools.t3code.service.plist")).toBe(
true,
);
expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "1.2.3",
});
expect(yield* fs.readFileString(plan.launcherPath)).toBe("export {};\n");
expect((yield* service.status).current).toBe(true);
expect(yield* service.uninstall).toBe(true);
expect((yield* service.status).installed).toBe(false);
expect(commands.some((command) => command.startsWith("npm "))).toBe(false);
expect(commands.some((command) => command.startsWith("systemctl "))).toBe(false);
// A bootout can block up to the plist's 90s ExitTimeOut; the runner's
// 60s default would cancel it and let bootstrap race a loaded job.
expect(timeouts.get("launchctl bootout gui/501/com.t3tools.t3code.service")).toEqual(
Duration.seconds(120),
);
}),
);
it.effect("restarts the launch agent when repair fails", () =>
Effect.gen(function* () {
const { service, commands, control } = yield* makeHarness("darwin");
yield* service.install;
const plistPath = (yield* service.status).unitPath;
commands.length = 0;
control.failCommand = `launchctl bootstrap gui/501 ${plistPath}`;
const error = yield* service.install.pipe(Effect.flip);
expect(error._tag).toBe("BootServiceCommandError");
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
"launchctl bootout gui/501/com.t3tools.t3code.service",
"launchctl enable gui/501/com.t3tools.t3code.service",
`launchctl bootstrap gui/501 ${plistPath}`,
`launchctl bootstrap gui/501 ${plistPath}`,
]);
}),
);
it.effect("ignores a bootout for an agent that is not loaded", () =>
Effect.gen(function* () {
const { service, control } = yield* makeHarness("darwin");
yield* service.install;
control.failCommand = "launchctl bootout gui/501/com.t3tools.t3code.service";
yield* service.install;
expect((yield* service.status).current).toBe(true);
}),
);
it.effect("restarts without overwriting a pending remote update on macOS", () =>
Effect.gen(function* () {
const { service, fs, statePath, commands } = yield* makeHarness("darwin");
yield* service.install;
const plistPath = (yield* service.status).unitPath;
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned test document.
const pendingState = JSON.stringify({
protocol: SERVICE_LAUNCHER_PROTOCOL - 1,
activeVersion: "1.2.3",
update: {
id: "remote-update",
fromVersion: "1.2.3",
targetVersion: "1.2.4",
status: "pending",
},
});
yield* fs.writeFileString(statePath, pendingState);
commands.length = 0;
expect((yield* service.install.pipe(Effect.flip))._tag).toBe("BootServiceUpdatePendingError");
expect(serviceStateHasPendingUpdate(yield* fs.readFileString(statePath))).toBe(true);
expect(commands.filter((command) => command.startsWith("launchctl "))).toEqual([
"launchctl bootout gui/501/com.t3tools.t3code.service",
`launchctl bootstrap gui/501 ${plistPath}`,
]);
}),
);
});
+47 -310
View File
@@ -1,8 +1,4 @@
import {
HostProcessExecutablePath,
HostProcessPlatform,
HostProcessUserId,
} from "@t3tools/shared/hostProcess";
import { HostProcessExecutablePath, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
@@ -31,10 +27,6 @@ import {
const BOOT_SERVICE_NAME = "t3code";
export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;
// `.service` suffix keeps the label distinct from the desktop app's bundle id
// (com.t3tools.t3code), so launchd and TCC records never collide.
export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";
export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;
export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";
/** systemd expands `%` specifiers, including in unquoted append-log paths. */
@@ -91,276 +83,12 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
].join("\n");
}
/** Plist values are emitted as XML text nodes; only these three need escaping. */
export function escapeXmlText(value: string): string {
return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}
/** Pure renderer: launch agents cannot rely on the user's shell or PATH. */
export function renderBootServicePlist(
plan: BootServicePlan,
options: { readonly homeDir: string },
): string {
// KeepAlive + ThrottleInterval mirror Restart=always + RestartSec=5. launchd
// has no StartLimitBurst analog; a hard crash loop respawns every 5s forever.
// ExitTimeOut 90 matches systemd's default TimeoutStopSec. A plain stop
// completes within the launcher's 5s child grace, but a stop that queues
// behind an in-flight update transition can take much longer; launchd's
// system-defined default (5s on current macOS) would SIGKILL the launcher
// (and, with it, the process group) mid-handoff.
// ProcessType Interactive opts out of background-job resource throttling.
// AbandonProcessGroup stays at its default (false): launchd reaps leftover
// process-group members only when the launcher itself exits — the analog of
// KillMode=mixed's final cgroup kill — and not when the launcher restarts its
// child, so agent children survive server updates.
return [
`<?xml version="1.0" encoding="UTF-8"?>`,
`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
`<plist version="1.0">`,
`<dict>`,
` <key>Label</key>`,
` <string>${BOOT_SERVICE_LAUNCHD_LABEL}</string>`,
` <key>ProgramArguments</key>`,
` <array>`,
` <string>${escapeXmlText(plan.nodePath)}</string>`,
` <string>${escapeXmlText(plan.launcherPath)}</string>`,
` </array>`,
` <key>EnvironmentVariables</key>`,
` <dict>`,
` <key>T3CODE_HOME</key>`,
` <string>${escapeXmlText(plan.baseDir)}</string>`,
` <key>${BOOT_SERVICE_UNIT_ENV}</key>`,
` <string>${BOOT_SERVICE_PLIST_FILE}</string>`,
` </dict>`,
` <key>WorkingDirectory</key>`,
` <string>${escapeXmlText(options.homeDir)}</string>`,
` <key>RunAtLoad</key>`,
` <true/>`,
` <key>KeepAlive</key>`,
` <true/>`,
` <key>ThrottleInterval</key>`,
` <integer>5</integer>`,
` <key>ExitTimeOut</key>`,
` <integer>90</integer>`,
` <key>ProcessType</key>`,
` <string>Interactive</string>`,
` <key>StandardOutPath</key>`,
` <string>${escapeXmlText(plan.logPath)}</string>`,
` <key>StandardErrorPath</key>`,
` <string>${escapeXmlText(plan.logPath)}</string>`,
`</dict>`,
`</plist>`,
``,
].join("\n");
}
export interface BootServiceStep {
readonly step: string;
readonly command: string;
readonly args: ReadonlyArray<string>;
/**
* Non-zero exit is logged and ignored. Reserved for steps whose common
* failures (not loaded, already enabled) leave a state a later strict step
* either tolerates or fails loudly on.
*/
readonly optional?: boolean;
/** Override the ProcessRunner default (60s) for steps that block longer. */
readonly timeout?: Duration.Input;
}
/**
* Stop commands block until the service manager gives up: 90s by default for
* systemd's TimeoutStopSec, and ExitTimeOut=90 in the rendered plist. This
* must stay above both, or the runner cancels the stop mid-shutdown and the
* next step races a still-loaded service.
*/
const STOP_STEP_TIMEOUT = Duration.seconds(120);
/**
* Platform service-manager integration as data: paths, a pure renderer, and
* the command steps each flow runs. install/uninstall/status consume this and
* never branch on platform.
*/
export interface BootServiceManager {
readonly kind: "systemd" | "launchd";
readonly unitPath: string;
readonly render: (plan: BootServicePlan) => string;
/** Before rewriting files, when a unit is already installed. */
readonly stop: ReadonlyArray<BootServiceStep>;
/** After files are written. The last entry starts the service. */
readonly activate: ReadonlyArray<BootServiceStep>;
/** Best-effort recovery after a failed repair of an installed service. */
readonly restart: ReadonlyArray<BootServiceStep>;
/** Uninstall, before the unit file is removed. */
readonly deactivate: ReadonlyArray<BootServiceStep>;
/** Uninstall, after the unit file is removed. */
readonly finalize: ReadonlyArray<BootServiceStep>;
}
export function systemdManager(input: {
readonly path: Path.Path;
readonly homeDir: string;
}): BootServiceManager {
const unitPath = input.path.join(
input.homeDir,
".config",
"systemd",
"user",
BOOT_SERVICE_UNIT_FILE,
);
return {
kind: "systemd",
unitPath,
render: renderBootServiceUnit,
stop: [
{
step: "stopping the installed service",
command: "systemctl",
args: ["--user", "stop", BOOT_SERVICE_UNIT_FILE],
timeout: STOP_STEP_TIMEOUT,
},
],
activate: [
{
step: "reloading systemd user units",
command: "systemctl",
args: ["--user", "daemon-reload"],
},
{
step: "enabling the service",
command: "systemctl",
args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE],
},
{ step: "enabling lingering for this user", command: "loginctl", args: ["enable-linger"] },
// Start last. No administrative state write occurs after this succeeds.
{
step: "starting the service",
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
},
],
restart: [
{
step: "restarting the service after a failed update",
command: "systemctl",
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
},
],
deactivate: [
{
step: "stopping the service",
command: "systemctl",
args: ["--user", "disable", "--now", BOOT_SERVICE_UNIT_FILE],
timeout: STOP_STEP_TIMEOUT,
},
],
finalize: [
{
step: "reloading systemd user units",
command: "systemctl",
args: ["--user", "daemon-reload"],
},
],
};
}
export function launchdManager(input: {
readonly path: Path.Path;
readonly homeDir: string;
readonly uid: number;
}): BootServiceManager {
const unitPath = input.path.join(
input.homeDir,
"Library",
"LaunchAgents",
BOOT_SERVICE_PLIST_FILE,
);
const domainTarget = `gui/${input.uid}`;
const serviceTarget = `${domainTarget}/${BOOT_SERVICE_LAUNCHD_LABEL}`;
// bootout/enable are optional: they fail on not-loaded states that are fine
// to proceed from. The strict `bootstrap` runs last and is also the start:
// loading a RunAtLoad/KeepAlive plist starts the job, so a separate
// kickstart would kill and restart a server it just booted. A lingering job
// that survived bootout, or a gui domain with nobody logged in at the
// screen (SSH install), makes bootstrap fail the flow loudly rather than
// silently keeping a stale server.
return {
kind: "launchd",
unitPath,
render: (plan) => renderBootServicePlist(plan, { homeDir: input.homeDir }),
stop: [
{
step: "stopping the installed launch agent",
command: "launchctl",
args: ["bootout", serviceTarget],
optional: true,
timeout: STOP_STEP_TIMEOUT,
},
],
activate: [
// A persisted `launchctl disable` override refuses bootstrap; clear it.
{
step: "enabling the launch agent",
command: "launchctl",
args: ["enable", serviceTarget],
optional: true,
},
// Start last. No administrative state write occurs after this succeeds.
{
step: "starting the service",
command: "launchctl",
args: ["bootstrap", domainTarget, unitPath],
},
],
restart: [
{
step: "restarting the service after a failed update",
command: "launchctl",
args: ["bootstrap", domainTarget, unitPath],
},
],
// No `launchctl disable` here: a persisted override would sabotage a
// later reinstall. Removing the plist is what stops the next login load.
// A bootout that fails for a reason other than "not loaded" leaves the
// job running until logout; the failure is in the boot-service log.
deactivate: [
{
step: "stopping the service",
command: "launchctl",
args: ["bootout", serviceTarget],
optional: true,
timeout: STOP_STEP_TIMEOUT,
},
],
finalize: [],
};
}
/** Undefined means this host cannot run the background service. */
export function selectBootServiceManager(input: {
readonly platform: NodeJS.Platform;
readonly homeDir: string;
readonly uid: number | undefined;
readonly path: Path.Path;
}): BootServiceManager | undefined {
if (input.homeDir === "") {
return undefined;
}
if (input.platform === "linux") {
return systemdManager({ path: input.path, homeDir: input.homeDir });
}
if (input.platform === "darwin" && input.uid !== undefined) {
return launchdManager({ path: input.path, homeDir: input.homeDir, uid: input.uid });
}
return undefined;
}
export class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(
"BootServiceUnsupportedError",
{ platform: Schema.String },
) {
override get message(): string {
return `Background setup supports Linux with systemd and macOS with launchd; this machine reports '${this.platform}'.`;
return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;
}
}
@@ -435,15 +163,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}) {
const hostExecPath = yield* HostProcessExecutablePath;
const platform = yield* HostProcessPlatform;
const uid = yield* HostProcessUserId;
const homeDir = yield* Config.string("HOME").pipe(Config.withDefault(""));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runner = yield* ProcessRunner.ProcessRunner;
const host = input.host ?? { execPath: hostExecPath };
const detectedManager = selectBootServiceManager({ platform, homeDir, uid, path });
const unitPath = detectedManager?.unitPath ?? "";
const unitDir = path.join(homeDir, ".config", "systemd", "user");
const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);
const logPath = path.join(input.logsDir, "boot-service.log");
const launcherPath = path.join(input.baseDir, "runtime", SERVICE_LAUNCHER_FILE);
const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE);
@@ -471,11 +198,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
unitPath,
};
const requireManager = Effect.suspend(() =>
detectedManager === undefined
? new BootServiceUnsupportedError({ platform })
: Effect.succeed(detectedManager),
);
const requireSystemdLinux = Effect.gen(function* () {
if (platform !== "linux" || homeDir === "") {
return yield* new BootServiceUnsupportedError({ platform });
}
});
const runStep = Effect.fn("cloud.boot_service.run_step")(function* (
step: string,
@@ -508,25 +235,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
);
});
const runSteps = (steps: ReadonlyArray<BootServiceStep>) =>
Effect.forEach(
steps,
(entry) => {
const run = runStep(
entry.step,
entry.command,
entry.args,
entry.timeout === undefined ? undefined : { timeout: entry.timeout },
);
// runStep's tapError already appends the failure to the log, so an
// ignored optional step still leaves a trace.
return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid);
},
{ discard: true },
);
const install: BootService["Service"]["install"] = Effect.gen(function* () {
const manager = yield* requireManager;
yield* requireSystemdLinux;
yield* fs
.makeDirectory(input.logsDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
@@ -588,7 +298,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
if (installed) {
yield* runSteps(manager.stop);
yield* runStep("stopping the installed service", "systemctl", [
"--user",
"stop",
BOOT_SERVICE_UNIT_FILE,
]);
}
yield* Effect.gen(function* () {
@@ -602,7 +316,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
}
}
yield* fs
.makeDirectory(path.dirname(unitPath), { recursive: true })
.makeDirectory(unitDir, { recursive: true })
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* writeDurably(launcherPath, launcherSource);
yield* writeDurably(
@@ -617,35 +331,58 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
2,
)}\n`,
);
yield* writeDurably(unitPath, manager.render(plan));
yield* writeDurably(unitPath, renderBootServiceUnit(plan));
yield* runSteps(manager.activate);
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
yield* runStep("enabling the service", "systemctl", [
"--user",
"enable",
BOOT_SERVICE_UNIT_FILE,
]);
yield* runStep("enabling lingering for this user", "loginctl", ["enable-linger"]);
// Start last. No administrative state write occurs after this succeeds.
yield* runStep("starting the service", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]);
}).pipe(
Effect.tapError(() =>
installed ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void,
installed
? runStep("restarting the service after a failed update", "systemctl", [
"--user",
"restart",
BOOT_SERVICE_UNIT_FILE,
]).pipe(Effect.ignore)
: Effect.void,
),
);
return plan;
}).pipe(Effect.withSpan("cloud.boot_service.install"));
const uninstall: BootService["Service"]["uninstall"] = Effect.gen(function* () {
const manager = yield* requireManager;
yield* requireSystemdLinux;
if (
!(yield* fs
.exists(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))
)
return false;
yield* runSteps(manager.deactivate);
yield* runStep("stopping the service", "systemctl", [
"--user",
"disable",
"--now",
BOOT_SERVICE_UNIT_FILE,
]);
yield* fs
.remove(unitPath)
.pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));
yield* runSteps(manager.finalize);
yield* runStep("reloading systemd user units", "systemctl", ["--user", "daemon-reload"]);
return true;
}).pipe(Effect.withSpan("cloud.boot_service.uninstall"));
const status: BootService["Service"]["status"] = Effect.gen(function* () {
if (detectedManager === undefined) {
if (platform !== "linux" || homeDir === "") {
return { supported: false, installed: false, current: false, unitPath, logPath };
}
if (!(yield* fs.exists(unitPath))) {
@@ -664,7 +401,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: {
supported: true,
installed: true,
current:
unit === detectedManager.render(plan) &&
unit === renderBootServiceUnit(plan) &&
launcherExists &&
runtimeEntryExists &&
Option.isSome(runtimeSentinel) &&
+1 -2
View File
@@ -649,8 +649,7 @@ export const pendingServiceUpdateExists = Effect.gen(function* () {
});
// A pending update alone is not proof a replacement server is coming: an
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`,
// `launchctl bootout`) during
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
// the pending window also tears this server down. The launcher marks that case
// just before it signals the child, so pending + no marker is the handoff.
const pendingUpdateHandoffExists = Effect.gen(function* () {
+2 -2
View File
@@ -10,8 +10,8 @@ import * as ProcessRunner from "../processRunner.ts";
/**
* A pinned runtime is an exact `t3@<version>` npm-installed into
* <baseDir>/runtime/versions/<version>. The boot service points its unit or
* launch agent here, and server self-update installs the target version here before
* <baseDir>/runtime/versions/<version>. The boot service points its systemd
* unit here, and server self-update installs the target version here before
* switching over, never `npx t3`, whose cache is ephemeral and whose
* registry fetch at boot would make startup depend on the network.
*/
+1 -2
View File
@@ -90,9 +90,9 @@ it.effect("derives direct Clerk OAuth endpoints from statically injected public
}).pipe(provideEnv({}));
assert.deepEqual(config, {
authorizationEndpoint: "https://clerk.example.test/oauth/authorize",
tokenEndpoint: "https://clerk.example.test/oauth/token",
clientId: "oauth_client_embedded",
loopbackPort: 34338,
redirectUri: "http://127.0.0.1:34338/callback",
scopes: ["openid", "profile", "email"],
});
@@ -111,7 +111,6 @@ it.effect("prefers runtime Clerk OAuth config overrides over statically injected
}),
);
assert.equal(config.authorizationEndpoint, "https://runtime.example.test/oauth/authorize");
assert.equal(config.tokenEndpoint, "https://runtime.example.test/oauth/token");
assert.equal(config.clientId, "oauth_client_runtime");
}),
+15 -5
View File
@@ -1,4 +1,8 @@
import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
import {
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
DEFAULT_HOSTED_APP_URL,
} from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
@@ -14,7 +18,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;
const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
function validateRelayUrl(value: string) {
@@ -145,10 +149,16 @@ function makePublicValueConfig(name: string, fallback: string) {
);
}
/**
* The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes
* through the hosted /connect page, which builds the authorize URL after a
* Clerk session exists (see CliTokenManager.login). Only the token endpoint
* is contacted directly.
*/
export interface CloudCliOAuthConfig {
readonly authorizationEndpoint: string;
readonly tokenEndpoint: string;
readonly clientId: string;
readonly loopbackPort: number;
readonly redirectUri: string;
readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
}
@@ -184,10 +194,10 @@ export function makeCloudCliOAuthConfig({
Effect.map(
(clerkFrontendApiUrl) =>
({
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
clientId,
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
scopes: CLOUD_CLI_OAUTH_SCOPES,
}) satisfies CloudCliOAuthConfig,
),
@@ -12,6 +12,7 @@ import {
resolveCursorAcpConfigUpdates,
} from "../Layers/CursorProvider.ts";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
import { discoverCursorPluginDirectories } from "./CursorMcpServers.ts";
type CursorAcpRuntimeCursorSettings = Pick<CursorSettings, "apiEndpoint" | "binaryPath">;
@@ -46,6 +47,20 @@ export function buildCursorAcpSpawnInput(
};
}
export function addCursorPluginDirectories(
spawn: AcpSessionRuntime.AcpSpawnInput,
pluginDirectories: ReadonlyArray<string>,
): AcpSessionRuntime.AcpSpawnInput {
return {
...spawn,
args: [
...spawn.args.slice(0, -1),
...pluginDirectories.flatMap((path) => ["--plugin-dir", path]),
...spawn.args.slice(-1),
],
};
}
export const makeCursorAcpRuntime = (
input: CursorAcpRuntimeInput,
): Effect.Effect<
@@ -54,10 +69,14 @@ export const makeCursorAcpRuntime = (
Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const pluginDirectories = yield* discoverCursorPluginDirectories(
input.environment === undefined ? {} : { environment: input.environment },
);
const spawn = buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment);
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
...input,
spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment),
spawn: addCursorPluginDirectories(spawn, pluginDirectories),
authMethodId: "cursor_login",
clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
}).pipe(
@@ -0,0 +1,60 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { addCursorPluginDirectories, buildCursorAcpSpawnInput } from "./CursorAcpSupport.ts";
import { discoverCursorPluginDirectories } from "./CursorMcpServers.ts";
const writePlugin = Effect.fn("writePlugin")(function* (pluginsRoot: string, slug: string) {
const pluginRoot = NodePath.join(pluginsRoot, slug, "hash");
yield* Effect.promise(() =>
NodeFSP.mkdir(NodePath.join(pluginRoot, ".cursor-plugin"), { recursive: true }),
);
yield* Effect.promise(() =>
NodeFSP.writeFile(
NodePath.join(pluginRoot, ".cursor-plugin", "plugin.json"),
`{"name":"${slug}"}`,
),
);
yield* Effect.promise(() =>
NodeFSP.writeFile(NodePath.join(pluginRoot, "mcp.json"), '{"mcpServers":{}}'),
);
return pluginRoot;
});
describe("discoverCursorPluginDirectories", () => {
it.effect("returns cached Cursor plugins that provide MCP servers", () =>
Effect.gen(function* () {
const temp = yield* Effect.acquireRelease(
Effect.promise(() => NodeFSP.mkdtemp("/tmp/t3-cursor-mcp-")),
(path) => Effect.promise(() => NodeFSP.rm(path, { recursive: true, force: true })),
);
const pluginsRoot = NodePath.join(temp, "plugins", "cache", "cursor-public");
const paperRoot = yield* writePlugin(pluginsRoot, "paper-desktop");
const noMcpRoot = NodePath.join(pluginsRoot, "no-mcp", "hash");
yield* Effect.promise(() =>
NodeFSP.mkdir(NodePath.join(noMcpRoot, ".cursor-plugin"), { recursive: true }),
);
yield* Effect.promise(() =>
NodeFSP.writeFile(
NodePath.join(noMcpRoot, ".cursor-plugin", "plugin.json"),
'{"name":"no-mcp"}',
),
);
const directories = yield* discoverCursorPluginDirectories({ pluginsRoot });
expect(directories).toEqual([paperRoot]);
const spawn = buildCursorAcpSpawnInput(null, "/workspace");
expect(addCursorPluginDirectories(spawn, directories).args).toEqual([
"--plugin-dir",
paperRoot,
"acp",
]);
}).pipe(Effect.scoped),
);
});
@@ -0,0 +1,46 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import { Effect } from "effect";
interface DiscoverCursorPluginDirectoriesOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly homeDirectory?: string;
readonly pluginsRoot?: string;
}
function resolveHome(environment: NodeJS.ProcessEnv, explicit: string | undefined): string {
return explicit ?? environment.HOME ?? environment.USERPROFILE ?? "";
}
/** Finds cached Cursor plugins that declare MCP servers. */
export function discoverCursorPluginDirectories(
options: DiscoverCursorPluginDirectoriesOptions = {},
): Effect.Effect<ReadonlyArray<string>> {
return Effect.sync(() => {
const environment = options.environment ?? process.env;
const homeDirectory = resolveHome(environment, options.homeDirectory);
const pluginsRoot =
options.pluginsRoot ??
NodePath.join(homeDirectory, ".cursor", "plugins", "cache", "cursor-public");
if (!NodeFS.existsSync(pluginsRoot)) return [];
const directories: string[] = [];
for (const slug of NodeFS.readdirSync(pluginsRoot, { withFileTypes: true })) {
if (!slug.isDirectory()) continue;
const slugRoot = NodePath.join(pluginsRoot, slug.name);
for (const version of NodeFS.readdirSync(slugRoot, { withFileTypes: true })) {
if (!version.isDirectory()) continue;
const pluginRoot = NodePath.join(slugRoot, version.name);
if (
NodeFS.existsSync(NodePath.join(pluginRoot, "mcp.json")) ||
NodeFS.existsSync(NodePath.join(pluginRoot, ".mcp.json"))
) {
directories.push(pluginRoot);
}
}
}
return directories.sort();
});
}
+1 -3
View File
@@ -317,9 +317,7 @@ export class Launcher {
// This must happen synchronously at signal receipt. A queued update
// transition may already be terminating the active child, and that child
// needs to see the marker in its shutdown finalizer. KillMode=mixed also
// ensures systemd signals the launcher before the rest of the cgroup, and
// launchd signals only the job's main process (this launcher), so the
// marker lands before the child sees any signal on both platforms.
// ensures systemd signals the launcher before the rest of the cgroup.
try {
NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
} catch {
+16
View File
@@ -46,6 +46,22 @@ describe("connectCliAuth", () => {
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
});
it("redirects straight to the CLI's loopback listener when the request carries a port", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
const authorizeUrl = buildConnectCliClerkAuthorizeUrl({
state: "state-1",
challenge: "challenge-1",
loopbackPort: 34338,
});
expect(authorizeUrl).not.toBeNull();
const url = new URL(authorizeUrl!);
expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:34338/callback");
expect(url.searchParams.get("state")).toBe("state-1");
});
it("returns null when the CLI OAuth client id is not configured", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
expect(
+10 -1
View File
@@ -1,6 +1,7 @@
import {
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
type ConnectAuthorizeRequest,
} from "@t3tools/shared/connectAuth";
@@ -34,6 +35,11 @@ export function connectCliAuthRoutesEnabled(): boolean {
* Builds the Clerk authorize URL for a CLI-initiated connect request. The
* state is mirrored into sessionStorage so the callback page can verify the
* response matches a request this browser actually started.
*
* A request carrying a loopback port came from a CLI with a local callback
* listener: the authorization code must return to `127.0.0.1` directly, so
* the hosted callback page never sees it. Clerk enforces its registered
* redirect URI allowlist either way.
*/
export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
const { clerkPublishableKey } = resolveCloudPublicConfig();
@@ -44,7 +50,10 @@ export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeReques
return buildConnectClerkAuthorizeUrl({
authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
clientId,
redirectUri: connectCallbackUrl(configuredHostedAppUrl()),
redirectUri:
request.loopbackPort === undefined
? connectCallbackUrl(configuredHostedAppUrl())
: connectLoopbackRedirectUri(request.loopbackPort),
scopes: CONNECT_OAUTH_SCOPES,
state: request.state,
challenge: request.challenge,
+10 -2
View File
@@ -10,7 +10,7 @@ import {
import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
@@ -147,6 +147,14 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
// that would otherwise refresh a render-time snapshot.
const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
const resetSidebarWidth = () => {
try {
removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
} catch (error) {
console.error("Could not clear persisted thread sidebar width.", error);
}
setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
};
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
return isMacosDesktop && typeof getWindowFullscreenState === "function"
@@ -225,7 +233,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
) : (
<ThreadSidebar />
)}
<SidebarRail />
<SidebarRail onDoubleClick={resetSidebarWidth} />
</Sidebar>
{children}
<SidebarControl />
+8
View File
@@ -480,6 +480,14 @@ function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
// The right-panel surface launcher claims its shortcut letters while it is
// visible (data attribute set in RightPanelTabs); those keys open surfaces
// instead of typing into the composer.
const launcherKeys = document
.querySelector("[data-surface-launcher-keys]")
?.getAttribute("data-surface-launcher-keys");
if (launcherKeys && launcherKeys.toLowerCase().includes(event.key.toLowerCase())) return false;
return true;
}
+203 -58
View File
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import {
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type ReactElement,
type ReactNode,
@@ -25,6 +26,7 @@ import type { RightPanelSurface } from "~/rightPanelStore";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { Kbd } from "~/components/ui/kbd";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
@@ -88,6 +90,28 @@ const SURFACE_DISABLED_REASONS = {
agents: "Agents are only available from a thread.",
} as const;
/** Overlays that must win over the launcher's letter shortcuts. */
const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
'[data-slot="dialog-popup"]',
'[data-slot="alert-dialog-popup"]',
'[data-slot="command-dialog-popup"]',
'[data-slot="menu-popup"]',
'[data-slot="select-popup"]',
'[data-slot="popover-popup"]',
'[data-slot="combobox-popup"]',
'[data-slot="autocomplete-popup"]',
].join(",");
/** One-line unavailability hints for the empty-state cards. */
const SURFACE_UNAVAILABLE_HINTS = {
browser: "Only available in the desktop app.",
terminal: "Available when a project is open.",
files: "Available when a project is open.",
diff: "Available for Git repositories.",
pullRequest: "No pull request on this branch yet.",
agents: "Available from a thread.",
} as const;
type TabContextMenuAction = "copy-path" | "close" | "close-others" | "close-to-right" | "close-all";
function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
@@ -118,6 +142,13 @@ function SurfaceMenuItem(props: {
return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
}
/**
* Card launcher shown when the right panel has no surfaces. Keyboard-first
* without palette chrome: a surface's letter opens it directly from anywhere
* outside a typing context, and arrows plus Enter work while the launcher is
* focused. The highlight only appears on hover or arrow use. Unavailable
* surfaces stay visible with a one-line reason.
*/
function RightPanelEmptyState(props: {
onAddBrowser: () => void;
onAddTerminal: () => void;
@@ -133,13 +164,17 @@ function RightPanelEmptyState(props: {
agentsAvailable: boolean;
liveAgentCount: number;
}) {
// -1 means no highlight: it only appears on hover or arrow use.
const [highlight, setHighlight] = useState(-1);
const actions = [
{
label: "Browser",
description: "Open a local app or URL.",
icon: Globe2,
shortcut: "B",
available: props.browserAvailable,
disabledReason: SURFACE_DISABLED_REASONS.browser,
disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
onClick: props.onAddBrowser,
badgeCount: 0,
},
@@ -147,8 +182,9 @@ function RightPanelEmptyState(props: {
label: "Terminal",
description: "Start a shell in this workspace.",
icon: TerminalSquare,
shortcut: "T",
available: props.terminalAvailable,
disabledReason: SURFACE_DISABLED_REASONS.terminal,
disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
onClick: props.onAddTerminal,
badgeCount: 0,
},
@@ -156,8 +192,9 @@ function RightPanelEmptyState(props: {
label: "Files",
description: "Browse and read workspace files.",
icon: Files,
shortcut: "F",
available: props.filesAvailable,
disabledReason: SURFACE_DISABLED_REASONS.files,
disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
onClick: props.onAddFiles,
badgeCount: 0,
},
@@ -165,91 +202,199 @@ function RightPanelEmptyState(props: {
label: "Diff",
description: "Review changes in this thread.",
icon: FileDiff,
shortcut: "D",
available: props.diffAvailable,
disabledReason: SURFACE_DISABLED_REASONS.diff,
disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
onClick: props.onAddDiff,
badgeCount: 0,
},
{
label: "Pull request",
description: "Open the pull request for this thread's branch.",
description: "Open this branch's pull request.",
icon: GitPullRequest,
shortcut: "P",
available: props.pullRequestAvailable,
disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
onClick: props.onAddPullRequest,
badgeCount: 0,
},
{
label: "Agents",
description: "Watch subagents and workflows run.",
description: "Follow subagents and workflows.",
icon: Bot,
shortcut: "A",
available: props.agentsAvailable,
disabledReason: SURFACE_DISABLED_REASONS.agents,
disabledReason: SURFACE_UNAVAILABLE_HINTS.agents,
onClick: props.onAddAgents,
badgeCount: props.liveAgentCount,
},
] as const;
type SurfaceAction = (typeof actions)[number];
const availableActions = actions.filter((action) => action.available);
const highlightIndex =
availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
// Letter shortcuts work while the launcher is visible, not only while it
// is focused; focus moves around too easily (stray clicks) to carry them.
// Capture phase so app-level key handlers cannot swallow the event first;
// typing contexts and already-handled events are left alone.
const shortcutActionsRef = useRef(availableActions);
useEffect(() => {
shortcutActionsRef.current = availableActions;
});
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (event.defaultPrevented || event.isComposing) return;
if (event.metaKey || event.ctrlKey || event.altKey) return;
if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
const target = event.target;
if (target instanceof HTMLElement) {
if (target.closest("input, textarea, select")) return;
// An empty contenteditable (the chat composer at rest) does not
// count as typing; letters only become text once a draft exists.
const editable = target.isContentEditable ? target : target.closest("[contenteditable]");
if (editable && (editable.textContent ?? "").trim().length > 0) return;
}
const action = shortcutActionsRef.current.find(
(candidate) => candidate.shortcut.toLowerCase() === event.key.toLowerCase(),
);
if (!action) return;
event.preventDefault();
event.stopPropagation();
action.onClick();
};
window.addEventListener("keydown", handler, true);
return () => window.removeEventListener("keydown", handler, true);
}, []);
const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
if (availableActions.length === 0) return;
if (event.key === "ArrowDown" || event.key === "ArrowRight") {
event.preventDefault();
setHighlight((highlightIndex + 1) % availableActions.length);
return;
}
if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
event.preventDefault();
setHighlight(
highlightIndex === -1
? availableActions.length - 1
: (highlightIndex - 1 + availableActions.length) % availableActions.length,
);
return;
}
if (event.key === "Enter") {
// A focused card button owns its own activation; only open from the
// highlight when the container itself has focus.
if (event.target instanceof HTMLElement && event.target.closest("button")) return;
const action = availableActions[highlightIndex];
if (!action) return;
event.preventDefault();
action.onClick();
}
};
// Stable identity so React only runs this callback ref on mount/unmount;
// an inline arrow would re-attach and re-focus on every render.
const focusOnMount = useCallback((node: HTMLDivElement | null) => {
node?.focus();
}, []);
const isHighlighted = (action: SurfaceAction) =>
highlightIndex !== -1 && availableActions[highlightIndex] === action;
const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
const Icon = action.icon;
return (
<span className="relative inline-flex shrink-0">
<Icon className={iconClassName} />
{action.badgeCount > 0 ? (
<span
aria-hidden
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
>
{action.badgeCount}
</span>
) : null}
</span>
);
};
const cardShellClass =
"rounded-lg border border-border/80 bg-card dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5";
const highlightedCardClass = "bg-accent/60 dark:inset-ring-white/20";
return (
<div className="flex min-h-0 flex-1 items-center justify-center p-6">
<div className="w-full max-w-xl">
<div className="mb-5 text-center">
<h3 className="text-sm font-medium text-foreground">Open a surface</h3>
<p className="mt-1 text-xs text-muted-foreground">
<div
ref={focusOnMount}
tabIndex={0}
onKeyDown={handleKeyDown}
aria-label="Open a surface"
data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
className={cn(
"flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 pt-6 outline-none",
// The panel topbar sits above this container; matching bottom padding
// keeps the cards centered against the full panel, not the leftover.
"pb-[calc(var(--workspace-topbar-height)+--spacing(6))]",
)}
>
<div className="relative w-full max-w-lg">
<div className="absolute inset-x-0 bottom-full mb-5 text-center">
<h3 className="font-medium text-foreground text-sm">Open a surface</h3>
<p className="mt-1 text-muted-foreground text-xs">
Choose what to show in the right panel.
</p>
</div>
<div className="grid grid-cols-2 gap-2">
{actions.map((action) => {
const Icon = action.icon;
const content = (
<>
<span className="relative mb-3 inline-flex">
<Icon className="size-5" />
{action.badgeCount > 0 ? (
<span
aria-hidden
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
>
{action.badgeCount}
</span>
) : null}
{actions.map((action) =>
action.available ? (
<button
key={action.label}
type="button"
onClick={action.onClick}
onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
onMouseLeave={() =>
setHighlight((current) =>
current === availableActions.indexOf(action) ? -1 : current,
)
}
className={cn(
"relative flex w-full cursor-pointer flex-col items-start p-4 text-left transition hover:border-border hover:bg-accent/60",
cardShellClass,
isHighlighted(action) && highlightedCardClass,
)}
>
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
<span className="flex items-center gap-2 pe-8">
{actionIcon(action)}
<span className="font-medium text-sm">{action.label}</span>
</span>
<span className="text-sm font-medium">{action.label}</span>
<span className="mt-1 text-xs leading-relaxed text-muted-foreground">
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
{action.description}
</span>
</>
);
if (action.available) {
return (
<button
key={action.label}
type="button"
onClick={action.onClick}
className="cursor-pointer flex min-h-28 w-full flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left transition hover:border-border hover:bg-accent/60 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
>
{content}
</button>
);
}
const disabledCard = (
<button
type="button"
className="flex min-h-28 w-full cursor-not-allowed flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left opacity-40 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
aria-disabled="true"
>
{content}
</button>
);
return (
<DisabledReasonTooltip
) : (
<div
key={action.label}
reason={action.disabledReason}
trigger={disabledCard}
/>
);
})}
className={cn(
"relative flex w-full flex-col items-start p-4 opacity-40",
cardShellClass,
)}
>
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
<span className="flex items-center gap-2 pe-8">
{actionIcon(action)}
<span className="font-medium text-sm">{action.label}</span>
</span>
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
{action.disabledReason}
</span>
</div>
),
)}
</div>
</div>
</div>
@@ -23,6 +23,14 @@ describe("ChangedFilesCard", () => {
expect(markup).toContain('data-changed-files-state="expanded"');
expect(markup).toContain('aria-expanded="true"');
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain(
'class="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden',
);
expect(markup).toContain('class="flex shrink-0 items-center gap-1 whitespace-nowrap');
expect(markup).toContain('class="ml-1 hidden min-w-0 flex-1 truncate');
expect(markup).toContain("@[24rem]/changed-files:inline");
expect(markup).not.toContain("sm:inline");
expect(markup).toContain('class="flex shrink-0 items-center gap-1.5"');
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all folders"');
@@ -56,7 +56,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
return (
<div
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
className="@container/changed-files mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
data-changed-files-state={
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
}
@@ -73,7 +73,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
type="button"
aria-expanded={expanded}
data-scroll-anchor-ignore
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onExpandedChange(!expanded)}
>
<ChevronRightIcon
@@ -83,7 +83,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
expanded && "rotate-90",
)}
/>
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span className="flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
</span>
@@ -96,11 +96,11 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
/>
)}
</span>
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
<span className="ml-1 hidden min-w-0 flex-1 truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 @[24rem]/changed-files:inline">
{expanded ? "Hide files" : "Show files"}
</span>
</button>
<div className="flex items-center gap-1.5">
<div className="flex shrink-0 items-center gap-1.5">
{expanded ? (
<Tooltip>
<TooltipTrigger
@@ -142,7 +142,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
}
>
<FileDiffIcon className="size-3" />
<span className="hidden sm:inline">Open diff</span>
<span className="hidden @[24rem]/changed-files:inline">Open diff</span>
</TooltipTrigger>
<TooltipPopup side="top">Open the full diff</TooltipPopup>
</Tooltip>
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vite-plus/test";
import {
EMBER_THEME,
GROVE_THEME,
IRIS_THEME,
OCEAN_THEME,
T3_CHAT_THEME,
themeColorToHex,
type ThemeColors,
} from "../../themePalette";
import { clerkAppearance } from "./clerkAppearance";
function contrastRatio(first: string, second: string): number {
const toRgb = (value: string) => {
const hex = themeColorToHex(value)?.slice(1, 7);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return [0, 1, 2].map(
(channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
);
};
const luminance = (value: string) =>
toRgb(value)
.map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
.reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
const lighter = Math.max(luminance(first), luminance(second));
const darker = Math.min(luminance(first), luminance(second));
return (lighter + 0.05) / (darker + 0.05);
}
function mixThemeColors(first: string, second: string, firstWeight: number): string {
const channels = [first, second].map((value) => {
const hex = themeColorToHex(value)?.slice(1, 7);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return [0, 1, 2].map((channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16));
});
const mixed = channels[0]!.map((channel, index) =>
Math.round(channel * firstWeight + channels[1]![index]! * (1 - firstWeight)),
);
return `#${mixed.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
}
const builtInThemeModes = [
T3_CHAT_THEME,
GROVE_THEME,
OCEAN_THEME,
EMBER_THEME,
IRIS_THEME,
].flatMap((theme) =>
[theme.colors, theme.variants?.dark].filter((colors): colors is ThemeColors => !!colors),
);
describe("clerkAppearance", () => {
it("maps theme colors without overriding Clerk's component structure", () => {
expect(clerkAppearance).toEqual({
variables: {
colorPrimary: "var(--update-foreground)",
colorPrimaryForeground: "var(--card)",
colorDanger: "var(--error)",
colorSuccess: "var(--success)",
colorWarning: "var(--warning)",
colorNeutral: "var(--foreground)",
colorForeground: "var(--foreground)",
colorMuted: "color-mix(in srgb, var(--card) 98%, var(--foreground))",
colorMutedForeground: "var(--muted-foreground)",
colorBackground: "var(--card)",
colorInputForeground: "var(--foreground)",
colorInput: "var(--secondary)",
colorRing: "var(--ring)",
},
elements: {
formFieldErrorText: { color: "var(--error-foreground)" },
formFieldWarningText: { color: "var(--warning-foreground)" },
formFieldSuccessText: { color: "var(--success-foreground)" },
otpCodeFieldErrorText: { color: "var(--error-foreground)" },
otpCodeFieldSuccessText: { color: "var(--success-foreground)" },
},
});
});
it.each(builtInThemeModes)("keeps Clerk text readable across a built-in palette", (colors) => {
const mutedSurface = mixThemeColors(colors.surface, colors.text, 0.98);
expect(contrastRatio(colors.text, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.mutedForeground, mutedSurface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.text, colors.secondary)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.updateForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.errorForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.warningForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
});
});
@@ -0,0 +1,34 @@
import type { ClerkProviderProps } from "@clerk/react";
/** Keeps Clerk's stock component structure while binding its color system to
* the live T3 Code palette. CSS variables make theme changes propagate to
* portaled sign-in and profile surfaces without remounting Clerk. */
export const clerkAppearance = {
variables: {
// Clerk reuses its primary color for filled buttons and bare links. The
// app's update foreground is the palette's action hue cast for readable
// text, while the card surface provides the inverse filled-control pair.
colorPrimary: "var(--update-foreground)",
colorPrimaryForeground: "var(--card)",
colorDanger: "var(--error)",
colorSuccess: "var(--success)",
colorWarning: "var(--warning)",
colorNeutral: "var(--foreground)",
colorForeground: "var(--foreground)",
// The stock dark theme's muted token is translucent. Clerk uses this as
// the footer's background, so derive an opaque muted surface from the card.
colorMuted: "color-mix(in srgb, var(--card) 98%, var(--foreground))",
colorMutedForeground: "var(--muted-foreground)",
colorBackground: "var(--card)",
colorInputForeground: "var(--foreground)",
colorInput: "var(--secondary)",
colorRing: "var(--ring)",
},
elements: {
formFieldErrorText: { color: "var(--error-foreground)" },
formFieldWarningText: { color: "var(--warning-foreground)" },
formFieldSuccessText: { color: "var(--success-foreground)" },
otpCodeFieldErrorText: { color: "var(--error-foreground)" },
otpCodeFieldSuccessText: { color: "var(--success-foreground)" },
},
} satisfies NonNullable<ClerkProviderProps["appearance"]>;
@@ -44,8 +44,10 @@ const invalidLinkMessage = {
} as const;
/**
* /connect: the URL a headless CLI prints. Waits for a Clerk session, then
* forwards the CLI's PKCE request to Clerk's authorize endpoint.
* /connect: the URL the CLI prints for both flows. Waits for a Clerk session,
* then forwards the CLI's PKCE request to Clerk's authorize endpoint — with a
* loopback redirect URI when the request carries a port, so the code returns
* straight to the waiting CLI, and the hosted callback page otherwise.
*/
export function ConnectCliAuthorizeSurface() {
const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
@@ -85,7 +87,11 @@ export function ConnectCliAuthorizeSurface() {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 1 of 2 · Browser authorization"
eyebrow={
request.loopbackPort === undefined
? "Step 1 of 2 · Browser authorization"
: "Browser authorization"
}
title="Connecting your terminal"
description={
isSignedIn
@@ -18,7 +18,7 @@ function ReleaseNotesLink({
}) {
return (
<button
className="ml-2 inline-flex cursor-pointer items-center gap-1 align-baseline text-muted-foreground underline decoration-dotted underline-offset-4 transition-colors hover:text-foreground"
className="ml-2 inline cursor-pointer text-muted-foreground underline decoration-dotted underline-offset-4 transition-colors hover:text-foreground"
onClick={() => {
void (async () => {
try {
@@ -32,7 +32,11 @@ function ReleaseNotesLink({
type="button"
>
Read more
<ArrowRightIcon aria-hidden className="size-3 -rotate-45" strokeWidth={2.25} />
<ArrowRightIcon
aria-hidden
className="ml-1 inline size-3 -rotate-45 align-[-0.125em]"
strokeWidth={2.25}
/>
</button>
);
}
+1 -1
View File
@@ -33,7 +33,7 @@ function TooltipPopup({
<TooltipPrimitive.Positioner
align={align}
anchor={anchor}
className="pointer-events-none z-70 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
className="pointer-events-none z-[140] h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
data-slot="tooltip-positioner"
side={side}
sideOffset={sideOffset}
@@ -5,6 +5,7 @@ import {
openPullRequestLink,
parseChangeRequestUrl,
PullRequestLinkOpenError,
shouldOpenPullRequestExternally,
} from "./openPullRequestLink";
describe("openPullRequestLink", () => {
@@ -34,6 +35,17 @@ describe("openPullRequestLink", () => {
});
});
describe("shouldOpenPullRequestExternally", () => {
it("uses the browser for command-click and control-click", () => {
expect(shouldOpenPullRequestExternally({ metaKey: true, ctrlKey: false })).toBe(true);
expect(shouldOpenPullRequestExternally({ metaKey: false, ctrlKey: true })).toBe(true);
});
it("keeps an unmodified click in the pull request view", () => {
expect(shouldOpenPullRequestExternally({ metaKey: false, ctrlKey: false })).toBe(false);
});
});
describe("parseChangeRequestUrl", () => {
it("reads a GitHub pull request", () => {
expect(parseChangeRequestUrl("https://github.com/T3Tools/T3Code/pull/123")).toEqual({
+11 -1
View File
@@ -173,10 +173,19 @@ export function findProjectForChangeRequest(
* should still be reading it afterwards. Any change request opens there, not only the thread's
* own, since the panel is told which one to show.
*/
export function shouldOpenPullRequestExternally(
event: Pick<MouseEvent<HTMLElement>, "metaKey" | "ctrlKey">,
): boolean {
return event.metaKey || event.ctrlKey;
}
export function useOpenChangeRequestLink(
threadRef?: ScopedThreadRef,
): (
event: Pick<MouseEvent<HTMLElement>, "preventDefault" | "stopPropagation">,
event: Pick<
MouseEvent<HTMLElement>,
"preventDefault" | "stopPropagation" | "metaKey" | "ctrlKey"
>,
targetUrl: string,
targetThreadRef?: ScopedThreadRef,
) => boolean {
@@ -186,6 +195,7 @@ export function useOpenChangeRequestLink(
const primaryEnvironmentId = usePrimaryEnvironmentId();
return useCallback(
(event, targetUrl, targetThreadRef) => {
if (shouldOpenPullRequestExternally(event)) return false;
const resolvedThreadRef = targetThreadRef ?? threadRef;
const environmentId = resolvedThreadRef?.environmentId ?? primaryEnvironmentId;
if (
+7 -2
View File
@@ -16,6 +16,7 @@ import {
syncDocumentWindowControlsOverlayClass,
} from "./lib/windowControlsOverlay";
import { AppRoot } from "./AppRoot";
import { clerkAppearance } from "./components/clerk/clerkAppearance";
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
const history = isElectron ? createHashHistory() : createBrowserHistory();
@@ -35,11 +36,15 @@ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
{clerkPublishableKey && hasCloudPublicConfig() ? (
isElectron ? (
<ElectronClerkProvider publishableKey={clerkPublishableKey} passkeys={passkeys}>
<ElectronClerkProvider
appearance={clerkAppearance}
publishableKey={clerkPublishableKey}
passkeys={passkeys}
>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</ElectronClerkProvider>
) : (
<ClerkProvider publishableKey={clerkPublishableKey}>
<ClerkProvider appearance={clerkAppearance} publishableKey={clerkPublishableKey}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</ClerkProvider>
)
@@ -0,0 +1,20 @@
// @effect-diagnostics nodeBuiltinImport:off - Regression coverage compares the onboarding header with the shared titlebar contract.
import * as NodeFS from "node:fs";
import { describe, expect, it } from "vite-plus/test";
describe("hosted static onboarding header", () => {
it("uses the shared workspace topbar geometry", () => {
const routeSource = NodeFS.readFileSync(new URL("./_chat.index.tsx", import.meta.url), "utf8");
const onboardingStart = routeSource.indexOf("function HostedStaticOnboardingState()");
const onboardingEnd = routeSource.indexOf('<Empty className="flex-1">', onboardingStart);
expect(onboardingStart).toBeGreaterThanOrEqual(0);
expect(onboardingEnd).toBeGreaterThan(onboardingStart);
const onboardingHeader = routeSource.slice(onboardingStart, onboardingEnd);
expect(onboardingHeader).toContain("workspace-topbar");
expect(onboardingHeader).not.toMatch(/(?:^|\s)(?:[\w-]+:)*py-/);
});
});
+1 -1
View File
@@ -145,7 +145,7 @@ function HostedStaticOnboardingState() {
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<header
className={cn(
"border-b border-border px-3 py-2 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5 sm:py-3",
"workspace-topbar border-b border-border px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
+6 -7
View File
@@ -2,15 +2,14 @@
> For maintainers. Using T3 Code? See [docs/user](../user/).
Remote server updates use one stable launcher selected by the platform service manager (systemd on
Linux, launchd on macOS). Foreground CLI processes do not self-update, and a running server never
edits its service definition or durable service state.
Remote server updates use one stable systemd launcher. Foreground CLI processes do not self-update,
and a running server never edits its systemd unit or durable service state.
## Ownership
The service files under `<baseDir>/runtime` are:
- `service-launcher.mjs`, the stable process selected by the service manager;
- `service-launcher.mjs`, the stable process selected by systemd;
- `service-state.json`, the launcher's durable selection state;
- `versions/<version>`, immutable exact-version npm installs.
@@ -23,7 +22,7 @@ The state contains one active version and, at most, one update record:
- `pending A → B` selects B as a retryable trial;
- `committed A → B` selects B for ordinary restarts;
- `rolled-back A → B` or `failed A → B` selects A;
- invalid state fails closed so the service manager cannot guess at a runtime.
- invalid state fails closed so systemd cannot guess at a runtime.
Every write uses same-directory replacement plus file and directory fsync.
@@ -51,8 +50,8 @@ operations. It only opens prepared gates and publishes prepared lifecycle state.
The launcher serializes child exits, IPC messages, and timers. A trial must report prepared within
120 seconds. If the trial exits or times out before prepared, the launcher stops it, restores the
snapshot, records rollback, and starts A. A durable restore marker makes an interrupted restore
resume before either version can boot. After commit, B is active and the service manager's normal
restart policy applies.
resume before either version can boot. After commit, B is active and normal systemd restart policy
applies.
## Database Rollback
+11 -3
View File
@@ -90,9 +90,17 @@ In **Clerk Dashboard > OAuth applications**:
5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
environment to the generated public client ID.
The CLI derives Clerk's frontend API URL from the publishable key and calls Clerk's
`/oauth/authorize` and `/oauth/token` endpoints directly. The relay is not involved in the OAuth
handshake; it only validates the issued Clerk bearer token when the CLI manages an environment link.
Both CLI flows start at the hosted `/connect` page (`buildConnectAuthorizeRequestUrl` in
`packages/shared/src/connectAuth.ts`), which waits for a Clerk session and then forwards the request
to Clerk's `/oauth/authorize`. The CLI never opens `/oauth/authorize` directly: a signed-out browser
sent there goes through Clerk's sign-in redirect, which drops the authorize query parameters and
fails the flow with `unsupported_response_type` or an empty `state` (#5051). The loopback flow marks
the request with a `port` fragment parameter so the hosted page asks Clerk to redirect the
authorization code straight to `http://127.0.0.1:<port>/callback`; the out-of-band flow omits it and
uses the hosted `/connect/callback` page instead. The CLI derives Clerk's frontend API URL from the
publishable key and calls only the `/oauth/token` endpoint directly. The relay is not involved in
the OAuth handshake; it only validates the issued Clerk bearer token when the CLI manages an
environment link.
The connect command group is:
+11 -35
View File
@@ -1,7 +1,7 @@
# Running T3 Code in the Background
On Linux and macOS, T3 Code can run as a background service for your user, so it is ready without
keeping a terminal open.
On a Linux host, T3 Code can run as a background service for your user. It starts when the machine
boots and keeps running after you log out.
## Manage the Service
@@ -32,42 +32,18 @@ npx t3@latest service uninstall
Updating restarts T3 Code briefly. Let active agent work and terminal commands finish first.
If a remote update is already in progress, wait for it to finish before retrying a local update.
The service runs a small stable launcher. Exact T3 Code versions are installed separately, so a
failed remote candidate can return to the previous version without rewriting the service
definition. The launcher snapshots the database before a remote candidate starts, so database
updates roll back with the server version. An older launcher may require one local
`service update` before this is available.
## Platform Support
**Linux** uses a systemd user unit at `~/.config/systemd/user/t3code.service`. The service starts
when the machine boots and keeps running after you log out (lingering is enabled during install).
**macOS** uses a launch agent at `~/Library/LaunchAgents/com.t3tools.t3code.service.plist`. It
starts when you log in, not when the Mac boots, and it stops when you log out; macOS has no
equivalent of Linux lingering for user agents. For a Mac that should stay reachable unattended,
turn on automatic login (System Settings → Users & Groups; unavailable while FileVault is on) and
keep the Mac from sleeping.
Two more macOS notes:
- Installing over SSH needs someone logged in at the Mac's screen to start the agent right away.
Without that, the install command reports an error at the final start step, but the agent is
fully installed and starts at the next login.
- macOS may show privacy prompts for protected folders such as Desktop, Documents, or Downloads,
attributed to a bare `node` process, or deny access without a prompt. If agent work fails to
read those folders, grant Full Disk Access to the node binary listed in the launch agent's
`ProgramArguments`.
- The agent appears under System Settings → General → Login Items. If it was switched off there,
or disabled with `launchctl disable`, macOS will not start it at login until you switch it back
on.
**Windows** is not supported yet.
The systemd unit runs a small stable launcher. Exact T3 Code versions are installed separately, so
a failed remote candidate can return to the previous version without rewriting the unit. The
launcher snapshots the database before a remote candidate starts, so database updates roll back
with the server version. An older launcher may require one local `service update` before this is
available.
## Using It with T3 Connect
T3 Connect may offer to install the service during setup so the host stays reachable in the
background. This is only an onboarding shortcut: the service and T3 Connect are managed separately.
T3 Connect may offer to install the service during setup so the host stays reachable after you log
out. This is only an onboarding shortcut: the service and T3 Connect are managed separately.
Signing out of T3 Connect does not remove the service. Use `t3 service uninstall` when you no longer
want T3 Code to start in the background.
The background service currently requires Linux with systemd.
+26
View File
@@ -4,6 +4,7 @@ import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
connectLoopbackRedirectUri,
encodeConnectAuthCode,
parseConnectAuthCode,
readConnectAuthorizeRequest,
@@ -37,6 +38,31 @@ describe("connectAuth", () => {
).toBeNull();
});
it("round-trips the loopback port through the authorize URL fragment", () => {
const url = buildConnectAuthorizeRequestUrl({
hostedAppUrl: "https://app.t3.codes",
state: "state-1",
challenge: "challenge-1",
loopbackPort: 34338,
});
expect(readConnectAuthorizeRequest(new URL(url))).toEqual({
state: "state-1",
challenge: "challenge-1",
loopbackPort: 34338,
});
expect(connectLoopbackRedirectUri(34338)).toBe("http://127.0.0.1:34338/callback");
});
it("rejects authorize requests whose loopback port is corrupted", () => {
for (const port of ["", "abc", "-1", "0", "65536", "34338x", "34 38"]) {
const url = new URL(
`https://app.t3.codes/connect#state=state-1&challenge=challenge-1&port=${encodeURIComponent(port)}`,
);
expect(readConnectAuthorizeRequest(url), port).toBeNull();
}
});
it("builds a PKCE authorize URL against the Clerk endpoint", () => {
const url = new URL(
buildConnectClerkAuthorizeUrl({
+50 -4
View File
@@ -2,7 +2,9 @@ import { readHashParams } from "./remote.ts";
const CONNECT_AUTH_STATE_PARAM = "state";
const CONNECT_AUTH_CHALLENGE_PARAM = "challenge";
const CONNECT_AUTH_PORT_PARAM = "port";
const CONNECT_AUTH_CODE_SEPARATOR = ".";
const CONNECT_LOOPBACK_CALLBACK_PATH = "/callback";
const CONNECT_AUTHORIZE_PATH = "/connect";
const CONNECT_CALLBACK_PATH = "/connect/callback";
@@ -23,22 +25,39 @@ export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
export interface ConnectAuthorizeRequest {
readonly state: string;
readonly challenge: string;
/**
* Present when a loopback CLI initiated the request: the hosted /connect
* page then asks Clerk to redirect the authorization code straight to
* `http://127.0.0.1:<port>/callback` instead of the hosted callback page.
*/
readonly loopbackPort?: number;
}
/**
* The URL a headless CLI prints for the user to open on a machine with a
* browser. `state` and `code_challenge` ride the fragment so they never reach
* the hosted app's server or CDN logs; neither is a secret.
* The URL the CLI prints for the user to open in a browser. `state` and
* `code_challenge` ride the fragment so they never reach the hosted app's
* server or CDN logs; neither is a secret.
*
* Both CLI flows route through the hosted /connect page rather than hitting
* Clerk's /oauth/authorize directly: a signed-out browser sent straight to
* /oauth/authorize goes through Clerk's sign-in redirect, which does not
* reliably preserve the authorize query parameters (state, response_type,
* code_challenge). The hosted page waits for a Clerk session first, then
* forwards the request with the parameters intact.
*/
export function buildConnectAuthorizeRequestUrl(input: {
readonly hostedAppUrl: string;
readonly state: string;
readonly challenge: string;
readonly loopbackPort?: number;
}): string {
const url = new URL(CONNECT_AUTHORIZE_PATH, input.hostedAppUrl);
url.hash = new URLSearchParams([
[CONNECT_AUTH_STATE_PARAM, input.state],
[CONNECT_AUTH_CHALLENGE_PARAM, input.challenge],
...(input.loopbackPort === undefined
? []
: [[CONNECT_AUTH_PORT_PARAM, String(input.loopbackPort)] as [string, string]]),
]).toString();
return url.toString();
}
@@ -50,7 +69,34 @@ export function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest |
if (!state || !challenge) {
return null;
}
return { state, challenge };
const port = params.get(CONNECT_AUTH_PORT_PARAM);
if (port === null) {
return { state, challenge };
}
// A present-but-invalid port means the link was corrupted; reject the whole
// request rather than silently downgrading a loopback flow to the
// out-of-band one, which would strand the waiting CLI.
const loopbackPort = parseLoopbackPort(port.trim());
if (loopbackPort === null) {
return null;
}
return { state, challenge, loopbackPort };
}
function parseLoopbackPort(value: string): number | null {
if (!/^\d{1,5}$/.test(value)) {
return null;
}
const port = Number(value);
return port >= 1 && port <= 65535 ? port : null;
}
/**
* Redirect URI for the CLI's local callback listener. Must stay in sync with
* the redirect URI registered on the Clerk CLI OAuth application.
*/
export function connectLoopbackRedirectUri(port: number): string {
return `http://127.0.0.1:${port}${CONNECT_LOOPBACK_CALLBACK_PATH}`;
}
export function connectCallbackUrl(hostedAppUrl: string): string {
-8
View File
@@ -51,12 +51,4 @@ export const HostProcessArguments = Context.Reference<ReadonlyArray<string>>(
},
);
/** Undefined on platforms without POSIX uids (Windows). */
export const HostProcessUserId = Context.Reference<number | undefined>(
"@t3tools/shared/hostProcess/HostProcessUserId",
{
defaultValue: () => process.getuid?.(),
},
);
export const isHostWindows = Effect.map(HostProcessPlatform, (platform) => platform === "win32");