-
{title}
- {description !== undefined &&
{description}
}
+
+
+
+
+
+ {title}
+
+ {count !== undefined && count > 0 && (
+ · {count}
+ )}
+
+ {description !== undefined &&
{description}
}
+
+ {action}
{children}
@@ -81,6 +98,53 @@ export function Row({
);
}
+/** Rows the size of real ones while the first answer is on its way, so nothing jumps when it lands. */
+export function Placeholder({ rows }: { readonly rows: number }) {
+ return (
+
+ {Array.from({ length: rows }, (_, index) => (
+
+ ))}
+
+ );
+}
+
+/** A setting in a dialog's bordered card: its title and description beside its field. */
+export function DialogRow({
+ title,
+ description,
+ htmlFor,
+ children,
+}: {
+ title: ReactNode;
+ description: ReactNode;
+ /** The field the title labels. */
+ htmlFor?: string | undefined;
+ children: ReactNode;
+}) {
+ return (
+
+
+ {htmlFor === undefined ? (
+ {title}
+ ) : (
+
+ )}
+ {description}
+
+ {children}
+
+ );
+}
+
/** A shortcut as the keys to press. */
export function Keys({ children }: { children: ReactNode }) {
return (
diff --git a/apps/web/src/settings/chat.tsx b/apps/web/src/settings/chat.tsx
deleted file mode 100644
index c51d6ac4..00000000
--- a/apps/web/src/settings/chat.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { isMac } from "@codeworksh/widget/view";
-import { useState } from "react";
-
-import { Switch } from "@/components/ui/switch";
-import { Group, Keys, Page, Row, Section } from "./blocks";
-import { Segmented } from "./controls";
-
-export function ChatSettings() {
- const [anchorPrompts, setAnchorPrompts] = useState(true);
- const [expandWorkLog, setExpandWorkLog] = useState(true);
- const [showUsage, setShowUsage] = useState(true);
- const [smoothReveal, setSmoothReveal] = useState(true);
- const [followUpBehavior, setFollowUpBehavior] = useState<"steer" | "followUp">("steer");
- const [spellcheck, setSpellcheck] = useState(true);
- const [emptySession, setEmptySession] = useState<"games" | "minimal">("games");
-
- return (
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Choose what Enter does while the agent works.{" "}
- {isMac ? "⌘Enter" : "Ctrl+Enter"} sends the other mode.
- >
- }
- >
-
-
-
-
-
-
-
-
-
-
- );
-}
diff --git a/apps/web/src/settings/controls.tsx b/apps/web/src/settings/controls.tsx
index 3a0d7d01..9083bfc3 100644
--- a/apps/web/src/settings/controls.tsx
+++ b/apps/web/src/settings/controls.tsx
@@ -1,8 +1,7 @@
-import { MinusIcon, PlusIcon } from "@phosphor-icons/react";
+import { CheckCircleIcon } from "@phosphor-icons/react";
import type { ReactNode } from "react";
-import { Button } from "@/components/ui/button";
-import { quietField, SavingInput } from "./blocks";
+import { Ago } from "../widgets/time";
export type StatusTone = "success" | "warning" | "danger" | "info" | "muted";
@@ -24,97 +23,30 @@ export function StatusDot({ tone, children }: { readonly tone: StatusTone; reado
);
}
-/** A compact segmented control for choosing one of a few options. */
-export function Segmented
({
- label,
- value,
- options,
- onChange,
-}: {
- readonly label: string;
- readonly value: T;
- readonly options: ReadonlyArray<{ readonly value: T; readonly label: ReactNode }>;
- readonly onChange: (value: T) => void;
-}) {
+/** Whether a machine answers now, else when it last did. */
+export function SeenStatus({ online, seenAt }: { readonly online: boolean; readonly seenAt: number | null }) {
+ if (online) return Online;
+ // Read as a number: a server that predates the field sends none.
+ if (typeof seenAt !== "number") return Never Seen;
return (
-
- {options.map((option) => {
- const active = option.value === value;
- return (
-
- );
- })}
-
+
+
+ Last Seen
+
+
);
}
-/** A numeric stepper with an inline editable input and optional unit suffix. */
-export function Stepper({
- label,
- value,
- min = 0,
- max = 999_999,
- step = 1,
- unit,
- onChange,
-}: {
- readonly label: string;
- readonly value: number;
- readonly min?: number;
- readonly max?: number;
- readonly step?: number;
- readonly unit?: string;
- readonly onChange: (next: number) => void;
-}) {
- const clamp = (n: number) => Math.min(max, Math.max(min, n));
+/** A short confirmation that something just worked, fading in where it appears. */
+export function Done({ children }: { readonly children: ReactNode }) {
return (
-
-
-
-
{
- const parsed = Number(typed);
- if (Number.isFinite(parsed)) onChange(clamp(Math.round(parsed)));
- }}
- />
-
-
- {unit !== undefined &&
{unit}}
-
+
+
+ {children}
+
);
}
diff --git a/apps/web/src/settings/general.tsx b/apps/web/src/settings/general.tsx
deleted file mode 100644
index 896da1ec..00000000
--- a/apps/web/src/settings/general.tsx
+++ /dev/null
@@ -1,205 +0,0 @@
-import { ArrowClockwiseIcon, CheckIcon, CopyIcon } from "@phosphor-icons/react";
-import { isMac } from "@codeworksh/widget/view";
-import { useState } from "react";
-
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { Switch } from "@/components/ui/switch";
-import { Code, Group, Keys, Page, quietField, Row, Section } from "./blocks";
-import { Badge } from "./servers/local";
-
-const VERSION = "0.4.2";
-const HOME_PATH = "~/.codework";
-
-const EDITORS = [
- { id: "cursor", label: "Cursor" },
- { id: "vscode", label: "VS Code" },
- { id: "zed", label: "Zed" },
- { id: "system", label: "System default" },
-] as const;
-
-const TERMINALS = [
- { id: "ghostty", label: "Ghostty" },
- { id: "iterm", label: "iTerm2" },
- { id: "warp", label: "Warp" },
- { id: "terminal", label: "Terminal" },
-] as const;
-
-const RELEASE_HIGHLIGHTS = [
- "Streamable HTTP and stdio MCP server support with OAuth 2.1 sign-in and deferred tool search.",
- "Thread forking at any committed message with inherited conversation history.",
- "Tabbed tiling and monocle window layouts with keyboard navigation.",
- "Local and cloud sandbox drivers for isolated session execution.",
-] as const;
-
-export function GeneralSettings() {
- const [notifications, setNotifications] = useState(true);
- const [sounds, setSounds] = useState(false);
- const [quickComposer, setQuickComposer] = useState(true);
- const [confirmDelete, setConfirmDelete] = useState(true);
- const [editor, setEditor] = useState("cursor");
- const [terminal, setTerminal] = useState("ghostty");
- const [checking, setChecking] = useState(false);
- const [updateStatus, setUpdateStatus] = useState("CodeWork is up to date.");
- const [whatsNewOpen, setWhatsNewOpen] = useState(false);
- const [copied, setCopied] = useState(false);
-
- const checkUpdates = () => {
- setChecking(true);
- setTimeout(() => {
- setChecking(false);
- setUpdateStatus(`Checked just now · v${VERSION} is the latest release.`);
- }, 600);
- };
-
- const copyHome = () => {
- void navigator.clipboard?.writeText(HOME_PATH);
- setCopied(true);
- setTimeout(() => setCopied(false), 1800);
- };
-
- return (
-
-
-
-
-
-
- Press {isMac ? "⌘⇧Space" : "Ctrl+Shift+Space"} from any app to start or steer a
- session.
- >
- }
- >
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Version
- v{VERSION}
- Latest
-
- }
- description={updateStatus}
- >
-
-
-
-
-
-
- User settings (settings.jsonc), MCP servers (mcp.json), and OAuth
- tokens live in {HOME_PATH}.
- >
- }
- >
-
-
-
-
-
- {whatsNewOpen && (
-
- )}
-
- );
-}
diff --git a/apps/web/src/settings/keybindings.tsx b/apps/web/src/settings/keybindings.tsx
deleted file mode 100644
index d137ae02..00000000
--- a/apps/web/src/settings/keybindings.tsx
+++ /dev/null
@@ -1,317 +0,0 @@
-import { ArrowCounterClockwiseIcon, KeyboardIcon, MagnifyingGlassIcon } from "@phosphor-icons/react";
-import { isMac } from "@codeworksh/widget/view";
-import { type KeyboardEvent, useState } from "react";
-
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Group, Keys, Page, quietField, Section } from "./blocks";
-import { EmptyState } from "./controls";
-import { Badge } from "./servers/local";
-
-interface ShortcutItem {
- readonly id: string;
- readonly group: "Navigation" | "Session & Composer" | "Window Layout";
- readonly label: string;
- readonly when: string;
- readonly defaultMac: string;
- readonly defaultOther: string;
- readonly fixed?: boolean;
-}
-
-const SHORTCUTS: readonly ShortcutItem[] = [
- {
- id: "palette",
- group: "Navigation",
- label: "Command palette",
- when: "Always",
- defaultMac: "⌘K",
- defaultOther: "Ctrl+K",
- },
- {
- id: "tabs",
- group: "Navigation",
- label: "Switch to tab 1–9",
- when: "Always",
- defaultMac: "⌘1 … ⌘9",
- defaultOther: "Ctrl+1 … Ctrl+9",
- fixed: true,
- },
- {
- id: "threads",
- group: "Navigation",
- label: "Go to Threads",
- when: "Always",
- defaultMac: "⌘⇧T",
- defaultOther: "Ctrl+Shift+T",
- },
- {
- id: "projects",
- group: "Navigation",
- label: "Go to Projects",
- when: "Always",
- defaultMac: "⌘⇧P",
- defaultOther: "Ctrl+Shift+P",
- },
- {
- id: "sidebar",
- group: "Navigation",
- label: "Toggle sidebar",
- when: "Always",
- defaultMac: "⌘B",
- defaultOther: "Ctrl+B",
- },
- {
- id: "settings",
- group: "Navigation",
- label: "Open Settings",
- when: "Always",
- defaultMac: "⌘,",
- defaultOther: "Ctrl+,",
- },
- {
- id: "send",
- group: "Session & Composer",
- label: "Send prompt or steer active turn",
- when: "Composer focused",
- defaultMac: "Enter",
- defaultOther: "Enter",
- fixed: true,
- },
- {
- id: "followup",
- group: "Session & Composer",
- label: "Queue follow-up for next turn",
- when: "Composer focused",
- defaultMac: "⌘Enter",
- defaultOther: "Ctrl+Enter",
- },
- {
- id: "stop",
- group: "Session & Composer",
- label: "Stop running thread",
- when: "Thread running",
- defaultMac: "Esc",
- defaultOther: "Esc",
- fixed: true,
- },
- {
- id: "new-session",
- group: "Session & Composer",
- label: "New session",
- when: "Always",
- defaultMac: "⌘N",
- defaultOther: "Ctrl+N",
- },
- {
- id: "fork-thread",
- group: "Session & Composer",
- label: "Fork conversation at latest turn",
- when: "Session focused",
- defaultMac: "⌘⇧F",
- defaultOther: "Ctrl+Shift+F",
- },
- {
- id: "model-picker",
- group: "Session & Composer",
- label: "Switch model",
- when: "Session focused",
- defaultMac: "⌘M",
- defaultOther: "Ctrl+M",
- },
- {
- id: "layout-toggle",
- group: "Window Layout",
- label: "Toggle Tiled / Focused view",
- when: "Tab active",
- defaultMac: "⌘⇧L",
- defaultOther: "Ctrl+Shift+L",
- },
- {
- id: "panel-next",
- group: "Window Layout",
- label: "Focus next panel",
- when: "Tab active",
- defaultMac: "⌘]",
- defaultOther: "Ctrl+]",
- },
- {
- id: "panel-prev",
- group: "Window Layout",
- label: "Focus previous panel",
- when: "Tab active",
- defaultMac: "⌘[",
- defaultOther: "Ctrl+[",
- },
- {
- id: "panel-pin",
- group: "Window Layout",
- label: "Pin or unpin focused panel",
- when: "Tab active",
- defaultMac: "⌘⇧I",
- defaultOther: "Ctrl+Shift+I",
- },
- {
- id: "panel-close",
- group: "Window Layout",
- label: "Close focused panel",
- when: "Tab active",
- defaultMac: "⌘W",
- defaultOther: "Ctrl+W",
- },
-];
-
-const GROUPS = ["Navigation", "Session & Composer", "Window Layout"] as const;
-
-function formatRecordedKey(event: KeyboardEvent): string | null {
- if (["Meta", "Control", "Alt", "Shift"].includes(event.key)) return null;
- const parts: string[] = [];
- if (isMac) {
- if (event.ctrlKey) parts.push("⌃");
- if (event.altKey) parts.push("⌥");
- if (event.shiftKey) parts.push("⇧");
- if (event.metaKey) parts.push("⌘");
- } else {
- if (event.ctrlKey) parts.push("Ctrl+");
- if (event.altKey) parts.push("Alt+");
- if (event.shiftKey) parts.push("Shift+");
- if (event.metaKey) parts.push("Meta+");
- }
- const key = event.key.length === 1 ? event.key.toUpperCase() : event.key;
- return `${parts.join("")}${key}`;
-}
-
-export function KeybindingsSettings() {
- const [query, setQuery] = useState("");
- const [custom, setCustom] = useState>>({});
- const [recordingId, setRecordingId] = useState(null);
-
- const normalized = query.trim().toLowerCase();
- const filtered = SHORTCUTS.filter((item) => {
- if (normalized === "") return true;
- const binding = custom[item.id] ?? (isMac ? item.defaultMac : item.defaultOther);
- return `${item.label} ${item.group} ${item.when} ${binding}`.toLowerCase().includes(normalized);
- });
-
- const hasCustom = Object.keys(custom).length > 0;
-
- return (
- setCustom({})}>
-
- Reset all
-
- ) : undefined
- }
- >
-
-
- setQuery(event.target.value)}
- />
-
-
- {filtered.length === 0 ? (
- }
- title="No matching shortcuts"
- description={`No keybinding matches “${query}”.`}
- />
- ) : (
- GROUPS.map((group) => {
- const items = filtered.filter((item) => item.group === group);
- if (items.length === 0) return null;
- return (
-
-
- {items.map((item) => {
- const defaultKeys = isMac ? item.defaultMac : item.defaultOther;
- const currentKeys = custom[item.id] ?? defaultKeys;
- const modified = custom[item.id] !== undefined && custom[item.id] !== defaultKeys;
- const recording = recordingId === item.id;
- return (
-
-
-
- {item.label}
- {modified && Modified}
-
-
{item.when}
-
-
- {modified && (
-
- )}
- {item.fixed ? (
-
- {currentKeys}
-
- ) : (
-
- )}
-
-
- );
- })}
-
-
- );
- })
- )}
-
- );
-}
diff --git a/apps/web/src/settings/layout.tsx b/apps/web/src/settings/layout.tsx
index 4f79e1f3..a43e42be 100644
--- a/apps/web/src/settings/layout.tsx
+++ b/apps/web/src/settings/layout.tsx
@@ -1,6 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import { ArrowLeftIcon, MagnifyingGlassIcon } from "@phosphor-icons/react";
-import { Link, Outlet, useMatchRoute, useNavigate } from "@tanstack/react-router";
+import { Link, Outlet, useLocation, useNavigate } from "@tanstack/react-router";
import { useScrollFade } from "@/hooks/use-scroll-fade";
import { AsyncResult } from "effect/reactivity";
@@ -27,7 +27,7 @@ import { search } from "./sections";
/** Settings replaces the sessions list within the same app shell and sidebar controls. */
export function SettingsSidebar() {
- const matchRoute = useMatchRoute();
+ const pathname = useLocation({ select: (location) => location.pathname });
const navigate = useNavigate();
const back = useTabReturn();
const [query, setQuery] = useState("");
@@ -84,7 +84,9 @@ export function SettingsSidebar() {
{matches
.filter((section) => section.group === group)
.map(({ to, label, icon: Icon }) => {
- const active = matchRoute({ to, params }) !== false;
+ // By path, so a page under a section (one paired machine) keeps it highlighted.
+ const path = to.replace("$workspaceId", params.workspaceId);
+ const active = pathname === path || pathname.startsWith(`${path}/`);
return (
option.id === workspaceId)
- : undefined;
- return (
-
-
- {workspace === undefined ? (
- }
- title="No Workspace"
- description="Your Workspace couldn't be loaded, so its Machines are unknown."
- />
- ) : (
- <>
-
-
- >
- )}
-
- );
-}
-
-function ThisMachine({ workspace }: { readonly workspace: Relay.Workspace | undefined }) {
- const machineAtom = useMachineAtom();
- const machine = useAtomValue(machineAtom);
- const refresh = useAtomRefresh(machineAtom);
- const rename = useAtomSet(renameAtom, { mode: "promise" });
- const [error, setError] = useState(null);
- if (AsyncResult.isInitial(machine)) {
- return (
-
- );
- }
- if (!AsyncResult.isSuccess(machine)) {
- return (
-
- );
- }
- const status = machine.value;
- const linked = workspace !== undefined && status.workspaces.some((option) => option.id === workspace.id);
- return (
-
-
-
-
- {
- setError(null);
- rename({ payload: { givenName } })
- .then(refresh)
- .catch((cause: unknown) => setError(messageOf(cause)));
- }}
- />
-
-
- {status.id ?? "Assigned on first connect"}
-
- {workspace !== undefined && !linked && (
-
-
-
- )}
-
-
-
- );
-}
-
-/** Machines that ran `codework connect --workspace` for this workspace, each with the code to check. */
-function Waiting({ workspace }: { readonly workspace: Relay.Workspace }) {
- const pairings = useAtomValue(pairingsAtom(workspace.id));
- const refreshPairings = useAtomRefresh(pairingsAtom(workspace.id));
- const refreshMachines = useAtomRefresh(machinesAtom(workspace.id));
- const approve = useAtomSet(approveAtom, { mode: "promise" });
- const decline = useAtomSet(declineAtom, { mode: "promise" });
- const [busy, setBusy] = useState>(new Set());
- const [error, setError] = useState(null);
- useEffect(() => {
- const timer = setInterval(refreshPairings, PENDING_MS);
- return () => clearInterval(timer);
- }, [refreshPairings]);
-
- const list = AsyncResult.isSuccess(pairings) ? pairings.value : [];
- // A connect leaves the list once its machine takes the link (or gives up): the machines list moves.
- const codes = list.map((pairing) => pairing.userCode).join(" ");
- const previous = useRef(codes);
- useEffect(() => {
- const now = new Set(codes.split(" "));
- if (previous.current.split(" ").some((code) => code !== "" && !now.has(code))) refreshMachines();
- previous.current = codes;
- }, [codes, refreshMachines]);
- const act = (pairing: Relay.PendingPairing, how: "approve" | "decline") => {
- setBusy((codes) => new Set(codes).add(pairing.userCode));
- setError(null);
- const input = { userCode: pairing.userCode, workspaceId: workspace.id };
- (how === "approve" ? approve(input) : decline(input))
- .then(() => {
- refreshPairings();
- refreshMachines();
- })
- .catch((cause: unknown) => setError(relayFailure(cause)))
- .finally(() =>
- setBusy((codes) => {
- const next = new Set(codes);
- next.delete(pairing.userCode);
- return next;
- }),
- );
- };
- const command = `codework connect --workspace ${workspace.id}`;
- return (
-
-
-
- Waiting to Join{list.length > 0 && · {list.length}}
-
-
-
- {list.map((pairing) => {
- const approved = pairing.status === "approved";
- const working = busy.has(pairing.userCode) || approved;
- return (
-
-
- {pairing.machine.os} {pairing.machine.arch} · {pairing.machine.id} · Code{" "}
- {pairing.userCode}
- {pairing.replaces && <> · Replaces the connected Machine>}
- >
- }
- >
-
-
-
-
-
-
- );
- })}
-
-
- Run this on a Machine to add it. It shows up here with its Code; check it matches before approving.
-
-
- {error !== null &&
{error}
}
-
-
-
-
- );
-}
-
-/**
- * The way in for a machine that isn't listed (its connect didn't name this workspace): type the code it
- * shows. Enter adds it; the field clears and keeps focus for the next.
- */
-function ManualCode({ workspace, onAdded }: { readonly workspace: Relay.Workspace; readonly onAdded: () => void }) {
- const input = useRef(null);
- const approve = useAtomSet(approveAtom, { mode: "promise" });
- const [open, setOpen] = useState(false);
- const [code, setCode] = useState("");
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState(null);
- const [added, setAdded] = useState(null);
- const submit = () => {
- if (busy) return;
- if (code.trim() === "") {
- setError("Enter the Code the Machine shows.");
- return;
- }
- setBusy(true);
- setError(null);
- approve({ userCode: code.trim().toUpperCase(), workspaceId: workspace.id })
- .then(({ machine }) => {
- setAdded(machine.givenName ?? machine.localHostName);
- setCode("");
- onAdded();
- })
- .catch((cause: unknown) => setError(relayFailure(cause)))
- .finally(() => {
- setBusy(false);
- input.current?.focus();
- });
- };
- return (
-
-
-
input.current?.focus({ preventScroll: true })}>
-
-
-
- );
-}
-
-function WorkspaceMachines({ workspace }: { readonly workspace: Relay.Workspace }) {
- const machines = useAtomValue(machinesAtom(workspace.id));
- const refresh = useAtomRefresh(machinesAtom(workspace.id));
- const machineAtom = useMachineAtom();
- const local = useAtomValue(machineAtom);
- const refreshLocal = useAtomRefresh(machineAtom);
- const me = useAtomValue(meAtom);
- const localId = AsyncResult.isSuccess(local) ? local.value.id : null;
- const localKey = AsyncResult.isSuccess(local)
- ? local.value.workspaces.find((option) => option.id === workspace.id)?.keyId
- : undefined;
- const accountId = AsyncResult.isSuccess(me) ? me.value.account.id : null;
- // Machines seen when the page opened; any other is new and arrives with a highlight.
- const [seen, setSeen] = useState | null>(null);
- // The relay's list and this machine's own record both move: a link removed elsewhere is forgotten on
- // the machine's next heartbeat, and a terminal can connect or disconnect it.
- useEffect(() => {
- const timer = setInterval(() => {
- refresh();
- refreshLocal();
- }, REFRESH_MS);
- return () => clearInterval(timer);
- }, [refresh, refreshLocal]);
- // Back in reach: ask now instead of on the next tick.
- const reach = useAtomValue(reachAtom);
- useEffect(() => {
- if (reach === "ok") refresh();
- }, [reach, refresh]);
-
- if (AsyncResult.isInitial(machines)) {
- return (
-
- );
- }
- // Out of reach, the list the relay last gave stays, marked as such; with none yet, there is nothing to show.
- const last = AsyncResult.isFailure(machines) ? Option.getOrUndefined(machines.previousSuccess) : undefined;
- if (AsyncResult.isFailure(machines) && last === undefined) {
- return (
-
- );
- }
- const stale = last !== undefined;
- const list = AsyncResult.isSuccess(machines) ? machines.value : (last?.value ?? []);
- if (seen === null && AsyncResult.isSuccess(machines)) setSeen(new Set(list.map((machine) => machine.id)));
- // This machine first, then the newest: a machine just added appears where you are looking.
- const ordered = [
- ...list.filter((machine) => machine.id === localId),
- ...list.filter((machine) => machine.id !== localId).reverse(),
- ];
- return (
- 0 ? ` · ${list.length}` : ""}`}
- description={stale ? "As CodeWork last said; it can't be reached now." : undefined}
- >
-
- {list.length === 0 ? (
- }
- title="No Machines Yet"
- description="Set up this Machine, or run codework connect on another."
- />
- ) : (
-
- {ordered.map((machine) => (
-
- ))}
-
- )}
-
-
- );
-}
-
-function MachineRow({
- machine,
- workspace,
- isLocal,
- strayLocal,
- fresh,
- canRemove,
- stale,
- onGone,
-}: {
- readonly machine: Relay.Machine;
- readonly workspace: Relay.Workspace;
- readonly isLocal: boolean;
- /** This machine's id under a key it doesn't hold: a link it lost, which only Remove clears. */
- readonly strayLocal: boolean;
- /** The last list the relay gave, while it can't be reached: online state is unknown and nothing acts. */
- readonly stale: boolean;
- readonly fresh: boolean;
- readonly canRemove: boolean;
- readonly onGone: () => void;
-}) {
- const [leaving, setLeaving] = useState(false);
- const [tint, setTint] = useState(fresh);
- useEffect(() => {
- if (!tint) return;
- const timer = setTimeout(() => setTint(false), 1600);
- return () => clearTimeout(timer);
- }, [tint]);
- const name = machine.givenName ?? machine.localHostName;
- return (
-
-
-
-
- {name}
- {isLocal && This Machine}
- {strayLocal && This Machine · Not Connected Here}
-
- }
- description={`${machine.os} ${machine.arch} · v${machine.version} · ${machine.id}`}
- >
- {stale ? (
- Unknown
- ) : machine.online ? (
- Online
- ) : machine.lastSeenAt === null ? (
- Never Seen
- ) : (
-
- Last Seen
-
- )}
- {!stale && (isLocal || canRemove || strayLocal) && (
- {
- setLeaving(true);
- setTimeout(onGone, 260);
- }}
- />
- )}
-
-
-
-
- );
-}
-
-/** This machine disconnects itself; another is removed by its owner or a workspace owner or admin. */
-function MachineMenu({
- name,
- machineId,
- keyId,
- workspace,
- isLocal,
- onDone,
-}: {
- readonly name: string;
- readonly machineId: string;
- readonly keyId: string;
- readonly workspace: Relay.Workspace;
- readonly isLocal: boolean;
- readonly onDone: () => void;
-}) {
- const disconnect = useAtomSet(disconnectAtom, { mode: "promise" });
- const remove = useAtomSet(removeMachineAtom, { mode: "promise" });
- const refreshLocal = useAtomRefresh(useMachineAtom());
- const [asking, setAsking] = useState(false);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState(null);
- const confirm = () => {
- setBusy(true);
- setError(null);
- const removeAsPerson = () => remove({ workspaceId: workspace.id, machineId, keyId, afterDisconnect: isLocal });
- (isLocal
- ? disconnect({ payload: { workspaceId: workspace.id, keyId } })
- // The relay didn't confirm the machine's own revoke: remove it as the signed-in person instead.
- .then(({ revoked }) =>
- revoked
- ? undefined
- : removeAsPerson().catch(() => {
- throw new Error(
- "Disconnected here, but CodeWork's servers didn't confirm. Remove it from the list when you're back online.",
- );
- }),
- )
- .finally(refreshLocal)
- : removeAsPerson()
- )
- .then(() => {
- setAsking(false);
- onDone();
- })
- .catch((cause: unknown) => setError(relayFailure(cause)))
- .finally(() => setBusy(false));
- };
- return (
- <>
-
-
-
-
-
- setAsking(true)}>
- {isLocal ? "Disconnect…" : `Remove from ${workspace.name}…`}
-
-
-
- !busy && setAsking(next)}>
-
-
- {isLocal ? `Disconnect ${name}?` : `Remove ${name}?`}
-
- {isLocal
- ? `It leaves ${workspace.name} and stops showing up here. Connect it again from Setup.`
- : `It's disconnected from ${workspace.name}. It can join again with codework connect.`}
-
-
- {error !== null && {error}
}
-
- Cancel
- {
- // Held open until the call returns, so a failure shows here.
- event.preventDefault();
- confirm();
- }}
- >
- {busy ? (isLocal ? "Disconnecting…" : "Removing…") : isLocal ? "Disconnect" : "Remove"}
-
-
-
-
- >
- );
-}
-
-/** Content that replaces a placeholder fades in where it stood, instead of cutting over. */
-function Loaded({ children }: { readonly children: ReactNode }) {
- return (
-
- {children}
-
- );
-}
-
-/** Rows the size of real ones while the first answer is on its way, so nothing jumps when it lands. */
-function Placeholder({ rows }: { readonly rows: number }) {
- return (
-
- {Array.from({ length: rows }, (_, index) => (
-
- ))}
-
- );
-}
diff --git a/apps/web/src/settings/machines/machine.tsx b/apps/web/src/settings/machines/machine.tsx
new file mode 100644
index 00000000..6f482a87
--- /dev/null
+++ b/apps/web/src/settings/machines/machine.tsx
@@ -0,0 +1,399 @@
+import { useAtomSet } from "@effect/atom-react";
+import type { RemoteServerStatus } from "@codeworksh/contract";
+import type { Relay } from "@codeworksh/schema";
+import { CaretLeftIcon, LinkBreakIcon } from "@phosphor-icons/react";
+import { Link, useNavigate } from "@tanstack/react-router";
+import { AsyncResult } from "effect/reactivity";
+import { type ReactNode, useEffect, useRef, useState } from "react";
+
+import { BusyLabel } from "@/components/busy";
+import { CopyCommand } from "@/components/copyable";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { messageOf } from "@/lib/utils";
+import { Server } from "../../kernel/rpc";
+import { removeAtom, updateAtom } from "../../kernel/servers";
+import { useConnect } from "../../shell/connect";
+import { Group, Page, Placeholder, quietField, Row, SavingInput, Section } from "../blocks";
+import { EmptyState } from "../controls";
+import { Badge } from "../servers/local";
+import { addressOf, PairAgain, urlOf } from "./pair";
+import { isLinked, linkText, Status, usePaired, useWorkspace } from "./shared";
+import { type Target, UnlinkDialog } from "./unlink";
+
+const labelAtom = Server.mutation("servers.label");
+
+/** One paired machine, by its id. */
+export function PairedMachine({ id }: { readonly id: string }) {
+ const paired = usePaired();
+ const { ready, workspace } = useWorkspace();
+ if (!AsyncResult.isSuccess(paired) || !ready) {
+ return (
+ // A blank title holds its line, so nothing moves when the machine arrives.
+
+ {AsyncResult.isFailure(paired) ? (
+
+ The app server did not answer.
+
+ ) : (
+
+ )}
+
+ );
+ }
+ const server = paired.value.find((each) => each.id === id);
+ if (server === undefined) return ;
+ return ;
+}
+
+/**
+ * No paired machine has the id in the address: it was removed, or the link is old. It says so and
+ * offers the list, in the card the list itself uses when it is empty.
+ */
+function Missing() {
+ return (
+
+
+
+
Machine Not Found
+ }
+ title="Machine Not Found"
+ description="It is no longer paired with this computer, or does not exist"
+ action={
+
+ }
+ />
+
+
+ );
+}
+
+/** The way back to the list, in the panel's top-left corner, outside the content column. */
+function Back({ focus = false }: { readonly focus?: boolean }) {
+ const back = useRef(null);
+ // The link that led here is gone with the list; focus lands on the way back instead of the page.
+ useEffect(() => {
+ if (focus) back.current?.focus({ preventScroll: true });
+ }, [focus]);
+ return (
+
+
+ Machines
+
+ );
+}
+
+/**
+ * A page under the list. The way back sits in the panel's top-left corner, outside the column, so the
+ * title stays where the list's title is.
+ */
+function Sub({
+ title,
+ description,
+ children,
+}: {
+ readonly title: string;
+ readonly description?: ReactNode;
+ readonly children?: ReactNode;
+}) {
+ return (
+
+ );
+}
+
+function Detail({
+ server,
+ workspace,
+}: {
+ readonly server: RemoteServerStatus;
+ readonly workspace: Relay.Workspace | undefined;
+}) {
+ const label = useAtomSet(labelAtom, { mode: "promise" });
+ const update = useAtomSet(updateAtom, { mode: "promise" });
+ const [labelError, setLabelError] = useState(null);
+ const [addressError, setAddressError] = useState(null);
+ const address = addressOf(server.url);
+ const linked = workspace !== undefined && isLinked(server, workspace);
+ const readdress = (typed: string) => {
+ setAddressError(null);
+ const url = urlOf(typed);
+ if (url === "") return setAddressError("Enter the Machine’s address.");
+ if (url === server.url) return;
+ update({ payload: { id: server.id, url } }).catch((cause: unknown) => setAddressError(messageOf(cause)));
+ };
+ return (
+
+
+ {workspace !== undefined && {linkText(linked, workspace)}}
+
+ }
+ >
+ {!server.paired && (
+
+ )}
+
+
+
+ {
+ setLabelError(null);
+ label({ payload: { id: server.id, label: next } }).catch((cause: unknown) =>
+ setLabelError(messageOf(cause)),
+ );
+ }}
+ />
+
+
+ {server.host ? (
+
+
+
+ ) : (
+ Unknown
+ )}
+
+
+
+
+
+ {server.version ? (
+ v{server.version}
+ ) : (
+ Unknown
+ )}
+
+
+
+ {workspace !== undefined && (
+
+ )}
+
+
+ );
+}
+
+/** Whether the machine is in the workspace, and the one action that changes it. */
+function Membership({
+ server,
+ workspace,
+ linked,
+}: {
+ readonly server: RemoteServerStatus;
+ readonly workspace: Relay.Workspace;
+ readonly linked: boolean;
+}) {
+ const [unlinking, setUnlinking] = useState(null);
+ const [linking, setLinking] = useState(false);
+ const [error, setError] = useState(null);
+ const action = useRef(null);
+ const link = server.workspaces.find((each) => each.id === workspace.id);
+ const target: Target | undefined =
+ link === undefined || server.machineId === null
+ ? undefined
+ : {
+ name: server.name,
+ workspace,
+ machineId: server.machineId,
+ keyId: link.keyId,
+ // Without its pairing it can't be asked; its link is removed at the relay instead.
+ via: server.paired ? { kind: "paired", serverId: server.id } : { kind: "relay" },
+ };
+ const title = linkText(linked, workspace);
+ return (
+ <>
+
+ {title}
+
+ }
+ description={
+ error !== null ? (
+
+ {error}
+
+ ) : linked ? (
+ `It shows up for everyone in ${workspace.name}`
+ ) : server.paired ? (
+ `Link it to add it to ${workspace.name}`
+ ) : (
+ "Pair it again to Link it"
+ )
+ }
+ >
+ {/* Its control changes with the link; focus comes back to whichever is here. */}
+
+ {target !== undefined ? (
+
+ ) : (
+
+ )}
+
+
+ {linking && (
+ {
+ setLinking(false);
+ setError(failure);
+ }}
+ />
+ )}
+ setUnlinking(null)}
+ returnFocus={() => action.current?.querySelector("button")}
+ />
+ >
+ );
+}
+
+/**
+ * Links a paired machine while mounted: starts the connect on it, approves its code as the signed-in
+ * member, and ends once the link arrives, or with the failure. Unmounting cancels the connect.
+ */
+function Linking({
+ workspaceId,
+ serverId,
+ onEnd,
+}: {
+ readonly workspaceId: string;
+ readonly serverId: string;
+ readonly onEnd: (failure: string | null) => void;
+}) {
+ const { phase, error, act } = useConnect(workspaceId, serverId);
+ const ended = error !== null ? error : phase === "connected" ? null : undefined;
+ useEffect(() => {
+ if (ended !== undefined) onEnd(ended);
+ else if (phase === "code") act();
+ });
+ return null;
+}
+
+/** Forgets the machine here, once confirmed, and goes back to the list. */
+function Remove({ server }: { readonly server: RemoteServerStatus }) {
+ const remove = useAtomSet(removeAtom, { mode: "promise" });
+ const navigate = useNavigate();
+ const [asking, setAsking] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+ const confirm = () => {
+ setBusy(true);
+ setError(null);
+ remove({ payload: { id: server.id } })
+ .then(() => navigate({ to: "/settings/machines" }))
+ .catch((cause: unknown) => {
+ setBusy(false);
+ setError(messageOf(cause));
+ });
+ };
+ return (
+ <>
+
+ !busy && setAsking(next)}>
+
+
+ Remove {server.name}?
+
+ Its threads leave this computer’s sidebar. Nothing on the Machine is deleted, and it can be paired
+ again.
+
+
+ {error !== null && {error}
}
+
+ Cancel
+ {
+ // Held open until the call returns, so a failure shows here.
+ event.preventDefault();
+ confirm();
+ }}
+ >
+ {busy ? "Removing…" : "Remove"}
+
+
+
+
+ >
+ );
+}
diff --git a/apps/web/src/settings/machines/page.tsx b/apps/web/src/settings/machines/page.tsx
new file mode 100644
index 00000000..c961d54c
--- /dev/null
+++ b/apps/web/src/settings/machines/page.tsx
@@ -0,0 +1,525 @@
+import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
+import type { RemoteServerStatus } from "@codeworksh/contract";
+import { DevicesIcon, DotsThreeIcon, PlusIcon, UsersThreeIcon } from "@phosphor-icons/react";
+import type { Relay } from "@codeworksh/schema";
+import { Link } from "@tanstack/react-router";
+import { Option } from "effect";
+import { AsyncResult } from "effect/reactivity";
+import { useEffect, useRef, useState } from "react";
+
+import { CopyCommand } from "@/components/copyable";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { messageOf } from "@/lib/utils";
+import { isSignedInApp } from "../../auth";
+import { machinesAtom, meAtom, reachAtom, relayFailure } from "../../kernel/relay";
+import { Server } from "../../kernel/rpc";
+import { useMachineAtom } from "../../shell/connect";
+import { Group, Page, Placeholder, quietField, Row, SavingInput, Section } from "../blocks";
+import { Done, EmptyState, SeenStatus, StatusDot } from "../controls";
+import { Badge } from "../servers/local";
+import { addressOf, PairDialog } from "./pair";
+import { isLinked, linkText, Loaded, MachineRow, Status, usePaired, useWorkspace } from "./shared";
+import { type Target, UnlinkDialog } from "./unlink";
+import { Waiting } from "./waiting";
+
+const renameAtom = Server.mutation("machine.rename");
+
+/** How often the list asks the relay again, so online and offline stay current while it is open. */
+const REFRESH_MS = 15_000;
+
+/** This machine, the machines this computer is paired with, and those of the workspace the app works in. */
+export function MachinesSettings() {
+ const { ready, workspace } = useWorkspace();
+ const paired = usePaired();
+ // The machines this computer reaches itself are listed once, as paired.
+ const pairedIds = new Set(
+ AsyncResult.isSuccess(paired)
+ ? paired.value.flatMap((server) => (server.machineId === null ? [] : [server.machineId]))
+ : [],
+ );
+ return (
+
+
+
+ {workspace !== undefined ? (
+ <>
+
+
+ >
+ ) : (
+ // Signed in, the workspace's sections hold their place until the account is known.
+ isSignedInApp &&
+ !ready && (
+ <>
+
+
+ >
+ )
+ )}
+
+ );
+}
+
+function ThisMachine({
+ workspace,
+ ready,
+}: {
+ readonly workspace: Relay.Workspace | undefined;
+ /** Whether the workspace is known yet: the last row depends on it, so the section waits for it. */
+ readonly ready: boolean;
+}) {
+ const machineAtom = useMachineAtom();
+ const machine = useAtomValue(machineAtom);
+ const refresh = useAtomRefresh(machineAtom);
+ const rename = useAtomSet(renameAtom, { mode: "promise" });
+ const [error, setError] = useState(null);
+ const [unlinking, setUnlinking] = useState(null);
+ const action = useRef(null);
+ // The rows the answer brings, held from the start so nothing below moves when it lands.
+ if (AsyncResult.isInitial(machine) || !ready) {
+ return (
+
+ );
+ }
+ if (!AsyncResult.isSuccess(machine)) {
+ return (
+
+ );
+ }
+ const status = machine.value;
+ const machineId = status.id;
+ const link =
+ workspace === undefined || machineId === null
+ ? undefined
+ : status.workspaces.find((option) => option.id === workspace.id);
+ const name = status.givenName ?? status.localHostName;
+ return (
+