Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

UI fixes

Julius Marmingece96ad0b61b5
diff --git a/apps/server/src/open.test.ts b/apps/server/src/open.test.ts
new file mode 100644
index 000000000..f4b88d052
--- /dev/null
+++ b/apps/server/src/open.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+
+import { launchDetached, resolveEditorLaunch } from "./open";
+
+describe("resolveEditorLaunch", () => {
+ it("returns cursor command for cursor editor", () => {
+ expect(resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "cursor" }, "darwin")).toEqual({
+ command: "cursor",
+ args: ["/tmp/workspace"],
+ });
+ });
+
+ it("maps file-manager editor to OS open commands", () => {
+ expect(resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "file-manager" }, "darwin")).toEqual(
+ {
+ command: "open",
+ args: ["/tmp/workspace"],
+ },
+ );
+ expect(resolveEditorLaunch({ cwd: "C:\\workspace", editor: "file-manager" }, "win32")).toEqual(
+ {
+ command: "explorer",
+ args: ["C:\\workspace"],
+ },
+ );
+ expect(resolveEditorLaunch({ cwd: "/tmp/workspace", editor: "file-manager" }, "linux")).toEqual(
+ {
+ command: "xdg-open",
+ args: ["/tmp/workspace"],
+ },
+ );
+ });
+});
+
+describe("launchDetached", () => {
+ it("resolves when command can be spawned", async () => {
+ await expect(launchDetached(process.execPath, ["-e", "process.exit(0)"])).resolves.toBe(
+ undefined,
+ );
+ });
+
+ it("rejects when command does not exist", async () => {
+ await expect(
+ launchDetached(`t3code-no-such-command-${Date.now()}`, []),
+ ).rejects.toBeInstanceOf(Error);
+ });
+});
diff --git a/apps/server/src/open.ts b/apps/server/src/open.ts
index 91b63cf04..1d8c875af 100644
--- a/apps/server/src/open.ts
+++ b/apps/server/src/open.ts
@@ -2,7 +2,6 @@ import { spawn } from "node:child_process";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
-import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
message: Schema.String,
@@ -26,7 +25,7 @@ export interface OpenShape {
export class Open extends ServiceMap.Service<Open, OpenShape>()("server/Open") {}
-function resolveEditorLaunch(
+export function resolveEditorLaunch(
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): EditorLaunch {
@@ -53,9 +52,25 @@ function resolveEditorLaunch(
}
}
+export function launchDetached(command: string, args: ReadonlyArray<string>): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, [...args], {
+ detached: true,
+ stdio: "ignore",
+ });
+
+ const handleSpawn = () => {
+ child.unref();
+ resolve();
+ };
+
+ child.once("spawn", handleSpawn);
+ child.once("error", (error) => reject(error));
+ });
+}
+
const make = Effect.gen(function* () {
const open = yield* Effect.promise(() => import("open"));
- const { spawn } = yield* ChildProcessSpawner.ChildProcessSpawner;
return {
openBrowser: (target) =>
@@ -64,14 +79,16 @@ const make = Effect.gen(function* () {
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) =>
- Effect.gen(function* () {
- const launch = resolveEditorLaunch(input);
- const child = yield* spawn(ChildProcess.make(launch.command, launch.args));
- yield* Effect.forkDetach(child.exitCode);
- }).pipe(
- Effect.catch((error) => Effect.logError("Failed to open editor", { cause: error })),
- Effect.scoped,
- ),
+ Effect.tryPromise({
+ try: () => {
+ const launch = resolveEditorLaunch(input);
+ return launchDetached(launch.command, launch.args);
+ },
+ catch: (cause) =>
+ cause instanceof OpenError
+ ? cause
+ : new OpenError({ message: "Failed to open editor", cause }),
+ }),
} satisfies OpenShape;
});
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index e8e2b9d85..91972d787 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -1,20 +1,43 @@
-import { memo } from "react";
+import { memo, useMemo } from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
import remarkGfm from "remark-gfm";
+import { useNativeApi } from "../hooks/useNativeApi";
+import { resolveMarkdownFileLinkTarget } from "../markdown-links";
+import { preferredTerminalEditor } from "../terminal-links";
interface ChatMarkdownProps {
text: string;
+ cwd: string | undefined;
}
-const markdownComponents: Components = {
- a({ node: _node, ...props }) {
- return <a {...props} target="_blank" rel="noreferrer" />;
- },
-};
+function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
+ const api = useNativeApi();
+ const markdownComponents = useMemo<Components>(
+ () => ({
+ a({ node: _node, href, ...props }) {
+ const targetPath = resolveMarkdownFileLinkTarget(href, cwd);
+ if (!targetPath || !api) {
+ return <a {...props} href={href} target="_blank" rel="noreferrer" />;
+ }
+
+ return (
+ <a
+ {...props}
+ href={href}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ void api.shell.openInEditor(targetPath, preferredTerminalEditor());
+ }}
+ />
+ );
+ },
+ }),
+ [api, cwd],
+ );
-function ChatMarkdown({ text }: ChatMarkdownProps) {
return (
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
<ReactMarkdown
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 150ae0a3e..8272223ae 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -344,7 +344,10 @@ interface ChatViewProps {
export default function ChatView({ threadId }: ChatViewProps) {
const { state, dispatch } = useStore();
const navigate = useNavigate();
- const rawSearch = useSearch({ strict: false });
+ const rawSearch = useSearch({
+ strict: false,
+ select: (params) => parseDiffRouteSearch(params),
+ });
const api = useNativeApi();
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
@@ -387,6 +390,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
const diffOpen = diffSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
+
+ useEffect(() => {
+ if (!activeThread?.id) return;
+ if (!activeThread.latestTurnCompletedAt) return;
+ const turnCompletedAt = Date.parse(activeThread.latestTurnCompletedAt);
+ if (Number.isNaN(turnCompletedAt)) return;
+ const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
+ if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
+
+ dispatch({
+ type: "MARK_THREAD_VISITED",
+ threadId: activeThread.id,
+ });
+ }, [
+ activeThread?.id,
+ activeThread?.lastVisitedAt,
+ activeThread?.latestTurnCompletedAt,
+ dispatch,
+ ]);
+
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
);
@@ -799,47 +822,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
keybinding?: string | null;
keybindingCommand: string;
}) => {
- dispatch({
- type: "SET_PROJECT_SCRIPTS",
- projectId: input.projectId,
+ if (!api) return;
+
+ await api.orchestration.dispatchCommand({
+ type: "project.meta.update",
+ commandId: newCommandId(),
+ projectId: asProjectId(input.projectId),
scripts: input.nextScripts,
});
- if (!api) return;
- try {
- await api.orchestration.dispatchCommand({
- type: "project.meta.update",
- commandId: newCommandId(),
- projectId: asProjectId(input.projectId),
- scripts: input.nextScripts,
+ if (isElectron && input.keybinding) {
+ const keybindingUpdate = await api.server.upsertKeybinding({
+ key: input.keybinding,
+ command: input.keybindingCommand,
});
-
- if (isElectron && input.keybinding) {
- const keybindingUpdate = await api.server.upsertKeybinding({
- key: input.keybinding,
- command: input.keybindingCommand,
- });
- queryClient.setQueryData(
- serverQueryKeys.config(),
- (current: { cwd: string; keybindings: ResolvedKeybindingsConfig } | undefined) =>
- current
- ? { ...current, keybindings: keybindingUpdate.keybindings }
- : {
- cwd: input.projectCwd,
- keybindings: keybindingUpdate.keybindings,
+ queryClient.setQueryData(
+ serverQueryKeys.config(),
+ (current: { cwd: string; keybindings: ResolvedKeybindingsConfig } | undefined) =>
+ current
+ ? { ...current, keybindings: keybindingUpdate.keybindings }
+ : {
+ cwd: input.projectCwd,
+ keybindings: keybindingUpdate.keybindings,
},
- );
- }
- } catch (error) {
- dispatch({
- type: "SET_PROJECT_SCRIPTS",
- projectId: input.projectId,
- scripts: input.previousScripts,
- });
- throw error;
+ );
}
},
- [api, dispatch, queryClient],
+ [api, queryClient],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput) => {
@@ -1338,15 +1347,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setIsRevertingCheckpoint(false);
}
},
- [
- activeThread,
- api,
- isConnecting,
- isRevertingCheckpoint,
- isSending,
- phase,
- setThreadError,
- ],
+ [activeThread, api, isConnecting, isRevertingCheckpoint, isSending, phase, setThreadError],
);
const onSend = async (e: FormEvent) => {
@@ -1425,7 +1426,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
try {
const turnAttachments = await Promise.all(
composerImagesSnapshot.map(
- async (image): Promise<{
+ async (
+ image,
+ ): Promise<{
type: "image";
name: string;
mimeType: string;
@@ -1749,12 +1752,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
onRevertUserMessage={onRevertUserMessage}
isRevertingCheckpoint={isRevertingCheckpoint}
onImageExpand={onExpandTimelineImage}
+ markdownCwd={gitCwd ?? undefined}
/>
</div>
{/* Input bar */}
<div className={cn("px-3 pt-1.5 sm:px-5 sm:pt-2", isGitRepo ? "pb-1" : "pb-3 sm:pb-4")}>
- <form onSubmit={onSend} className="mx-auto w-full max-w-3xl">
+ <form
+ onSubmit={onSend}
+ className="mx-auto w-full min-w-fit max-w-3xl"
+ data-chat-composer-form="true"
+ >
<div
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring ${
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border"
@@ -1853,7 +1861,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* Bottom toolbar */}
<div className="flex flex-wrap items-center justify-between gap-2 px-2.5 pb-2.5 sm:flex-nowrap sm:gap-0 sm:px-3 sm:pb-3">
- <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:overflow-visible">
+ <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible">
{/* Model picker */}
<ModelPicker model={selectedModel} onModelChange={onModelSelect} />
@@ -1869,7 +1877,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
{/* Runtime mode toggle */}
<Button
variant="ghost"
- className="shrink-0 px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
+ className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
size="sm"
type="button"
disabled={isSwitchingRuntimeMode}
@@ -2075,19 +2083,19 @@ const ChatHeader = memo(function ChatHeader({
onToggleDiff,
}: ChatHeaderProps) {
return (
- <div className="flex min-w-0 flex-1 items-center justify-between gap-2">
- <div className="flex min-w-0 items-center gap-2 sm:gap-3">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
- <h2 className="truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
+ <h2 className="min-w-0 shrink truncate text-sm font-medium text-foreground" title={activeThreadTitle}>
{activeThreadTitle}
</h2>
{activeProjectName && (
- <Badge variant="outline" className="max-w-28 truncate sm:max-w-none">
+ <Badge variant="outline" className="max-w-28 shrink-0 truncate">
{activeProjectName}
</Badge>
)}
</div>
- <div className="flex shrink-0 items-center gap-2 sm:gap-3">
+ <div className="@container/header-actions flex min-w-0 flex-1 items-center justify-end gap-2 @sm/header-actions:gap-3">
{activeProjectScripts && (
<ProjectScriptsControl
scripts={activeProjectScripts}
@@ -2221,6 +2229,7 @@ interface MessagesTimelineProps {
onRevertUserMessage: (messageId: string) => void;
isRevertingCheckpoint: boolean;
onImageExpand: (image: ExpandedImagePreview) => void;
+ markdownCwd: string | undefined;
}
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
@@ -2256,6 +2265,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
onRevertUserMessage,
isRevertingCheckpoint,
onImageExpand,
+ markdownCwd,
}: MessagesTimelineProps) {
const rows = useMemo<TimelineRow[]>(() => {
const nextRows: TimelineRow[] = [];
@@ -2448,7 +2458,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
</div>
)}
{row.message.text && (
- <pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-foreground">
+ <pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
{row.message.text}
</pre>
)}
@@ -2490,7 +2500,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
</div>
)}
<div className="min-w-0 px-1 py-0.5">
- <ChatMarkdown text={messageText} />
+ <ChatMarkdown text={messageText} cwd={markdownCwd} />
{(() => {
const turnSummary = turnDiffSummaryByAssistantMessageId.get(
row.message.id,
@@ -2567,7 +2577,9 @@ const MessagesTimeline = memo(function MessagesTimeline({
<span className="ml-1 text-muted-foreground/70">(</span>
<span className="text-success">+{stat.additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
- <span className="text-destructive">-{stat.deletions}</span>
+ <span className="text-destructive">
+ -{stat.deletions}
+ </span>
<span className="text-muted-foreground/70">)</span>
</>
);
@@ -2728,9 +2740,11 @@ const OpenInPicker = memo(function OpenInPicker({
<Group aria-label="Subscription actions">
<Button size="xs" variant="outline" onClick={() => openInEditor(lastEditor)}>
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
- <span className="sr-only sm:not-sr-only sm:ml-0.5">Open</span>
+ <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
+ Open
+ </span>
</Button>
- <GroupSeparator className="hidden sm:block" />
+ <GroupSeparator className="hidden @sm/header-actions:block" />
<Menu>
<MenuTrigger render={<Button aria-label="Copy options" size="icon-xs" variant="outline" />}>
<ChevronDownIcon aria-hidden="true" className="size-4" />
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx
index 065008158..38658c728 100644
--- a/apps/web/src/components/DiffPanel.tsx
+++ b/apps/web/src/components/DiffPanel.tsx
@@ -75,7 +75,7 @@ function formatTurnChipTimestamp(isoDate: string): string {
}
interface DiffPanelProps {
- mode?: "inline" | "sheet";
+ mode?: "inline" | "sheet" | "sidebar";
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
@@ -271,7 +271,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
updateTurnStripScrollState();
const onScroll = () => updateTurnStripScrollState();
-
+
element.addEventListener("scroll", onScroll, { passive: true });
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
@@ -297,10 +297,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
}, [selectedTurn?.turnId, selectedTurnId]);
- const shouldUseDragRegion = isElectron && mode === "inline";
+ const shouldUseDragRegion = isElectron && mode !== "sheet";
return (
- <aside
+ <div
className={cn(
"flex h-full min-w-0 flex-col bg-card",
mode === "inline"
@@ -308,18 +308,19 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
: "w-full",
)}
>
- <div
- className={cn(
- "flex items-center justify-between gap-2 border-b border-border px-4",
- shouldUseDragRegion ? "drag-region h-[52px]" : "py-3",
- )}
- >
- <div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
+ <div className="border-b border-border">
+ <div
+ className={cn(
+ "flex h-12 items-center justify-between gap-2 px-4",
+ shouldUseDragRegion ? "drag-region" : undefined,
+ )}
+ >
+ <div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
{canScrollTurnStripLeft && (
- <div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-gradient-to-r from-card to-transparent" />
+ <div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-linear-to-r from-card to-transparent" />
)}
{canScrollTurnStripRight && (
- <div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-gradient-to-l from-card to-transparent" />
+ <div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-linear-to-l from-card to-transparent" />
)}
<button
type="button"
@@ -402,26 +403,27 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</button>
))}
</div>
+ </div>
+ <ToggleGroup
+ className="shrink-0 [-webkit-app-region:no-drag]"
+ variant="outline"
+ size="xs"
+ value={[diffRenderMode]}
+ onValueChange={(value) => {
+ const next = value[0];
+ if (next === "stacked" || next === "split") {
+ setDiffRenderMode(next);
+ }
+ }}
+ >
+ <Toggle aria-label="Stacked diff view" value="stacked">
+ <Rows3Icon className="size-3" />
+ </Toggle>
+ <Toggle aria-label="Split diff view" value="split">
+ <Columns2Icon className="size-3" />
+ </Toggle>
+ </ToggleGroup>
</div>
- <ToggleGroup
- className="shrink-0 [-webkit-app-region:no-drag]"
- variant="outline"
- size="xs"
- value={[diffRenderMode]}
- onValueChange={(value) => {
- const next = value[0];
- if (next === "stacked" || next === "split") {
- setDiffRenderMode(next);
- }
- }}
- >
- <Toggle aria-label="Stacked diff view" value="stacked">
- <Rows3Icon className="size-3" />
- </Toggle>
- <Toggle aria-label="Split diff view" value="split">
- <Columns2Icon className="size-3" />
- </Toggle>
- </ToggleGroup>
</div>
{!activeThread ? (
@@ -488,6 +490,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</div>
</>
)}
- </aside>
+ </div>
);
}
diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx
index 4b2879476..af88bc800 100644
--- a/apps/web/src/components/GitActionsControl.tsx
+++ b/apps/web/src/components/GitActionsControl.tsx
@@ -136,11 +136,7 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
return <InfoIcon className={iconClassName} />;
}
-export default function GitActionsControl({
- api,
- gitCwd,
- activeThreadId,
-}: GitActionsControlProps) {
+export default function GitActionsControl({ api, gitCwd, activeThreadId }: GitActionsControlProps) {
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
@@ -501,7 +497,9 @@ export default function GitActionsControl({
}
>
<GitQuickActionIcon quickAction={quickAction} />
- <span className="sr-only sm:not-sr-only sm:ml-0.5">{quickAction.label}</span>
+ <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
+ {quickAction.label}
+ </span>
</PopoverTrigger>
<PopoverPopup tooltipStyle side="bottom" align="start">
{quickActionDisabledReason}
@@ -515,10 +513,12 @@ export default function GitActionsControl({
onClick={runQuickAction}
>
<GitQuickActionIcon quickAction={quickAction} />
- <span className="sr-only sm:not-sr-only sm:ml-0.5">{quickAction.label}</span>
+ <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
+ {quickAction.label}
+ </span>
</Button>
)}
- <GroupSeparator className="hidden sm:block" />
+ <GroupSeparator className="hidden @sm/header-actions:block" />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitQueries(queryClient);
diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx
index 067ae5792..2217a9098 100644
--- a/apps/web/src/components/ProjectScriptsControl.tsx
+++ b/apps/web/src/components/ProjectScriptsControl.tsx
@@ -266,9 +266,11 @@ export default function ProjectScriptsControl({
title={`Run ${primaryScript.name}`}
>
<ScriptIcon icon={primaryScript.icon} />
- <span className="sr-only sm:not-sr-only sm:ml-0.5">{primaryScript.name}</span>
+ <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
+ {primaryScript.name}
+ </span>
</Button>
- <GroupSeparator className="hidden sm:block" />
+ <GroupSeparator className="hidden @sm/header-actions:block" />
<Menu highlightItemOnHover={false}>
<MenuTrigger
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
@@ -329,7 +331,9 @@ export default function ProjectScriptsControl({
) : (
<Button size="xs" variant="outline" onClick={openAddDialog} title="Add action">
<PlusIcon className="size-3.5" />
- <span className="sr-only sm:not-sr-only sm:ml-0.5">Add action</span>
+ <span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
+ Add action
+ </span>
</Button>
)}
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 4ebcf0541..566b38691 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -33,7 +33,6 @@ import {
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
- SidebarRail,
SidebarSeparator,
SidebarTrigger,
} from "./ui/sidebar";
@@ -710,8 +709,6 @@ export default function Sidebar() {
</button>
)}
</SidebarFooter>
-
- <SidebarRail />
</>
);
}
diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx
index fbe2308f6..c3bdf6576 100644
--- a/apps/web/src/components/ui/sidebar.tsx
+++ b/apps/web/src/components/ui/sidebar.tsx
@@ -25,6 +25,7 @@ const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "calc(100vw - var(--spacing(3)))";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
+const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
type SidebarContextProps = {
state: "expanded" | "collapsed";
@@ -36,7 +37,43 @@ type SidebarContextProps = {
toggleSidebar: () => void;
};
+type SidebarResizableOptions = {
+ maxWidth?: number;
+ minWidth?: number;
+ onResize?: (width: number) => void;
+ shouldAcceptWidth?: (context: {
+ currentWidth: number;
+ nextWidth: number;
+ rail: HTMLButtonElement;
+ side: "left" | "right";
+ sidebarRoot: HTMLElement;
+ wrapper: HTMLElement;
+ }) => boolean;
+ storageKey?: string;
+};
+
+type SidebarResolvedResizableOptions = {
+ maxWidth: number;
+ minWidth: number;
+ onResize?: (width: number) => void;
+ shouldAcceptWidth?: (context: {
+ currentWidth: number;
+ nextWidth: number;
+ rail: HTMLButtonElement;
+ side: "left" | "right";
+ sidebarRoot: HTMLElement;
+ wrapper: HTMLElement;
+ }) => boolean;
+ storageKey: string | null;
+};
+
+type SidebarInstanceContextProps = {
+ resizable: SidebarResolvedResizableOptions | null;
+ side: "left" | "right";
+};
+
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
+const SidebarInstanceContext = React.createContext<SidebarInstanceContextProps | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
@@ -149,6 +186,7 @@ function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
+ resizable = false,
className,
children,
...props
@@ -156,98 +194,123 @@ function Sidebar({
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
+ resizable?: boolean | SidebarResizableOptions;
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
+ const resolvedResizable = React.useMemo<SidebarResolvedResizableOptions | null>(() => {
+ if (isMobile || collapsible === "none" || !resizable) {
+ return null;
+ }
+
+ const options = typeof resizable === "boolean" ? {} : resizable;
+ return {
+ maxWidth: options.maxWidth ?? Number.POSITIVE_INFINITY,
+ minWidth: options.minWidth ?? SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH,
+ onResize: options.onResize,
+ shouldAcceptWidth: options.shouldAcceptWidth,
+ storageKey: options.storageKey ?? null,
+ };
+ }, [collapsible, isMobile, resizable]);
+ const instanceContextValue = React.useMemo<SidebarInstanceContextProps>(
+ () => ({ side, resizable: resolvedResizable }),
+ [resolvedResizable, side],
+ );
if (collapsible === "none") {
return (
- <div
- className={cn(
- "flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
- className,
- )}
- data-slot="sidebar"
- {...props}
- >
- {children}
- </div>
- );
- }
-
- if (isMobile) {
- return (
- <Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
- <SheetPopup
+ <SidebarInstanceContext.Provider value={instanceContextValue}>
+ <div
className={cn(
- "w-(--sidebar-width) max-w-none bg-sidebar p-0 text-sidebar-foreground",
+ "flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
className,
)}
- data-mobile="true"
- data-sidebar="sidebar"
data-slot="sidebar"
- showCloseButton={false}
- side={side}
- style={
- {
- "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
- } as React.CSSProperties
- }
+ {...props}
>
- <SheetHeader className="sr-only">
- <SheetTitle>Sidebar</SheetTitle>
- <SheetDescription>Displays the mobile sidebar.</SheetDescription>
- </SheetHeader>
- <div className="flex h-full w-full flex-col">{children}</div>
- </SheetPopup>
- </Sheet>
+ {children}
+ </div>
+ </SidebarInstanceContext.Provider>
+ );
+ }
+
+ if (isMobile) {
+ return (
+ <SidebarInstanceContext.Provider value={instanceContextValue}>
+ <Sheet onOpenChange={setOpenMobile} open={openMobile} {...props}>
+ <SheetPopup
+ className={cn(
+ "w-(--sidebar-width) max-w-none bg-sidebar p-0 text-sidebar-foreground",
+ className,
+ )}
+ data-mobile="true"
+ data-sidebar="sidebar"
+ data-slot="sidebar"
+ showCloseButton={false}
+ side={side}
+ style={
+ {
+ "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
+ } as React.CSSProperties
+ }
+ >
+ <SheetHeader className="sr-only">
+ <SheetTitle>Sidebar</SheetTitle>
+ <SheetDescription>Displays the mobile sidebar.</SheetDescription>
+ </SheetHeader>
+ <div className="flex h-full w-full flex-col">{children}</div>
+ </SheetPopup>
+ </Sheet>
+ </SidebarInstanceContext.Provider>
);
}
return (
- <div
- className="group peer hidden text-sidebar-foreground md:block"
- data-collapsible={state === "collapsed" ? collapsible : ""}
- data-side={side}
- data-slot="sidebar"
- data-state={state}
- data-variant={variant}
- >
- {/* This is what handles the sidebar gap on desktop */}
+ <SidebarInstanceContext.Provider value={instanceContextValue}>
<div
- className={cn(
- "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
- "group-data-[collapsible=offcanvas]:w-0",
- "group-data-[side=right]:rotate-180",
- variant === "floating" || variant === "inset"
- ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
- )}
- data-slot="sidebar-gap"
- />
- <div
- className={cn(
- "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
- side === "left"
- ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
- : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
- // Adjust the padding for floating and inset variants.
- variant === "floating" || variant === "inset"
- ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
- className,
- )}
- data-slot="sidebar-container"
- {...props}
+ className="group peer hidden text-sidebar-foreground md:block"
+ data-collapsible={state === "collapsed" ? collapsible : ""}
+ data-side={side}
+ data-slot="sidebar"
+ data-state={state}
+ data-variant={variant}
>
+ {/* This is what handles the sidebar gap on desktop */}
<div
- className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm/5"
- data-sidebar="sidebar"
- data-slot="sidebar-inner"
+ className={cn(
+ "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
+ "group-data-[collapsible=offcanvas]:w-0",
+ "group-data-[side=right]:rotate-180",
+ variant === "floating" || variant === "inset"
+ ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
+ )}
+ data-slot="sidebar-gap"
+ />
+ <div
+ className={cn(
+ "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
+ side === "left"
+ ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
+ : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
+ // Adjust the padding for floating and inset variants.
+ variant === "floating" || variant === "inset"
+ ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
+ className,
+ )}
+ data-slot="sidebar-container"
+ {...props}
>
- {children}
+ <div
+ className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm/5"
+ data-sidebar="sidebar"
+ data-slot="sidebar-inner"
+ >
+ {children}
+ </div>
</div>
</div>
- </div>
+ </SidebarInstanceContext.Provider>
);
}
@@ -273,12 +336,244 @@ function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<t
);
}
-function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
- const { toggleSidebar } = useSidebar();
+function clampSidebarWidth(width: number, options: SidebarResolvedResizableOptions): number {
+ return Math.max(options.minWidth, Math.min(width, options.maxWidth));
+}
+
+function SidebarRail({
+ className,
+ onClick,
+ onPointerCancel,
+ onPointerDown,
+ onPointerMove,
+ onPointerUp,
+ ...props
+}: React.ComponentProps<"button">) {
+ const { open, toggleSidebar } = useSidebar();
+ const sidebarInstance = React.useContext(SidebarInstanceContext);
+ const railRef = React.useRef<HTMLButtonElement | null>(null);
+ const suppressClickRef = React.useRef(false);
+ const resizeStateRef = React.useRef<{
+ moved: boolean;
+ pointerId: number;
+ pendingWidth: number;
+ rail: HTMLButtonElement;
+ rafId: number | null;
+ sidebarRoot: HTMLElement;
+ side: "left" | "right";
+ startWidth: number;
+ startX: number;
+ transitionTargets: HTMLElement[];
+ width: number;
+ wrapper: HTMLElement;
+ } | null>(null);
+ const resolvedResizable = sidebarInstance?.resizable ?? null;
+ const canResize = resolvedResizable !== null && open;
+ const railLabel = canResize ? "Resize Sidebar" : "Toggle Sidebar";
+ const railTitle = canResize ? "Drag to resize sidebar" : "Toggle Sidebar";
+
+ const stopResize = React.useCallback(
+ (pointerId: number) => {
+ const resizeState = resizeStateRef.current;
+ if (!resizeState) {
+ return;
+ }
+ if (resizeState.rafId !== null) {
+ window.cancelAnimationFrame(resizeState.rafId);
+ }
+ resizeState.transitionTargets.forEach((element) => {
+ element.style.removeProperty("transition-duration");
+ });
+ if (resolvedResizable?.storageKey && typeof window !== "undefined") {
+ window.localStorage.setItem(resolvedResizable.storageKey, String(resizeState.width));
+ }
+ resolvedResizable?.onResize?.(resizeState.width);
+ resizeStateRef.current = null;
+ if (resizeState.rail.hasPointerCapture(pointerId)) {
+ resizeState.rail.releasePointerCapture(pointerId);
+ }
+ document.body.style.removeProperty("cursor");
+ document.body.style.removeProperty("user-select");
+ },
+ [resolvedResizable],
+ );
+
+ const handlePointerDown = React.useCallback(
+ (event: React.PointerEvent<HTMLButtonElement>) => {
+ onPointerDown?.(event);
+ if (event.defaultPrevented) return;
+ if (!resolvedResizable || !open || event.button !== 0) return;
+
+ const wrapper = event.currentTarget.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
+ const sidebarRoot = event.currentTarget.closest<HTMLElement>("[data-slot='sidebar']");
+ if (!wrapper || !sidebarRoot) {
+ return;
+ }
+
+ const sidebarContainer = sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-container']");
+ if (!sidebarContainer) {
+ return;
+ }
+
+ const startWidth = sidebarContainer.getBoundingClientRect().width;
+ const initialWidth = clampSidebarWidth(startWidth, resolvedResizable);
+ const transitionTargets = [
+ sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-gap']"),
+ sidebarRoot.querySelector<HTMLElement>("[data-slot='sidebar-container']"),
+ ].filter((element): element is HTMLElement => element !== null);
+ transitionTargets.forEach((element) => {
+ element.style.setProperty("transition-duration", "0ms");
+ });
+
+ event.preventDefault();
+ event.stopPropagation();
+ resizeStateRef.current = {
+ moved: false,
+ pointerId: event.pointerId,
+ pendingWidth: initialWidth,
+ rail: event.currentTarget,
+ rafId: null,
+ sidebarRoot,
+ side: sidebarInstance?.side ?? "left",
+ startWidth: initialWidth,
+ startX: event.clientX,
+ transitionTargets,
+ width: initialWidth,
+ wrapper,
+ };
+ wrapper.style.setProperty("--sidebar-width", `${initialWidth}px`);
+ event.currentTarget.setPointerCapture(event.pointerId);
+ document.body.style.cursor = "col-resize";
+ document.body.style.userSelect = "none";
+ },
+ [onPointerDown, open, resolvedResizable, sidebarInstance?.side],
+ );
+
+ const handlePointerMove = React.useCallback(
+ (event: React.PointerEvent<HTMLButtonElement>) => {
+ onPointerMove?.(event);
+ if (event.defaultPrevented) return;
+ const resizeState = resizeStateRef.current;
+ if (!resizeState || resizeState.pointerId !== event.pointerId || !resolvedResizable) return;
+
+ event.preventDefault();
+ const delta =
+ resizeState.side === "right"
+ ? resizeState.startX - event.clientX
+ : event.clientX - resizeState.startX;
+ if (Math.abs(delta) > 2) {
+ resizeState.moved = true;
+ }
+ resizeState.pendingWidth = clampSidebarWidth(resizeState.startWidth + delta, resolvedResizable);
+ if (resizeState.rafId !== null) {
+ return;
+ }
+
+ resizeState.rafId = window.requestAnimationFrame(() => {
+ const activeResizeState = resizeStateRef.current;
+ if (!activeResizeState || !resolvedResizable) return;
+
+ activeResizeState.rafId = null;
+ const nextWidth = activeResizeState.pendingWidth;
+ const accepted =
+ resolvedResizable.shouldAcceptWidth?.({
+ currentWidth: activeResizeState.width,
+ nextWidth,
+ rail: activeResizeState.rail,
+ side: activeResizeState.side,
+ sidebarRoot: activeResizeState.sidebarRoot,
+ wrapper: activeResizeState.wrapper,
+ }) ?? true;
+ if (!accepted) {
+ return;
+ }
+
+ activeResizeState.wrapper.style.setProperty("--sidebar-width", `${nextWidth}px`);
+ activeResizeState.width = nextWidth;
+ });
+ },
+ [onPointerMove, resolvedResizable],
+ );
+
+ const endResizeInteraction = React.useCallback(
+ (event: React.PointerEvent<HTMLButtonElement>) => {
+ const resizeState = resizeStateRef.current;
+ if (!resizeState || resizeState.pointerId !== event.pointerId) return;
+
+ event.preventDefault();
+ suppressClickRef.current = resizeState.moved;
+ stopResize(event.pointerId);
+ },
+ [stopResize],
+ );
+
+ const handlePointerUp = React.useCallback(
+ (event: React.PointerEvent<HTMLButtonElement>) => {
+ onPointerUp?.(event);
+ if (event.defaultPrevented) return;
+ endResizeInteraction(event);
+ },
+ [endResizeInteraction, onPointerUp],
+ );
+
+ const handlePointerCancel = React.useCallback(
+ (event: React.PointerEvent<HTMLButtonElement>) => {
+ onPointerCancel?.(event);
+ if (event.defaultPrevented) return;
+ endResizeInteraction(event);
+ },
+ [endResizeInteraction, onPointerCancel],
+ );
+
+ const handleClick = React.useCallback(
+ (event: React.MouseEvent<HTMLButtonElement>) => {
+ onClick?.(event);
+ if (event.defaultPrevented) return;
+ if (suppressClickRef.current) {
+ suppressClickRef.current = false;
+ event.preventDefault();
+ return;
+ }
+ if (resolvedResizable && open) {
+ event.preventDefault();
+ return;
+ }
+ toggleSidebar();
+ },
+ [onClick, open, resolvedResizable, toggleSidebar],
+ );
+
+ React.useEffect(() => {
+ if (!resolvedResizable?.storageKey || typeof window === "undefined") return;
+ const rail = railRef.current;
+ if (!rail) return;
+ const wrapper = rail.closest<HTMLElement>("[data-slot='sidebar-wrapper']");
+ if (!wrapper) return;
+
+ const storedWidth = Number(window.localStorage.getItem(resolvedResizable.storageKey));
+ if (!Number.isFinite(storedWidth)) return;
+ const clampedWidth = clampSidebarWidth(storedWidth, resolvedResizable);
+ wrapper.style.setProperty("--sidebar-width", `${clampedWidth}px`);
+ resolvedResizable.onResize?.(clampedWidth);
+ }, [resolvedResizable]);
+
+ React.useEffect(() => {
+ return () => {
+ const resizeState = resizeStateRef.current;
+ if (resizeState?.rafId != null) {
+ window.cancelAnimationFrame(resizeState.rafId);
+ }
+ resizeState?.transitionTargets.forEach((element) => {
+ element.style.removeProperty("transition-duration");
+ });
+ document.body.style.removeProperty("cursor");
+ document.body.style.removeProperty("user-select");
+ };
+ }, []);
return (
<button
- aria-label="Toggle Sidebar"
+ aria-label={railLabel}
className={cn(
"-translate-x-1/2 group-data-[side=left]:-right-4 absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=right]:left-0 sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
@@ -290,9 +585,14 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
)}
data-sidebar="rail"
data-slot="sidebar-rail"
- onClick={toggleSidebar}
+ onClick={handleClick}
+ onPointerCancel={handlePointerCancel}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ ref={railRef}
tabIndex={-1}
- title="Toggle Sidebar"
+ title={railTitle}
type="button"
{...props}
/>
diff --git a/apps/web/src/markdown-links.test.ts b/apps/web/src/markdown-links.test.ts
new file mode 100644
index 000000000..3d8fe3fee
--- /dev/null
+++ b/apps/web/src/markdown-links.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveMarkdownFileLinkTarget } from "./markdown-links";
+
+describe("resolveMarkdownFileLinkTarget", () => {
+ it("resolves absolute posix file paths", () => {
+ expect(resolveMarkdownFileLinkTarget("/Users/julius/project/AGENTS.md")).toBe(
+ "/Users/julius/project/AGENTS.md",
+ );
+ });
+
+ it("resolves relative file paths against cwd", () => {
+ expect(resolveMarkdownFileLinkTarget("src/processRunner.ts:71", "/Users/julius/project")).toBe(
+ "/Users/julius/project/src/processRunner.ts:71",
+ );
+ });
+
+ it("resolves bare file names against cwd", () => {
+ expect(resolveMarkdownFileLinkTarget("AGENTS.md", "/Users/julius/project")).toBe(
+ "/Users/julius/project/AGENTS.md",
+ );
+ });
+
+ it("maps #L line anchors to editor line suffixes", () => {
+ expect(
+ resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7"),
+ ).toBe("/Users/julius/project/src/main.ts:42:7");
+ });
+
+ it("ignores external urls", () => {
+ expect(resolveMarkdownFileLinkTarget("https://example.com/docs")).toBeNull();
+ });
+
+ it("does not treat app routes as file links", () => {
+ expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();
+ });
+});
diff --git a/apps/web/src/markdown-links.ts b/apps/web/src/markdown-links.ts
new file mode 100644
index 000000000..a5c593479
--- /dev/null
+++ b/apps/web/src/markdown-links.ts
@@ -0,0 +1,126 @@
+import { resolvePathLinkTarget } from "./terminal-links";
+
+const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
+const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
+const EXTERNAL_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/;
+const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
+const RELATIVE_FILE_PATH_PATTERN =
+ /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}$/;
+const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
+const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
+const POSIX_FILE_ROOT_PREFIXES = [
+ "/Users/",
+ "/home/",
+ "/tmp/",
+ "/var/",
+ "/etc/",
+ "/opt/",
+ "/mnt/",
+ "/Volumes/",
+ "/private/",
+ "/root/",
+] as const;
+
+function safeDecode(value: string): string {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
+function stripSearchAndHash(value: string): { path: string; hash: string } {
+ const hashIndex = value.indexOf("#");
+ const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
+ const rawHash = hashIndex >= 0 ? value.slice(hashIndex) : "";
+ const queryIndex = pathWithSearch.indexOf("?");
+ const path = queryIndex >= 0 ? pathWithSearch.slice(0, queryIndex) : pathWithSearch;
+ return { path, hash: rawHash };
+}
+
+function parseFileUrlHref(href: string): { path: string; hash: string } | null {
+ try {
+ const parsed = new URL(href);
+ if (parsed.protocol.toLowerCase() !== "file:") return null;
+
+ const decodedPath = safeDecode(parsed.pathname);
+ if (decodedPath.length === 0) return null;
+
+ // Browser URL parser encodes "C:/foo" as "/C:/foo" for file URLs.
+ const normalizedPath = /^\/[A-Za-z]:[\\/]/.test(decodedPath)
+ ? decodedPath.slice(1)
+ : decodedPath;
+
+ return { path: normalizedPath, hash: parsed.hash };
+ } catch {
+ return null;
+ }
+}
+
+function looksLikePosixFilesystemPath(path: string): boolean {
+ if (!path.startsWith("/")) return false;
+ if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
+ if (POSITION_SUFFIX_PATTERN.test(path)) return true;
+ const basename = path.slice(path.lastIndexOf("/") + 1);
+ return /\.[A-Za-z0-9_-]+$/.test(basename);
+}
+
+function appendLineColumnFromHash(path: string, hash: string): string {
+ if (!hash || POSITION_SUFFIX_PATTERN.test(path)) return path;
+ const match = hash.match(/^#L(\d+)(?:C(\d+))?$/i);
+ if (!match?.[1]) return path;
+ const line = match[1];
+ const column = match[2];
+ return `${path}:${line}${column ? `:${column}` : ""}`;
+}
+
+function isLikelyPathCandidate(path: string): boolean {
+ if (WINDOWS_DRIVE_PATH_PATTERN.test(path) || WINDOWS_UNC_PATH_PATTERN.test(path)) return true;
+ if (RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
+ if (path.startsWith("/")) return looksLikePosixFilesystemPath(path);
+ return RELATIVE_FILE_PATH_PATTERN.test(path) || RELATIVE_FILE_NAME_PATTERN.test(path);
+}
+
+function isRelativePath(path: string): boolean {
+ return (
+ RELATIVE_PATH_PREFIX_PATTERN.test(path) ||
+ (!path.startsWith("/") &&
+ !WINDOWS_DRIVE_PATH_PATTERN.test(path) &&
+ !WINDOWS_UNC_PATH_PATTERN.test(path))
+ );
+}
+
+export function resolveMarkdownFileLinkTarget(
+ href: string | undefined,
+ cwd?: string,
+): string | null {
+ if (!href) return null;
+ const rawHref = href.trim();
+ if (rawHref.length === 0 || rawHref.startsWith("#")) return null;
+
+ const fileUrlTarget = rawHref.toLowerCase().startsWith("file:")
+ ? parseFileUrlHref(rawHref)
+ : null;
+ const source = fileUrlTarget ?? stripSearchAndHash(rawHref);
+ const decodedPath = safeDecode(source.path.trim());
+ const decodedHash = safeDecode(source.hash.trim());
+
+ if (decodedPath.length === 0) return null;
+ if (
+ !WINDOWS_DRIVE_PATH_PATTERN.test(decodedPath) &&
+ !WINDOWS_UNC_PATH_PATTERN.test(decodedPath) &&
+ EXTERNAL_SCHEME_PATTERN.test(decodedPath)
+ ) {
+ return null;
+ }
+
+ if (!isLikelyPathCandidate(decodedPath)) return null;
+
+ const pathWithPosition = appendLineColumnFromHash(decodedPath, decodedHash);
+ if (!isRelativePath(pathWithPosition)) {
+ return pathWithPosition;
+ }
+
+ if (!cwd) return null;
+ return resolvePathLinkTarget(pathWithPosition, cwd);
+}
diff --git a/apps/web/src/routes/_chat.$threadId.tsx b/apps/web/src/routes/_chat.$threadId.tsx
index 5efee58f5..1cebff4b3 100644
--- a/apps/web/src/routes/_chat.$threadId.tsx
+++ b/apps/web/src/routes/_chat.$threadId.tsx
@@ -6,45 +6,130 @@ import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch"
import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store";
import { Sheet, SheetPopup } from "../components/ui/sheet";
+import { Sidebar, SidebarInset, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
const DiffPanel = lazy(() => import("../components/DiffPanel"));
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
+const DIFF_INLINE_SIDEBAR_WIDTH_STORAGE_KEY = "chat_diff_sidebar_width";
+const DIFF_INLINE_DEFAULT_WIDTH = "clamp(28rem,48vw,44rem)";
+const DIFF_INLINE_SIDEBAR_MIN_WIDTH = 28 * 16;
-const DiffPanelWrapper = (props: {
+const DiffPanelSheet = (props: {
children: ReactNode;
- sheet: boolean;
diffOpen: boolean;
onCloseDiff: () => void;
}) => {
- if (props.sheet) {
- return (
- <Sheet
- open={props.diffOpen}
- onOpenChange={(open) => {
- if (!open) {
- props.onCloseDiff();
- }
- }}
+ return (
+ <Sheet
+ open={props.diffOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ props.onCloseDiff();
+ }
+ }}
+ >
+ <SheetPopup
+ side="right"
+ showCloseButton={false}
+ keepMounted
+ className="w-[min(88vw,820px)] max-w-[820px] p-0"
>
- <SheetPopup
- side="right"
- showCloseButton={false}
- keepMounted
- className="w-[min(88vw,820px)] max-w-[820px] p-0"
- >
- {props.children}
- </SheetPopup>
- </Sheet>
+ {props.children}
+ </SheetPopup>
+ </Sheet>
+ );
+};
+
+const DiffLoadingFallback = (props: { inline: boolean }) => {
+ if (props.inline) {
+ return (
+ <div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
+ Loading diff viewer...
+ </div>
);
}
return (
- <aside className={props.diffOpen ? undefined : "hidden"} aria-hidden={!props.diffOpen}>
- {props.children}
+ <aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
+ Loading diff viewer...
</aside>
);
};
+const DiffPanelInlineSidebar = (props: {
+ diffOpen: boolean;
+ onCloseDiff: () => void;
+ onOpenDiff: () => void;
+}) => {
+ const { diffOpen, onCloseDiff, onOpenDiff } = props;
+ const onOpenChange = useCallback(
+ (open: boolean) => {
+ if (open) {
+ onOpenDiff();
+ return;
+ }
+ onCloseDiff();
+ },
+ [onCloseDiff, onOpenDiff],
+ );
+ const shouldAcceptInlineSidebarWidth = useCallback(
+ ({ nextWidth, wrapper }: { nextWidth: number; wrapper: HTMLElement }) => {
+ const composerForm = document.querySelector<HTMLElement>("[data-chat-composer-form='true']");
+ if (!composerForm) return true;
+ const composerViewport = composerForm.parentElement;
+ if (!composerViewport) return true;
+ const previousSidebarWidth = wrapper.style.getPropertyValue("--sidebar-width");
+ wrapper.style.setProperty("--sidebar-width", `${nextWidth}px`);
+
+ const viewportStyle = window.getComputedStyle(composerViewport);
+ const viewportPaddingLeft = Number.parseFloat(viewportStyle.paddingLeft) || 0;
+ const viewportPaddingRight = Number.parseFloat(viewportStyle.paddingRight) || 0;
+ const viewportContentWidth = Math.max(
+ 0,
+ composerViewport.clientWidth - viewportPaddingLeft - viewportPaddingRight,
+ );
+ const formRect = composerForm.getBoundingClientRect();
+ const hasComposerOverflow = composerForm.scrollWidth > composerForm.clientWidth + 0.5;
+ const overflowsViewport = formRect.width > viewportContentWidth + 0.5;
+
+ if (previousSidebarWidth.length > 0) {
+ wrapper.style.setProperty("--sidebar-width", previousSidebarWidth);
+ } else {
+ wrapper.style.removeProperty("--sidebar-width");
+ }
+
+ return !hasComposerOverflow && !overflowsViewport;
+ },
+ [],
+ );
+
+ return (
+ <SidebarProvider
+ defaultOpen={false}
+ open={diffOpen}
+ onOpenChange={onOpenChange}
+ className="w-auto min-h-0 flex-none bg-transparent"
+ style={{ "--sidebar-width": DIFF_INLINE_DEFAULT_WIDTH } as React.CSSProperties}
+ >
+ <Sidebar
+ side="right"
+ collapsible="offcanvas"
+ className="border-l border-border bg-card text-foreground"
+ resizable={{
+ minWidth: DIFF_INLINE_SIDEBAR_MIN_WIDTH,
+ shouldAcceptWidth: shouldAcceptInlineSidebarWidth,
+ storageKey: DIFF_INLINE_SIDEBAR_WIDTH_STORAGE_KEY,
+ }}
+ >
+ <Suspense fallback={<DiffLoadingFallback inline />}>
+ <DiffPanel mode="sidebar" />
+ </Suspense>
+ <SidebarRail />
+ </Sidebar>
+ </SidebarProvider>
+ );
+};
+
function ChatThreadRouteView() {
const { state } = useStore();
const navigate = useNavigate();
@@ -62,6 +147,16 @@ function ChatThreadRouteView() {
},
});
}, [navigate, threadId]);
+ const openDiff = useCallback(() => {
+ void navigate({
+ to: "/$threadId",
+ params: { threadId },
+ search: (previous) => {
+ const rest = stripDiffSearchParams(previous);
+ return { ...rest, diff: "1" };
+ },
+ });
+ }, [navigate, threadId]);
useEffect(() => {
if (!threadId) {
@@ -83,25 +178,27 @@ function ChatThreadRouteView() {
return null;
}
- const diffLoadingFallback =
- !diffOpen || shouldUseDiffSheet ? (
- <div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
- Loading diff viewer...
- </div>
- ) : (
- <aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
- Loading diff viewer...
- </aside>
+ if (!shouldUseDiffSheet) {
+ return (
+ <>
+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
+ <ChatView threadId={threadId} />
+ </SidebarInset>
+ <DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
+ </>
);
+ }
return (
<>
- <ChatView threadId={threadId} />
- <DiffPanelWrapper sheet={shouldUseDiffSheet} diffOpen={diffOpen} onCloseDiff={closeDiff}>
- <Suspense fallback={diffLoadingFallback}>
- <DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
+ <ChatView threadId={threadId} />
+ </SidebarInset>
+ <DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
+ <Suspense fallback={<DiffLoadingFallback inline={false} />}>
+ <DiffPanel mode="sheet" />
</Suspense>
- </DiffPanelWrapper>
+ </DiffPanelSheet>
</>
);
}
diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx
index 740707add..b2fac54ab 100644
--- a/apps/web/src/routes/_chat.settings.tsx
+++ b/apps/web/src/routes/_chat.settings.tsx
@@ -7,6 +7,7 @@ import { useStore } from "../store";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Switch } from "../components/ui/switch";
+import { SidebarInset } from "~/components/ui/sidebar";
const THEME_OPTIONS = [
{
@@ -48,209 +49,214 @@ function SettingsRouteView() {
const codexHomePath = settings.codexHomePath;
return (
- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
- {isElectron && (
- <div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
- <span className="text-xs font-medium tracking-wide text-muted-foreground/70">Settings</span>
- </div>
- )}
-
- <div className="flex-1 overflow-y-auto p-6">
- <div className="mx-auto flex w-full max-w-3xl flex-col gap-6">
- <header className="space-y-1">
- <h1 className="text-2xl font-semibold tracking-tight text-foreground">Settings</h1>
- <p className="text-sm text-muted-foreground">
- Configure app-level preferences for this device.
- </p>
- </header>
+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
+ {isElectron && (
+ <div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
+ <span className="text-xs font-medium tracking-wide text-muted-foreground/70">
+ Settings
+ </span>
+ </div>
+ )}
- <section className="rounded-2xl border border-border bg-card p-5">
- <div className="mb-4">
- <h2 className="text-sm font-medium text-foreground">Appearance</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- Choose how T3 Code handles light and dark mode.
+ <div className="flex-1 overflow-y-auto p-6">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-6">
+ <header className="space-y-1">
+ <h1 className="text-2xl font-semibold tracking-tight text-foreground">Settings</h1>
+ <p className="text-sm text-muted-foreground">
+ Configure app-level preferences for this device.
</p>
- </div>
+ </header>
- <div className="space-y-2" role="radiogroup" aria-label="Theme preference">
- {THEME_OPTIONS.map((option) => {
- const selected = theme === option.value;
- return (
- <button
- key={option.value}
- type="button"
- role="radio"
- aria-checked={selected}
- className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
- selected
- ? "border-primary/60 bg-primary/8 text-foreground"
- : "border-border bg-background text-muted-foreground hover:bg-accent"
- }`}
- onClick={() => setTheme(option.value)}
- >
- <span className="flex flex-col">
- <span className="text-sm font-medium">{option.label}</span>
- <span className="text-xs">{option.description}</span>
- </span>
- {selected ? (
- <span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
- Selected
- </span>
- ) : null}
- </button>
- );
- })}
- </div>
+ <section className="rounded-2xl border border-border bg-card p-5">
+ <div className="mb-4">
+ <h2 className="text-sm font-medium text-foreground">Appearance</h2>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Choose how T3 Code handles light and dark mode.
+ </p>
+ </div>
- <p className="mt-4 text-xs text-muted-foreground">
- Active theme: <span className="font-medium text-foreground">{resolvedTheme}</span>
- </p>
- </section>
+ <div className="space-y-2" role="radiogroup" aria-label="Theme preference">
+ {THEME_OPTIONS.map((option) => {
+ const selected = theme === option.value;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
+ selected
+ ? "border-primary/60 bg-primary/8 text-foreground"
+ : "border-border bg-background text-muted-foreground hover:bg-accent"
+ }`}
+ onClick={() => setTheme(option.value)}
+ >
+ <span className="flex flex-col">
+ <span className="text-sm font-medium">{option.label}</span>
+ <span className="text-xs">{option.description}</span>
+ </span>
+ {selected ? (
+ <span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
+ Selected
+ </span>
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
- <section className="rounded-2xl border border-border bg-card p-5">
- <div className="mb-4">
- <h2 className="text-sm font-medium text-foreground">Codex App Server</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- These overrides apply to new sessions and let you use a non-default Codex install.
+ <p className="mt-4 text-xs text-muted-foreground">
+ Active theme: <span className="font-medium text-foreground">{resolvedTheme}</span>
</p>
- </div>
-
- <div className="space-y-4">
- <label className="block space-y-1">
- <span className="text-xs font-medium text-foreground">Codex binary path</span>
- <Input
- value={codexBinaryPath}
- onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
- placeholder="codex"
- spellCheck={false}
- />
- <span className="text-xs text-muted-foreground">
- Leave blank to use <code>codex</code> from your PATH.
- </span>
- </label>
+ </section>
- <label className="block space-y-1">
- <span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
- <Input
- value={codexHomePath}
- onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
- placeholder="/Users/you/.codex"
- spellCheck={false}
- />
- <span className="text-xs text-muted-foreground">
- Optional custom Codex home/config directory.
- </span>
- </label>
-
- <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
- <p>
- Binary source: <span className="font-medium text-foreground">{codexBinaryPath || "PATH"}</span>
+ <section className="rounded-2xl border border-border bg-card p-5">
+ <div className="mb-4">
+ <h2 className="text-sm font-medium text-foreground">Codex App Server</h2>
+ <p className="mt-1 text-xs text-muted-foreground">
+ These overrides apply to new sessions and let you use a non-default Codex install.
</p>
- <Button
- size="xs"
- variant="outline"
- onClick={() =>
- updateSettings({
- codexBinaryPath: defaults.codexBinaryPath,
- codexHomePath: defaults.codexHomePath,
- })
- }
- >
- Reset codex overrides
- </Button>
</div>
- </div>
- </section>
- <section className="rounded-2xl border border-border bg-card p-5">
- <div className="mb-4">
- <h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- Select the default execution policy for this client.
- </p>
- </div>
+ <div className="space-y-4">
+ <label className="block space-y-1">
+ <span className="text-xs font-medium text-foreground">Codex binary path</span>
+ <Input
+ value={codexBinaryPath}
+ onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
+ placeholder="codex"
+ spellCheck={false}
+ />
+ <span className="text-xs text-muted-foreground">
+ Leave blank to use <code>codex</code> from your PATH.
+ </span>
+ </label>
- <div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
- {RUNTIME_MODE_OPTIONS.map((option) => {
- const selected = state.runtimeMode === option.value;
- return (
- <button
- key={option.value}
- type="button"
- role="radio"
- aria-checked={selected}
- className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
- selected
- ? "border-primary/60 bg-primary/8 text-foreground"
- : "border-border bg-background text-muted-foreground hover:bg-accent"
- }`}
- onClick={() => {
- dispatch({
- type: "SET_RUNTIME_MODE",
- mode: option.value,
- });
- }}
+ <label className="block space-y-1">
+ <span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
+ <Input
+ value={codexHomePath}
+ onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
+ placeholder="/Users/you/.codex"
+ spellCheck={false}
+ />
+ <span className="text-xs text-muted-foreground">
+ Optional custom Codex home/config directory.
+ </span>
+ </label>
+
+ <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
+ <p>
+ Binary source:{" "}
+ <span className="font-medium text-foreground">{codexBinaryPath || "PATH"}</span>
+ </p>
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() =>
+ updateSettings({
+ codexBinaryPath: defaults.codexBinaryPath,
+ codexHomePath: defaults.codexHomePath,
+ })
+ }
>
- <span className="flex flex-col">
- <span className="text-sm font-medium">{option.label}</span>
- <span className="text-xs">{option.description}</span>
- </span>
- {selected ? (
- <span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
- Selected
- </span>
- ) : null}
- </button>
- );
- })}
- </div>
- </section>
+ Reset codex overrides
+ </Button>
+ </div>
+ </div>
+ </section>
- <section className="rounded-2xl border border-border bg-card p-5">
- <div className="mb-4">
- <h2 className="text-sm font-medium text-foreground">Safety</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- Additional guardrails for destructive local actions.
- </p>
- </div>
+ <section className="rounded-2xl border border-border bg-card p-5">
+ <div className="mb-4">
+ <h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Select the default execution policy for this client.
+ </p>
+ </div>
+
+ <div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
+ {RUNTIME_MODE_OPTIONS.map((option) => {
+ const selected = state.runtimeMode === option.value;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ className={`flex w-full items-start justify-between rounded-lg border px-3 py-2 text-left transition-colors ${
+ selected
+ ? "border-primary/60 bg-primary/8 text-foreground"
+ : "border-border bg-background text-muted-foreground hover:bg-accent"
+ }`}
+ onClick={() => {
+ dispatch({
+ type: "SET_RUNTIME_MODE",
+ mode: option.value,
+ });
+ }}
+ >
+ <span className="flex flex-col">
+ <span className="text-sm font-medium">{option.label}</span>
+ <span className="text-xs">{option.description}</span>
+ </span>
+ {selected ? (
+ <span className="rounded bg-primary/14 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-primary">
+ Selected
+ </span>
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
+ </section>
- <div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
- <div>
- <p className="text-sm font-medium text-foreground">Confirm thread deletion</p>
- <p className="text-xs text-muted-foreground">
- Ask for confirmation before deleting a thread and its chat history.
+ <section className="rounded-2xl border border-border bg-card p-5">
+ <div className="mb-4">
+ <h2 className="text-sm font-medium text-foreground">Safety</h2>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Additional guardrails for destructive local actions.
</p>
</div>
- <Switch
- checked={settings.confirmThreadDelete}
- onCheckedChange={(checked) =>
- updateSettings({
- confirmThreadDelete: Boolean(checked),
- })
- }
- aria-label="Confirm thread deletion"
- />
- </div>
- {settings.confirmThreadDelete !== defaults.confirmThreadDelete ? (
- <div className="mt-3 flex justify-end">
- <Button
- size="xs"
- variant="outline"
- onClick={() =>
+ <div className="flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2">
+ <div>
+ <p className="text-sm font-medium text-foreground">Confirm thread deletion</p>
+ <p className="text-xs text-muted-foreground">
+ Ask for confirmation before deleting a thread and its chat history.
+ </p>
+ </div>
+ <Switch
+ checked={settings.confirmThreadDelete}
+ onCheckedChange={(checked) =>
updateSettings({
- confirmThreadDelete: defaults.confirmThreadDelete,
+ confirmThreadDelete: Boolean(checked),
})
}
- >
- Restore default
- </Button>
+ aria-label="Confirm thread deletion"
+ />
</div>
- ) : null}
- </section>
+
+ {settings.confirmThreadDelete !== defaults.confirmThreadDelete ? (
+ <div className="mt-3 flex justify-end">
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() =>
+ updateSettings({
+ confirmThreadDelete: defaults.confirmThreadDelete,
+ })
+ }
+ >
+ Restore default
+ </Button>
+ </div>
+ ) : null}
+ </section>
+ </div>
</div>
</div>
- </div>
+ </SidebarInset>
);
}
diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx
index 38cf5bccc..0c535c68f 100644
--- a/apps/web/src/routes/_chat.tsx
+++ b/apps/web/src/routes/_chat.tsx
@@ -33,11 +33,9 @@ function ChatRouteLayout() {
>
<ThreadSidebar />
</Sidebar>
- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
- <DiffWorkerPoolProvider>
- <Outlet />
- </DiffWorkerPoolProvider>
- </SidebarInset>
+ <DiffWorkerPoolProvider>
+ <Outlet />
+ </DiffWorkerPoolProvider>
</SidebarProvider>
);
}
diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts
index c19f2618f..bf2691fbd 100644
--- a/apps/web/src/store.ts
+++ b/apps/web/src/store.ts
@@ -8,10 +8,7 @@ import {
useReducer,
} from "react";
-import {
- type OrchestrationReadModel,
- type OrchestrationSessionStatus,
-} from "@t3tools/contracts";
+import { type OrchestrationReadModel, type OrchestrationSessionStatus } from "@t3tools/contracts";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
@@ -30,8 +27,7 @@ import {
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
- | { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
- | { type: "SET_THREADS_HYDRATED"; hydrated: boolean }
+ | { type: "MARK_THREAD_VISITED"; threadId: string; visitedAt?: string }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
@@ -137,10 +133,6 @@ function updateThread(
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
-function cloneProjectScripts(scripts: ReadonlyArray<ProjectScript>): ProjectScript[] {
- return scripts.map((script) => ({ ...script }));
-}
-
function mapProjectsFromReadModel(
incoming: OrchestrationReadModel["projects"],
previous: Project[],
@@ -159,7 +151,7 @@ function mapProjectsFromReadModel(
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.workspaceRoot)
: true),
- scripts: cloneProjectScripts(project.scripts),
+ scripts: project.scripts.map((script) => ({ ...script })),
};
});
}
@@ -187,7 +179,6 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
return providerName === "claudeCode" ? "claudeCode" : "codex";
}
-
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
@@ -208,7 +199,6 @@ function normalizeRunningTerminalIds(
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
-
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
@@ -374,7 +364,6 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
});
}
-
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
@@ -384,94 +373,100 @@ export function reducer(state: AppState, action: Action): AppState {
action.readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
- const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
+ const existingThreadById = new Map(
+ state.threads.map((thread) => [thread.id, thread] as const),
+ );
const threads = action.readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
- const existing = existingThreadById.get(thread.id);
- const latestTurnStartedAt =
- thread.latestTurnId === null
- ? undefined
- : thread.messages.find(
- (message) => message.turnId === thread.latestTurnId && message.role === "user",
- )?.createdAt;
- const latestTurnCompletedAt = thread.checkpoints.find(
- (checkpoint) => checkpoint.turnId === thread.latestTurnId,
- )?.completedAt;
- const latestTurnDurationMs =
- latestTurnStartedAt && latestTurnCompletedAt
- ? Math.max(0, Date.parse(latestTurnCompletedAt) - Date.parse(latestTurnStartedAt))
- : undefined;
-
- return normalizeThreadTerminals({
- id: thread.id,
- codexThreadId: thread.session?.providerThreadId ?? null,
- projectId: thread.projectId,
- title: thread.title,
- model: resolveModelSlug(thread.model),
- terminalOpen: existing?.terminalOpen ?? false,
- terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
- terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
- runningTerminalIds: existing?.runningTerminalIds ?? [],
- activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
- terminalGroups: existing?.terminalGroups ?? [
- { id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
- ],
- activeTerminalGroupId: existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
- session: thread.session
- ? {
- sessionId: thread.session.providerSessionId ?? `thread:${thread.id}`,
- provider: toLegacyProvider(thread.session.providerName),
- status: toLegacySessionStatus(thread.session.status),
- orchestrationStatus: thread.session.status,
- threadId: thread.session.providerThreadId,
- activeTurnId: thread.session.activeTurnId ?? undefined,
- createdAt: thread.session.updatedAt,
- updatedAt: thread.session.updatedAt,
- ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
- }
- : null,
- messages: thread.messages.map((message) => {
- const attachments = message.attachments?.map((attachment, index) => ({
- type: "image" as const,
- id: `${message.id}:${index}`,
- name: attachment.name,
- mimeType: attachment.mimeType,
- sizeBytes: attachment.sizeBytes,
- previewUrl: attachment.dataUrl,
- }));
- const normalizedMessage: ChatMessage = {
- id: message.id,
- role: message.role,
- text: message.text,
- createdAt: message.createdAt,
- streaming: message.streaming,
- ...(message.streaming ? {} : { completedAt: message.updatedAt }),
- ...(attachments && attachments.length > 0 ? { attachments } : {}),
- };
- return normalizedMessage;
- }),
- error: thread.session?.lastError ?? null,
- createdAt: thread.createdAt,
- latestTurnId: thread.latestTurnId ?? undefined,
- latestTurnStartedAt,
- latestTurnCompletedAt,
- latestTurnDurationMs,
- lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
- branch: thread.branch,
- worktreePath: thread.worktreePath,
- turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
- turnId: checkpoint.turnId,
- completedAt: checkpoint.completedAt,
- status: checkpoint.status,
- assistantMessageId: checkpoint.assistantMessageId ?? undefined,
- checkpointTurnCount: checkpoint.checkpointTurnCount,
- checkpointRef: checkpoint.checkpointRef,
- files: checkpoint.files.map((file) => ({ ...file })),
- })),
- activities: thread.activities.map((activity) => ({ ...activity })),
+ const existing = existingThreadById.get(thread.id);
+ const latestTurnStartedAt =
+ thread.latestTurnId === null
+ ? undefined
+ : thread.messages.find(
+ (message) => message.turnId === thread.latestTurnId && message.role === "user",
+ )?.createdAt;
+ const latestTurnCompletedAt = thread.checkpoints.find(
+ (checkpoint) => checkpoint.turnId === thread.latestTurnId,
+ )?.completedAt;
+ const latestTurnDurationMs =
+ latestTurnStartedAt && latestTurnCompletedAt
+ ? Math.max(0, Date.parse(latestTurnCompletedAt) - Date.parse(latestTurnStartedAt))
+ : undefined;
+
+ return normalizeThreadTerminals({
+ id: thread.id,
+ codexThreadId: thread.session?.providerThreadId ?? null,
+ projectId: thread.projectId,
+ title: thread.title,
+ model: resolveModelSlug(thread.model),
+ terminalOpen: existing?.terminalOpen ?? false,
+ terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
+ terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
+ runningTerminalIds: existing?.runningTerminalIds ?? [],
+ activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
+ terminalGroups: existing?.terminalGroups ?? [
+ {
+ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
+ terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
+ },
+ ],
+ activeTerminalGroupId:
+ existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
+ session: thread.session
+ ? {
+ sessionId: thread.session.providerSessionId ?? `thread:${thread.id}`,
+ provider: toLegacyProvider(thread.session.providerName),
+ status: toLegacySessionStatus(thread.session.status),
+ orchestrationStatus: thread.session.status,
+ threadId: thread.session.providerThreadId,
+ activeTurnId: thread.session.activeTurnId ?? undefined,
+ createdAt: thread.session.updatedAt,
+ updatedAt: thread.session.updatedAt,
+ ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
+ }
+ : null,
+ messages: thread.messages.map((message) => {
+ const attachments = message.attachments?.map((attachment, index) => ({
+ type: "image" as const,
+ id: `${message.id}:${index}`,
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ sizeBytes: attachment.sizeBytes,
+ previewUrl: attachment.dataUrl,
+ }));
+ const normalizedMessage: ChatMessage = {
+ id: message.id,
+ role: message.role,
+ text: message.text,
+ createdAt: message.createdAt,
+ streaming: message.streaming,
+ ...(message.streaming ? {} : { completedAt: message.updatedAt }),
+ ...(attachments && attachments.length > 0 ? { attachments } : {}),
+ };
+ return normalizedMessage;
+ }),
+ error: thread.session?.lastError ?? null,
+ createdAt: thread.createdAt,
+ latestTurnId: thread.latestTurnId ?? undefined,
+ latestTurnStartedAt,
+ latestTurnCompletedAt,
+ latestTurnDurationMs,
+ lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
+ branch: thread.branch,
+ worktreePath: thread.worktreePath,
+ turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
+ turnId: checkpoint.turnId,
+ completedAt: checkpoint.completedAt,
+ status: checkpoint.status,
+ assistantMessageId: checkpoint.assistantMessageId ?? undefined,
+ checkpointTurnCount: checkpoint.checkpointTurnCount,
+ checkpointRef: checkpoint.checkpointRef,
+ files: checkpoint.files.map((file) => ({ ...file })),
+ })),
+ activities: thread.activities.map((activity) => ({ ...activity })),
+ });
});
- });
return {
...state,
projects,
@@ -480,24 +475,27 @@ export function reducer(state: AppState, action: Action): AppState {
};
}
- case "SET_PROJECT_SCRIPTS":
- return {
- ...state,
- projects: state.projects.map((project) =>
- project.id === action.projectId
- ? { ...project, scripts: cloneProjectScripts(action.scripts) }
- : project,
- ),
- };
-
- case "SET_THREADS_HYDRATED":
- if (state.threadsHydrated === action.hydrated) {
- return state;
- }
+ case "MARK_THREAD_VISITED": {
+ const visitedAt = action.visitedAt ?? new Date().toISOString();
+ const visitedAtMs = Date.parse(visitedAt);
return {
...state,
- threadsHydrated: action.hydrated,
+ threads: updateThread(state.threads, action.threadId, (thread) => {
+ const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
+ if (
+ Number.isFinite(previousVisitedAtMs) &&
+ Number.isFinite(visitedAtMs) &&
+ previousVisitedAtMs >= visitedAtMs
+ ) {
+ return thread;
+ }
+ return {
+ ...thread,
+ lastVisitedAt: visitedAt,
+ };
+ }),
};
+ }
case "TOGGLE_PROJECT":
return {
@@ -540,10 +538,7 @@ export function reducer(state: AppState, action: Action): AppState {
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
- if (
- isNewTerminal &&
- normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
- ) {
+ if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
@@ -613,10 +608,7 @@ export function reducer(state: AppState, action: Action): AppState {
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
- if (
- isNewTerminal &&
- normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
- ) {
+ if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)