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.

fix(web): resolve preferred editor from available editors & introduce `useLocalStorage` helper (#662)

Magnus Buvarpa01d712751f8
diff --git a/apps/web/src/appSettings.test.ts b/apps/web/src/appSettings.test.ts
index 213e4cd3d..e7e9a67e1 100644
--- a/apps/web/src/appSettings.test.ts
+++ b/apps/web/src/appSettings.test.ts
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import {
getAppModelOptions,
- getSlashModelOptions,
normalizeCustomModelSlugs,
resolveAppModelSelection,
} from "./appSettings";
@@ -58,17 +57,3 @@ describe("resolveAppModelSelection", () => {
expect(resolveAppModelSelection("codex", [], "")).toBe("gpt-5.4");
});
});
-
-describe("getSlashModelOptions", () => {
- it("includes saved custom model slugs for /model command suggestions", () => {
- const options = getSlashModelOptions("codex", ["custom/internal-model"], "", "gpt-5.3-codex");
-
- expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
- });
-
- it("filters slash-model suggestions across built-in and custom model names", () => {
- const options = getSlashModelOptions("codex", ["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
-
- expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
- });
-});
diff --git a/apps/web/src/appSettings.ts b/apps/web/src/appSettings.ts
index 5ed218fb2..e5018e0bf 100644
--- a/apps/web/src/appSettings.ts
+++ b/apps/web/src/appSettings.ts
@@ -1,7 +1,8 @@
-import { useCallback, useSyncExternalStore } from "react";
+import { useCallback } from "react";
import { Option, Schema } from "effect";
import { type ProviderKind } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
+import { useLocalStorage } from "./hooks/useLocalStorage";
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
@@ -34,10 +35,6 @@ export interface AppModelOption {
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
-let listeners: Array<() => void> = [];
-let cachedRawSettings: string | null | undefined;
-let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
-
export function normalizeCustomModelSlugs(
models: Iterable<string | null | undefined>,
provider: ProviderKind = "codex",
@@ -67,13 +64,6 @@ export function normalizeCustomModelSlugs(
return normalizedModels;
}
-function normalizeAppSettings(settings: AppSettings): AppSettings {
- return {
- ...settings,
- customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
- };
-}
-
export function getAppModelOptions(
provider: ProviderKind,
customModels: readonly string[],
@@ -143,112 +133,26 @@ export function resolveAppModelSelection(
);
}
-export function getSlashModelOptions(
- provider: ProviderKind,
- customModels: readonly string[],
- query: string,
- selectedModel?: string | null,
-): AppModelOption[] {
- const normalizedQuery = query.trim().toLowerCase();
- const options = getAppModelOptions(provider, customModels, selectedModel);
- if (!normalizedQuery) {
- return options;
- }
-
- return options.filter((option) => {
- const searchSlug = option.slug.toLowerCase();
- const searchName = option.name.toLowerCase();
- return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
- });
-}
-
-function emitChange(): void {
- for (const listener of listeners) {
- listener();
- }
-}
-
-function parsePersistedSettings(value: string | null): AppSettings {
- if (!value) {
- return DEFAULT_APP_SETTINGS;
- }
-
- try {
- return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
- } catch {
- return DEFAULT_APP_SETTINGS;
- }
-}
-
-export function getAppSettingsSnapshot(): AppSettings {
- if (typeof window === "undefined") {
- return DEFAULT_APP_SETTINGS;
- }
-
- const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
- if (raw === cachedRawSettings) {
- return cachedSnapshot;
- }
-
- cachedRawSettings = raw;
- cachedSnapshot = parsePersistedSettings(raw);
- return cachedSnapshot;
-}
-
-function persistSettings(next: AppSettings): void {
- if (typeof window === "undefined") return;
-
- const raw = JSON.stringify(next);
- try {
- if (raw !== cachedRawSettings) {
- window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
- }
- } catch {
- // Best-effort persistence only.
- }
-
- cachedRawSettings = raw;
- cachedSnapshot = next;
-}
-
-function subscribe(listener: () => void): () => void {
- listeners.push(listener);
-
- const onStorage = (event: StorageEvent) => {
- if (event.key === APP_SETTINGS_STORAGE_KEY) {
- emitChange();
- }
- };
-
- window.addEventListener("storage", onStorage);
- return () => {
- listeners = listeners.filter((entry) => entry !== listener);
- window.removeEventListener("storage", onStorage);
- };
-}
-
export function useAppSettings() {
- const settings = useSyncExternalStore(
- subscribe,
- getAppSettingsSnapshot,
- () => DEFAULT_APP_SETTINGS,
+ const [settings, setSettings] = useLocalStorage(
+ APP_SETTINGS_STORAGE_KEY,
+ DEFAULT_APP_SETTINGS,
+ AppSettingsSchema,
);
- const updateSettings = useCallback((patch: Partial<AppSettings>) => {
- const next = normalizeAppSettings(
- Schema.decodeSync(AppSettingsSchema)({
- ...getAppSettingsSnapshot(),
+ const updateSettings = useCallback(
+ (patch: Partial<AppSettings>) => {
+ setSettings((prev) => ({
+ ...prev,
...patch,
- }),
- );
- persistSettings(next);
- emitChange();
- }, []);
+ }));
+ },
+ [setSettings],
+ );
const resetSettings = useCallback(() => {
- persistSettings(DEFAULT_APP_SETTINGS);
- emitChange();
- }, []);
+ setSettings(DEFAULT_APP_SETTINGS);
+ }, [setSettings]);
return {
settings,
diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx
index f4298fc22..3f8876ec1 100644
--- a/apps/web/src/components/ChatMarkdown.tsx
+++ b/apps/web/src/components/ChatMarkdown.tsx
@@ -20,13 +20,13 @@ import React, {
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
+import { openInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { readNativeApi } from "../nativeApi";
-import { preferredTerminalEditor } from "../terminal-links";
class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode },
@@ -254,7 +254,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
event.stopPropagation();
const api = readNativeApi();
if (api) {
- void api.shell.openInEditor(targetPath, preferredTerminalEditor());
+ void openInPreferredEditor(api, targetPath);
} else {
console.warn("Native API not found. Unable to open file in editor.");
}
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 4cd64af9f..59e290431 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -1,29 +1,14 @@
-import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
+import { ProjectId, type ProviderKind, type ThreadId } from "@t3tools/contracts";
import { type ChatMessage, type Thread } from "../types";
import { randomUUID } from "~/lib/utils";
import { getAppModelOptions } from "../appSettings";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
+import { Schema } from "effect";
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
const WORKTREE_BRANCH_PREFIX = "t3code";
-export function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
- const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
- if (!stored) return {};
-
- try {
- const parsed: unknown = JSON.parse(stored);
- if (!parsed || typeof parsed !== "object") return {};
- return Object.fromEntries(
- Object.entries(parsed).filter(
- (entry): entry is [string, string] =>
- typeof entry[0] === "string" && typeof entry[1] === "string",
- ),
- );
- } catch {
- return {};
- }
-}
+export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
export function buildLocalDraftThread(
threadId: ThreadId,
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index d81e024f3..76a5610ce 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -148,13 +148,14 @@ import {
collectUserMessageBlobPreviewUrls,
getCustomModelOptionsByProvider,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
+ LastInvokedScriptByProjectSchema,
PullRequestDialogState,
readFileAsDataUrl,
- readLastInvokedScriptByProjectFromStorage,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
SendPhase,
} from "./ChatView.logic";
+import { useLocalStorage } from "~/hooks/useLocalStorage";
const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -267,9 +268,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [composerTrigger, setComposerTrigger] = useState<ComposerTrigger | null>(() =>
detectComposerTrigger(prompt, prompt.length),
);
- const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
- Record<string, string>
- >(() => readLastInvokedScriptByProjectFromStorage());
+ const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(
+ LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
+ {},
+ LastInvokedScriptByProjectSchema,
+ );
const messagesScrollRef = useRef<HTMLDivElement>(null);
const [messagesScrollElement, setMessagesScrollElement] = useState<HTMLDivElement | null>(null);
const shouldAutoScrollRef = useRef(true);
@@ -1196,6 +1199,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setThreadError,
storeNewTerminal,
storeSetActiveTerminal,
+ setLastInvokedScriptByProjectId,
terminalState.activeTerminalId,
terminalState.runningTerminalIds,
terminalState.terminalIds,
@@ -1438,21 +1442,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
[serverThread],
);
- useEffect(() => {
- try {
- if (Object.keys(lastInvokedScriptByProjectId).length === 0) {
- localStorage.removeItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
- return;
- }
- localStorage.setItem(
- LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
- JSON.stringify(lastInvokedScriptByProjectId),
- );
- } catch {
- // Ignore storage write failures (private mode, quota exceeded, etc.)
- }
- }, [lastInvokedScriptByProjectId]);
-
// Auto-scroll on new messages
const messageCount = timelineMessages.length;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx
index 1293f51f7..b0f1b91c3 100644
--- a/apps/web/src/components/DiffPanel.tsx
+++ b/apps/web/src/components/DiffPanel.tsx
@@ -12,11 +12,12 @@ import {
useRef,
useState,
} from "react";
+import { openInPreferredEditor } from "../editorPreferences";
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
-import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
+import { resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
@@ -311,7 +312,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const api = readNativeApi();
if (!api) return;
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
- void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
+ void openInPreferredEditor(api, targetPath).catch((error) => {
console.warn("Failed to open diff file in editor.", error);
});
},
diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx
index 379fb5a84..ea1865bc8 100644
--- a/apps/web/src/components/GitActionsControl.tsx
+++ b/apps/web/src/components/GitActionsControl.tsx
@@ -31,6 +31,7 @@ import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
+import { openInPreferredEditor } from "~/editorPreferences";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
@@ -40,7 +41,7 @@ import {
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
-import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
+import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
interface GitActionsControlProps {
@@ -581,7 +582,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
return;
}
const target = resolvePathLinkTarget(filePath, gitCwd);
- void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
+ void openInPreferredEditor(api, target).catch((error) => {
toastManager.add({
type: "error",
title: "Unable to open file",
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index cce2ed133..7861212e4 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -12,10 +12,10 @@ import {
useState,
} from "react";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
+import { openInPreferredEditor } from "../editorPreferences";
import {
extractTerminalLinks,
isTerminalLinkActivation,
- preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
@@ -236,7 +236,7 @@ function TerminalViewport({
}
const target = resolvePathLinkTarget(match.text, cwd);
- void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
+ void openInPreferredEditor(api, target).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open path",
diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx
index 701204c1b..2e09da03c 100644
--- a/apps/web/src/components/chat/OpenInPicker.tsx
+++ b/apps/web/src/components/chat/OpenInPicker.tsx
@@ -1,6 +1,7 @@
-import { EDITORS, type EditorId, type ResolvedKeybindingsConfig } from "@t3tools/contracts";
-import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import { EditorId, type ResolvedKeybindingsConfig } from "@t3tools/contracts";
+import { memo, useCallback, useEffect, useMemo } from "react";
import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings";
+import { usePreferredEditor } from "../../editorPreferences";
import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
@@ -9,7 +10,35 @@ import { CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
-const LAST_EDITOR_KEY = "t3code:last-editor";
+const resolveOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
+ const baseOptions: ReadonlyArray<{ label: string; Icon: Icon; value: EditorId }> = [
+ {
+ label: "Cursor",
+ Icon: CursorIcon,
+ value: "cursor",
+ },
+ {
+ label: "VS Code",
+ Icon: VisualStudioCode,
+ value: "vscode",
+ },
+ {
+ label: "Zed",
+ Icon: Zed,
+ value: "zed",
+ },
+ {
+ label: isMacPlatform(platform)
+ ? "Finder"
+ : isWindowsPlatform(platform)
+ ? "Explorer"
+ : "Files",
+ Icon: FolderClosedIcon,
+ value: "file-manager",
+ },
+ ];
+ return baseOptions.filter((option) => availableEditors.includes(option.value));
+};
export const OpenInPicker = memo(function OpenInPicker({
keybindings,
@@ -20,61 +49,23 @@ export const OpenInPicker = memo(function OpenInPicker({
availableEditors: ReadonlyArray<EditorId>;
openInCwd: string | null;
}) {
- const [lastEditor, setLastEditor] = useState<EditorId>(() => {
- const stored = localStorage.getItem(LAST_EDITOR_KEY);
- return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
- });
-
- const allOptions = useMemo<Array<{ label: string; Icon: Icon; value: EditorId }>>(
- () => [
- {
- label: "Cursor",
- Icon: CursorIcon,
- value: "cursor",
- },
- {
- label: "VS Code",
- Icon: VisualStudioCode,
- value: "vscode",
- },
- {
- label: "Zed",
- Icon: Zed,
- value: "zed",
- },
- {
- label: isMacPlatform(navigator.platform)
- ? "Finder"
- : isWindowsPlatform(navigator.platform)
- ? "Explorer"
- : "Files",
- Icon: FolderClosedIcon,
- value: "file-manager",
- },
- ],
- [],
- );
+ const [preferredEditor, setPreferredEditor] = usePreferredEditor(availableEditors);
const options = useMemo(
- () => allOptions.filter((option) => availableEditors.includes(option.value)),
- [allOptions, availableEditors],
+ () => resolveOptions(navigator.platform, availableEditors),
+ [availableEditors],
);
-
- const effectiveEditor = options.some((option) => option.value === lastEditor)
- ? lastEditor
- : (options[0]?.value ?? null);
- const primaryOption = options.find(({ value }) => value === effectiveEditor) ?? null;
+ const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
const openInEditor = useCallback(
(editorId: EditorId | null) => {
const api = readNativeApi();
if (!api || !openInCwd) return;
- const editor = editorId ?? effectiveEditor;
+ const editor = editorId ?? preferredEditor;
if (!editor) return;
void api.shell.openInEditor(openInCwd, editor);
- localStorage.setItem(LAST_EDITOR_KEY, editor);
- setLastEditor(editor);
+ setPreferredEditor(editor);
},
- [effectiveEditor, openInCwd, setLastEditor],
+ [preferredEditor, openInCwd, setPreferredEditor],
);
const openFavoriteEditorShortcutLabel = useMemo(
@@ -87,22 +78,22 @@ export const OpenInPicker = memo(function OpenInPicker({
const api = readNativeApi();
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!api || !openInCwd) return;
- if (!effectiveEditor) return;
+ if (!preferredEditor) return;
e.preventDefault();
- void api.shell.openInEditor(openInCwd, effectiveEditor);
+ void api.shell.openInEditor(openInCwd, preferredEditor);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
- }, [effectiveEditor, keybindings, openInCwd]);
+ }, [preferredEditor, keybindings, openInCwd]);
return (
<Group aria-label="Subscription actions">
<Button
size="xs"
variant="outline"
- disabled={!effectiveEditor || !openInCwd}
- onClick={() => openInEditor(effectiveEditor)}
+ disabled={!preferredEditor || !openInCwd}
+ onClick={() => openInEditor(preferredEditor)}
>
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
@@ -120,7 +111,7 @@ export const OpenInPicker = memo(function OpenInPicker({
<MenuItem key={value} onClick={() => openInEditor(value)}>
<Icon aria-hidden="true" className="text-muted-foreground" />
{label}
- {value === effectiveEditor && openFavoriteEditorShortcutLabel && (
+ {value === preferredEditor && openFavoriteEditorShortcutLabel && (
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
)}
</MenuItem>
diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx
index 3876d3513..9f25ea5cc 100644
--- a/apps/web/src/components/ui/sidebar.tsx
+++ b/apps/web/src/components/ui/sidebar.tsx
@@ -18,6 +18,8 @@ import {
import { Skeleton } from "~/components/ui/skeleton";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { useMediaQuery } from "~/hooks/useMediaQuery";
+import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
+import { Schema } from "effect";
const SIDEBAR_COOKIE_NAME = "sidebar_state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
@@ -371,7 +373,7 @@ function SidebarRail({
element.style.removeProperty("transition-duration");
});
if (resolvedResizable?.storageKey && typeof window !== "undefined") {
- window.localStorage.setItem(resolvedResizable.storageKey, String(resizeState.width));
+ setLocalStorageItem(resolvedResizable.storageKey, resizeState.width, Schema.Finite);
}
resolvedResizable?.onResize?.(resizeState.width);
resizeStateRef.current = null;
@@ -541,8 +543,8 @@ function SidebarRail({
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 storedWidth = getLocalStorageItem(resolvedResizable.storageKey, Schema.Finite);
+ if (storedWidth === null) return;
const clampedWidth = clampSidebarWidth(storedWidth, resolvedResizable);
wrapper.style.setProperty("--sidebar-width", `${clampedWidth}px`);
resolvedResizable.onResize?.(clampedWidth);
diff --git a/apps/web/src/editorPreferences.ts b/apps/web/src/editorPreferences.ts
new file mode 100644
index 000000000..ca43f3e5d
--- /dev/null
+++ b/apps/web/src/editorPreferences.ts
@@ -0,0 +1,35 @@
+import { EDITORS, EditorId, NativeApi } from "@t3tools/contracts";
+import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";
+import { useMemo } from "react";
+
+const LAST_EDITOR_KEY = "t3code:last-editor";
+
+export function usePreferredEditor(availableEditors: ReadonlyArray<EditorId>) {
+ const [lastEditor, setLastEditor] = useLocalStorage(LAST_EDITOR_KEY, null, EditorId);
+
+ const effectiveEditor = useMemo(() => {
+ if (lastEditor && availableEditors.includes(lastEditor)) return lastEditor;
+ return EDITORS.find((editor) => availableEditors.includes(editor.id))?.id ?? null;
+ }, [lastEditor, availableEditors]);
+
+ return [effectiveEditor, setLastEditor] as const;
+}
+
+export function resolveAndPersistPreferredEditor(
+ availableEditors: readonly EditorId[],
+): EditorId | null {
+ const availableEditorIds = new Set(availableEditors);
+ const stored = getLocalStorageItem(LAST_EDITOR_KEY, EditorId);
+ if (stored && availableEditorIds.has(stored)) return stored;
+ const editor = EDITORS.find((editor) => availableEditorIds.has(editor.id))?.id ?? null;
+ if (editor) setLocalStorageItem(LAST_EDITOR_KEY, editor, EditorId);
+ return editor ?? null;
+}
+
+export async function openInPreferredEditor(api: NativeApi, targetPath: string): Promise<EditorId> {
+ const { availableEditors } = await api.server.getConfig();
+ const editor = resolveAndPersistPreferredEditor(availableEditors);
+ if (!editor) throw new Error("No available editors found.");
+ await api.shell.openInEditor(targetPath, editor);
+ return editor;
+}
diff --git a/apps/web/src/hooks/useLocalStorage.ts b/apps/web/src/hooks/useLocalStorage.ts
new file mode 100644
index 000000000..da9aa4b88
--- /dev/null
+++ b/apps/web/src/hooks/useLocalStorage.ts
@@ -0,0 +1,143 @@
+import * as Schema from "effect/Schema";
+import * as Record from "effect/Record";
+import { useCallback, useEffect, useRef, useState } from "react";
+
+const isomorphicLocalStorage: Storage =
+ typeof window !== "undefined"
+ ? window.localStorage
+ : (function () {
+ const store = new Map<string, string>();
+ return {
+ clear: () => store.clear(),
+ getItem: (_) => store.get(_) ?? null,
+ key: (_) => Record.keys(store).at(_) ?? null,
+ get length() {
+ return store.size;
+ },
+ removeItem: (_) => store.delete(_),
+ setItem: (_, value) => store.set(_, value),
+ };
+ })();
+
+const decode = <T, E>(schema: Schema.Codec<T, E>, value: string) =>
+ Schema.decodeSync(Schema.fromJsonString(schema))(value);
+
+const encode = <T, E>(schema: Schema.Codec<T, E>, value: T) =>
+ Schema.encodeSync(Schema.fromJsonString(schema))(value);
+
+export const getLocalStorageItem = <T, E>(key: string, schema: Schema.Codec<T, E>): T | null => {
+ const item = isomorphicLocalStorage.getItem(key);
+ return item ? decode(schema, item) : null;
+};
+
+export const setLocalStorageItem = <T, E>(key: string, value: T, schema: Schema.Codec<T, E>) => {
+ const valueToSet = encode(schema, value);
+ isomorphicLocalStorage.setItem(key, valueToSet);
+};
+
+export const removeLocalStorageItem = (key: string) => {
+ isomorphicLocalStorage.removeItem(key);
+};
+
+const LOCAL_STORAGE_CHANGE_EVENT = "t3code:local_storage_change";
+
+interface LocalStorageChangeDetail {
+ key: string;
+}
+
+function dispatchLocalStorageChange(key: string) {
+ if (typeof window === "undefined") return;
+ window.dispatchEvent(
+ new CustomEvent<LocalStorageChangeDetail>(LOCAL_STORAGE_CHANGE_EVENT, {
+ detail: { key },
+ }),
+ );
+}
+
+export function useLocalStorage<T, E>(
+ key: string,
+ initialValue: T,
+ schema: Schema.Codec<T, E>,
+): [T, (value: T | ((val: T) => T)) => void] {
+ // Get the initial value from localStorage or use the provided initialValue
+ const [storedValue, setStoredValue] = useState<T>(() => {
+ try {
+ const item = getLocalStorageItem(key, schema);
+ return item ?? initialValue;
+ } catch (error) {
+ console.error("[LOCALSTORAGE] Error:", error);
+ return initialValue;
+ }
+ });
+
+ // Return a wrapped version of useState's setter function that persists the new value to localStorage
+ const setValue = useCallback(
+ (value: T | ((val: T) => T)) => {
+ try {
+ setStoredValue((prev) => {
+ const valueToStore = typeof value === "function" ? (value as (val: T) => T)(prev) : value;
+ if (valueToStore === null) {
+ removeLocalStorageItem(key);
+ } else {
+ setLocalStorageItem(key, valueToStore, schema);
+ }
+ // Dispatch event after state update completes to avoid nested state updates
+ queueMicrotask(() => dispatchLocalStorageChange(key));
+ return valueToStore;
+ });
+ } catch (error) {
+ console.error("[LOCALSTORAGE] Error:", error);
+ }
+ },
+ [key, schema],
+ );
+
+ const prevKeyRef = useRef(key);
+
+ // Re-sync from localStorage when key changes
+ useEffect(() => {
+ if (prevKeyRef.current !== key) {
+ prevKeyRef.current = key;
+ try {
+ const newValue = getLocalStorageItem(key, schema);
+ setStoredValue(newValue ?? initialValue);
+ } catch (error) {
+ console.error("[LOCALSTORAGE] Error:", error);
+ }
+ }
+ }, [key, initialValue, schema]);
+
+ // Listen for storage events from other tabs AND custom events from the same tab
+ useEffect(() => {
+ const syncFromStorage = () => {
+ try {
+ const newValue = getLocalStorageItem(key, schema);
+ setStoredValue(newValue ?? initialValue);
+ } catch (error) {
+ console.error("[LOCALSTORAGE] Error:", error);
+ }
+ };
+
+ const handleStorageChange = (event: StorageEvent) => {
+ if (event.key === key) {
+ syncFromStorage();
+ }
+ };
+
+ const handleLocalChange = (event: CustomEvent<LocalStorageChangeDetail>) => {
+ if (event.detail.key === key) {
+ syncFromStorage();
+ }
+ };
+
+ window.addEventListener("storage", handleStorageChange);
+ window.addEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener);
+
+ return () => {
+ window.removeEventListener("storage", handleStorageChange);
+ window.removeEventListener(LOCAL_STORAGE_CHANGE_EVENT, handleLocalChange as EventListener);
+ };
+ }, [key, initialValue, schema]);
+
+ return [storedValue, setValue];
+}
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index 2fe07505f..34f9c4b82 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -13,12 +13,12 @@ import { Throttler } from "@tanstack/react-pacer";
import { APP_DISPLAY_NAME } from "../branding";
import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
+import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
-import { preferredTerminalEditor } from "../terminal-links";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
import { providerQueryKeys } from "../lib/providerReactQuery";
@@ -281,9 +281,13 @@ function EventRouter() {
onClick: () => {
void queryClient
.ensureQueryData(serverConfigQueryOptions())
- .then((config) =>
- api.shell.openInEditor(config.keybindingsConfigPath, preferredTerminalEditor()),
- )
+ .then((config) => {
+ const editor = resolveAndPersistPreferredEditor(config.availableEditors);
+ if (!editor) {
+ throw new Error("No available editors found.");
+ }
+ return api.shell.openInEditor(config.keybindingsConfigPath, editor);
+ })
.catch((error) => {
toastManager.add({
type: "error",
diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx
index 93e074442..c0e9a7ef9 100644
--- a/apps/web/src/routes/_chat.settings.tsx
+++ b/apps/web/src/routes/_chat.settings.tsx
@@ -3,13 +3,12 @@ import { useQuery } from "@tanstack/react-query";
import { useCallback, useState } from "react";
import { type ProviderKind } from "@t3tools/contracts";
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
-
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
+import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { ensureNativeApi } from "../nativeApi";
-import { preferredTerminalEditor } from "../terminal-links";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Switch } from "../components/ui/switch";
@@ -98,14 +97,21 @@ function SettingsRouteView() {
const codexBinaryPath = settings.codexBinaryPath;
const codexHomePath = settings.codexHomePath;
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
+ const availableEditors = serverConfigQuery.data?.availableEditors;
const openKeybindingsFile = useCallback(() => {
if (!keybindingsConfigPath) return;
setOpenKeybindingsError(null);
setIsOpeningKeybindings(true);
const api = ensureNativeApi();
+ const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);
+ if (!editor) {
+ setOpenKeybindingsError("No available editors found.");
+ setIsOpeningKeybindings(false);
+ return;
+ }
void api.shell
- .openInEditor(keybindingsConfigPath, preferredTerminalEditor())
+ .openInEditor(keybindingsConfigPath, editor)
.catch((error) => {
setOpenKeybindingsError(
error instanceof Error ? error.message : "Unable to open keybindings file.",
@@ -114,7 +120,7 @@ function SettingsRouteView() {
.finally(() => {
setIsOpeningKeybindings(false);
});
- }, [keybindingsConfigPath]);
+ }, [availableEditors, keybindingsConfigPath]);
const addCustomModel = useCallback(
(provider: ProviderKind) => {
diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts
index 64e18670f..1119fc908 100644
--- a/apps/web/src/terminal-links.ts
+++ b/apps/web/src/terminal-links.ts
@@ -1,4 +1,3 @@
-import { EDITORS, type EditorId } from "@t3tools/contracts";
import { isMacPlatform } from "./lib/utils";
export type TerminalLinkKind = "url" | "path";
@@ -14,7 +13,6 @@ const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
const FILE_PATH_PATTERN =
/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:\\|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
-const LAST_EDITOR_KEY = "t3code:last-editor";
function trimClosingDelimiters(value: string): string {
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
@@ -175,23 +173,3 @@ export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
if (!line) return resolvedPath;
return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;
}
-
-export function preferredTerminalEditor(): EditorId {
- const fallback = EDITORS.find((editor) => editor.command)?.id ?? EDITORS[0]?.id ?? "cursor";
-
- if (typeof window === "undefined") {
- return fallback;
- }
-
- const storedEditor = window.localStorage.getItem(LAST_EDITOR_KEY);
- if (!storedEditor) {
- return fallback;
- }
-
- const configured = EDITORS.find((editor) => editor.id === storedEditor);
- if (!configured?.command) {
- return fallback;
- }
-
- return configured.id;
-}