Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16eedd9473 | ||
|
|
972740d55c | ||
|
|
96b5f889cd | ||
|
|
8d24b5131f | ||
|
|
770946d026 | ||
|
|
8601797233 | ||
|
|
b73232bdd3 | ||
|
|
f131228a59 | ||
|
|
e321667b10 | ||
|
|
849bac8946 | ||
|
|
6fd088af9f | ||
|
|
b54bfc9312 | ||
|
|
e1378a1f4d |
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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -24,6 +24,7 @@ import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
@@ -953,6 +954,69 @@ it.layer(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses platform utility paths for POSIX subprocess polling", () =>
|
||||
Effect.gen(function* () {
|
||||
const calls: ProcessRunner.ProcessRunInput[] = [];
|
||||
const runner = ProcessRunner.ProcessRunner.of({
|
||||
run: (input) => {
|
||||
calls.push(input);
|
||||
const stdout =
|
||||
input.args[0] === "-P"
|
||||
? "10001\n"
|
||||
: input.args[0] === "-eo"
|
||||
? "10001 9000\n"
|
||||
: input.args.includes("comm=")
|
||||
? ""
|
||||
: "/usr/bin/node\n";
|
||||
return Effect.succeed({
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(0),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const { manager } = yield* createManager(5, { subprocessPollIntervalMs: 20 }).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, runner),
|
||||
Effect.provide(withHostPlatform("darwin")),
|
||||
);
|
||||
yield* manager.open(openInput());
|
||||
yield* waitFor(
|
||||
Effect.sync(() => calls.length >= 4),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
expect(calls.slice(0, 4).map(({ command }) => command)).toEqual([
|
||||
"/usr/bin/pgrep",
|
||||
"/bin/ps",
|
||||
"/bin/ps",
|
||||
"/bin/ps",
|
||||
]);
|
||||
|
||||
yield* manager.close({ threadId: "thread-1" });
|
||||
calls.length = 0;
|
||||
|
||||
const { manager: linuxManager } = yield* createManager(5, {
|
||||
subprocessPollIntervalMs: 20,
|
||||
}).pipe(
|
||||
Effect.provideService(ProcessRunner.ProcessRunner, runner),
|
||||
Effect.provide(withHostPlatform("linux")),
|
||||
);
|
||||
yield* linuxManager.open(openInput());
|
||||
yield* waitFor(
|
||||
Effect.sync(() => calls.length >= 4),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
expect(calls.slice(0, 4).map(({ command }) => command)).toEqual(["pgrep", "ps", "ps", "ps"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("caps persisted history to configured line limit", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager(3);
|
||||
|
||||
@@ -703,9 +703,12 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func
|
||||
ProcessRunner.ProcessRunner
|
||||
> {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
// Absolute paths avoid libuv's per-PATH-entry posix_spawn search on macOS.
|
||||
const pgrepCommand = platform === "darwin" ? "/usr/bin/pgrep" : "pgrep";
|
||||
const psCommand = platform === "darwin" ? "/bin/ps" : "ps";
|
||||
const runPgrep = processRunner
|
||||
.run({
|
||||
command: "pgrep",
|
||||
command: pgrepCommand,
|
||||
args: ["-P", String(terminalPid)],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 32_768,
|
||||
@@ -725,7 +728,7 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func
|
||||
|
||||
const runPs = processRunner
|
||||
.run({
|
||||
command: "ps",
|
||||
command: psCommand,
|
||||
args: ["-eo", "pid=,ppid="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 262_144,
|
||||
@@ -776,7 +779,7 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func
|
||||
}
|
||||
|
||||
const runComm = processRunner.run({
|
||||
command: "ps",
|
||||
command: psCommand,
|
||||
args: ["-p", String(childPid), "-o", "comm="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 8_192,
|
||||
@@ -792,7 +795,7 @@ const posixInspectSubprocess = Effect.fn("terminal.posixInspectSubprocess")(func
|
||||
|
||||
if (!rawComm || rawComm.length === 0) {
|
||||
const runArgs = processRunner.run({
|
||||
command: "ps",
|
||||
command: psCommand,
|
||||
args: ["-p", String(childPid), "-o", "args="],
|
||||
timeout: "1 second",
|
||||
maxOutputBytes: 16_384,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,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 />
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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-/);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user