From a18054f7f00deeb8e680f3dcac6cb2384592c76b Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 20 Nov 2026 19:03:11 +0530 Subject: [PATCH 1/6] feat(desktop): move Setup under Machines and tidy the This Machine card - Rename the settings group to Workspaces and drop Setup from the sidebar. Setup is reached from the Machines page, where its row is always present, and Set Up Later returns there. - Show the hostname in its own row with a copy button, since it is the name used when none is given, and shorten the row descriptions so a long hostname cannot wrap them. - Show the ID in the copy field once assigned, and as "Not Assigned" until then. - Hold the card's four rows while it loads and wait for the workspace before showing them, so the sections below no longer jump. - The copy field truncates a long value and shows it in full on hover. Co-Authored-By: Claude Fable 5.2 --- apps/web/src/components/copyable.tsx | 12 +++--- apps/web/src/settings/machines.tsx | 56 ++++++++++++++++++++-------- apps/web/src/settings/sections.ts | 31 +++++++++------ apps/web/src/setup.tsx | 2 +- 4 files changed, 67 insertions(+), 34 deletions(-) diff --git a/apps/web/src/components/copyable.tsx b/apps/web/src/components/copyable.tsx index 1138439e..3d7857b1 100644 --- a/apps/web/src/components/copyable.tsx +++ b/apps/web/src/components/copyable.tsx @@ -3,16 +3,18 @@ import { useState } from "react"; import { Button } from "@/components/ui/button"; -/** A shell command to run by hand, with a copy button that confirms. */ -export function CopyCommand({ command }: { command: string }) { +/** A shell command to run by hand, or a value to paste elsewhere, with a copy button that confirms. */ +export function CopyCommand({ command, label = "Copy command" }: { command: string; label?: string }) { const [copied, setCopied] = useState(false); return ( - - {command} + + + {command} + diff --git a/apps/web/src/settings/sections.ts b/apps/web/src/settings/sections.ts index 3cd09551..76b86298 100644 --- a/apps/web/src/settings/sections.ts +++ b/apps/web/src/settings/sections.ts @@ -14,7 +14,6 @@ import { SparkleIcon, StackIcon, UserIcon, - WrenchIcon, } from "@phosphor-icons/react"; /** Whether a path is a settings page: the app's own, or the account's and workspace's under a workspace. */ @@ -24,7 +23,6 @@ export const isSettingsPath = (pathname: string) => export interface SettingsSection { readonly to: | "/workspaces/$workspaceId/settings/account/profile" - | "/workspaces/$workspaceId/settings/machines/setup" | "/settings/general" | "/settings/tabs" | "/settings/themes" @@ -41,7 +39,7 @@ export interface SettingsSection { readonly label: string; readonly icon: Icon; /** Sidebar heading the section sits under. */ - readonly group: "Personal" | "Application" | "Administration"; + readonly group: "Personal" | "Application" | "Workspaces"; /** Extra words the search matches, beyond the label. */ readonly keywords: readonly string[]; } @@ -147,19 +145,28 @@ const sections: readonly SettingsSection[] = [ group: "Application", keywords: ["plugins", "extensions", "npm", "tools", "prompt", "bash", "grep", "find", "reload"], }, - { - to: "/workspaces/$workspaceId/settings/machines/setup", - label: "Setup", - icon: WrenchIcon, - group: "Administration", - keywords: ["set up", "install", "cli", "start", "server", "connect", "this machine", "onboarding"], - }, { to: "/workspaces/$workspaceId/settings/machines", label: "Machines", icon: DesktopTowerIcon, - group: "Administration", - keywords: ["machines", "connect", "online", "offline", "rename", "name", "relay", "harness", "computer"], + group: "Workspaces", + keywords: [ + "machines", + "connect", + "online", + "offline", + "rename", + "name", + "relay", + "harness", + "computer", + "setup", + "set up", + "install", + "cli", + "server", + "paired", + ], }, { to: "/settings/sandboxes", diff --git a/apps/web/src/setup.tsx b/apps/web/src/setup.tsx index 9b7c98ad..86757db1 100644 --- a/apps/web/src/setup.tsx +++ b/apps/web/src/setup.tsx @@ -200,7 +200,7 @@ export function Setup({ workspaceId }: { readonly workspaceId: string }) { variant="ghost" onClick={() => { setUpLater(workspaceId); - void navigate({ to: "/" }); + void navigate({ to: "/workspaces/$workspaceId/settings/machines", params: { workspaceId } }); }} > Set Up Later From 5af59f3328968d085071f784b580eec0fb7e6514 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 20 Nov 2026 23:23:40 +0530 Subject: [PATCH 2/6] fix(desktop): stop Escape from leaving Settings Escape on a settings page returned to the app, which also fired when a key press missed the dialog or field it was meant for. Settings is left with Back to App or the close button. Co-Authored-By: Claude Fable 5.2 --- apps/web/src/settings/tabs.tsx | 3 --- apps/web/src/shell/shell.tsx | 13 ++----------- apps/web/src/shell/titlebar.tsx | 2 +- 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/apps/web/src/settings/tabs.tsx b/apps/web/src/settings/tabs.tsx index 4c333c25..2560fa99 100644 --- a/apps/web/src/settings/tabs.tsx +++ b/apps/web/src/settings/tabs.tsx @@ -225,9 +225,6 @@ export function TabsSettings() { {isMac ? "⌘," : "Ctrl+,"} - - Esc - diff --git a/apps/web/src/shell/shell.tsx b/apps/web/src/shell/shell.tsx index d0ca62b7..07369972 100644 --- a/apps/web/src/shell/shell.tsx +++ b/apps/web/src/shell/shell.tsx @@ -6,7 +6,7 @@ import { useEffect } from "react"; import { isSettingsPath } from "../settings/sections"; import { Desktop } from "../wm/desktop"; import { deskQueryAtom } from "../wm/instances"; -import { lastTabAtom, useTabs, useTabReturn, tabRoute, tabsAtom } from "../wm/tabs"; +import { lastTabAtom, useTabs, tabRoute, tabsAtom } from "../wm/tabs"; import { settingsShortcut, tabShortcut } from "./switcher"; /** @@ -20,7 +20,6 @@ export function Shell() { const navigate = useNavigate(); // From the location, which changes before route params do: a match-based check lags a // render behind, in which the first tab would pass for the one settings returns to. - const inSettings = useLocation({ select: (location) => isSettingsPath(location.pathname) }); const overDesktop = useLocation({ select: (location) => isSettingsPath(location.pathname) || @@ -32,7 +31,6 @@ export function Shell() { const onTab = useLocation({ select: (location) => location.pathname.startsWith("/tabs/") }); // An id that no longer exists (a deleted tab) shows the first one. const shown = tabs.find((tab) => tab.id === tabId) ?? tabs[0]; - const back = useTabReturn(); // With every tab deleted there is nothing to show here; the start page needs none. Only once // the list has settled: a first load, or the refetch after creating one, must not bounce the user out. @@ -60,14 +58,11 @@ export function Shell() { } else if (settingsShortcut(event)) { event.preventDefault(); void navigate({ to: "/settings/tabs" }); - } else if (inSettings && event.key === "Escape" && !event.defaultPrevented && !isEditing(event.target)) { - // Dialogs and popovers claim Escape first by preventing its default. - void navigate(back); } }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [navigate, tabs, inSettings, back]); + }, [navigate, tabs]); return (
@@ -88,7 +83,3 @@ export function Shell() {
); } - -const isEditing = (target: EventTarget | null) => - target instanceof HTMLElement && - (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName)); diff --git a/apps/web/src/shell/titlebar.tsx b/apps/web/src/shell/titlebar.tsx index f7ea98bc..337207ba 100644 --- a/apps/web/src/shell/titlebar.tsx +++ b/apps/web/src/shell/titlebar.tsx @@ -80,7 +80,7 @@ function CloseSettings() { + } + > + {AsyncResult.isSuccess(paired) ? ( + paired.value.length === 0 ? ( + { + opener.current = event.currentTarget; + setPairing(true); + }} + > + Pair a Machine + + } + /> + ) : ( + + {paired.value.map((server) => ( + + ))} + + ) + ) : AsyncResult.isFailure(paired) ? ( +

+ The app server did not answer. +

+ ) : ( + + )} + {pairing && ( + { + close(); + setFresh(id); + }} + /> + )} + + ); +} + +function Item({ server, fresh }: { server: RemoteServerStatus; fresh: boolean }) { + const address = addressOf(server.url); + return ( + + + + {server.name} + + + {address} + + + {fresh ? Paired : } + + + ); +} diff --git a/apps/web/src/settings/paired/machine.tsx b/apps/web/src/settings/paired/machine.tsx new file mode 100644 index 00000000..47127c2d --- /dev/null +++ b/apps/web/src/settings/paired/machine.tsx @@ -0,0 +1,249 @@ +import { useAtomSet } from "@effect/atom-react"; +import type { RemoteServerStatus } from "@codeworksh/contract"; +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 { 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 { Group, Page, Placeholder, quietField, Row, SavingInput, Section } from "../blocks"; +import { EmptyState } from "../controls"; +import { Badge } from "../servers/local"; +import { Status, TITLE, usePaired } from "./list"; +import { addressOf, PairAgain, urlOf } from "./pair"; + +const labelAtom = Server.mutation("servers.label"); + +/** One paired machine, by its id. */ +export function PairedMachine({ id }: { id: string }) { + const paired = usePaired(); + if (!AsyncResult.isSuccess(paired)) { + 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 }: { 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 ( + + + {TITLE} + + ); +} + +/** + * 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 }: { title: string; description?: ReactNode; children?: ReactNode }) { + return ( +
+ + + {children} + +
+ ); +} + +function Detail({ server }: { server: RemoteServerStatus }) { + 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 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 ( + }> + {!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 + )} + +
+
+
+ + + + + +
+
+ ); +} + +/** Forgets the machine here, once confirmed, and goes back to the list. */ +function Remove({ server }: { 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/paired" })) + .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/paired/pair.tsx b/apps/web/src/settings/paired/pair.tsx new file mode 100644 index 00000000..6f380e59 --- /dev/null +++ b/apps/web/src/settings/paired/pair.tsx @@ -0,0 +1,284 @@ +import { useAtomSet } from "@effect/atom-react"; +import { PairingRefused, type RemoteServerStatus } from "@codeworksh/contract"; +import { WarningCircleIcon } from "@phosphor-icons/react"; +import { type ComponentProps, type FormEvent, useId, useRef, useState } from "react"; + +import { CopyCommand } from "@/components/copyable"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { messageOf } from "@/lib/utils"; +import { Server } from "../../kernel/rpc"; +import { updateAtom } from "../../kernel/servers"; +import { DialogRow, quietField } from "../blocks"; + +const addAtom = Server.mutation("servers.add"); + +const PAIR_COMMAND = "codework service pair"; + +const PORT = 7433; + +/** `host:port` as typed or as stored, without a scheme or path. */ +const hostPort = (text: string) => + text + .trim() + .replace(/^[a-z]+:\/\//i, "") + .replace(/\/.*$/, ""); + +/** Where a paired machine is, as `host:port`. */ +export const addressOf = (url: string) => hostPort(url); + +/** The URL for an address as typed, a bare host on the default port; empty for none. */ +export const urlOf = (typed: string) => { + const address = hostPort(typed); + if (address === "") return ""; + return `ws://${/:\d+$/.test(address) ? address : `${address}:${PORT}`}/rpc/v1`; +}; + +/** A pairing code as typed: any case, with or without its dash. */ +const plainCode = (typed: string) => + typed + .toUpperCase() + .replace(/[^0-9A-Z]/g, "") + .slice(0, 10); + +/** `XXXXX-XXXXX`, as far as it has been typed. */ +const formatCode = (typed: string) => { + const plain = plainCode(typed); + return plain.length > 5 ? `${plain.slice(0, 5)}-${plain.slice(5)}` : plain; +}; + +type Field = "address" | "code"; + +/** + * A pairing form's fields and failures. A failure sits under its own field, which takes focus with its + * text selected; changing that field clears it. + */ +function usePairForm() { + const id = useId(); + const address = useRef(null); + const code = useRef(null); + const [busy, setBusy] = useState(false); + const [failure, setFailure] = useState<{ readonly field: Field; readonly text: string } | null>(null); + const errorId = (field: Field) => `${id}-${field}-error`; + + const fail = (field: Field, text: string) => { + setFailure({ field, text }); + const input = (field === "address" ? address : code).current; + input?.focus(); + input?.select(); + }; + return { + busy, + address, + /** + * Validates first: `check` answers a failure to show, or null to go on and pair. A refused code + * fails under the code; anything else under `other`. + */ + submit: + ({ + check, + pair, + done, + other, + }: { + check: () => { field: Field; text: string } | null; + pair: () => Promise; + done: (value: A) => void; + other: Field; + }) => + (event: FormEvent) => { + event.preventDefault(); + if (busy) return; + const invalid = check(); + if (invalid !== null) return fail(invalid.field, invalid.text); + setBusy(true); + setFailure(null); + pair().then( + (value) => { + setBusy(false); + done(value); + }, + (cause: unknown) => { + setBusy(false); + fail(cause instanceof PairingRefused ? "code" : other, messageOf(cause)); + }, + ); + }, + /** The props a field needs for its failure, and to stay put while pairing. */ + field: (field: Field) => ({ + id: `${id}-${field}`, + ref: field === "address" ? address : code, + "aria-invalid": failure?.field === field ? true : undefined, + "aria-describedby": failure?.field === field ? errorId(field) : undefined, + autoComplete: "off", + spellCheck: false, + readOnly: busy, + }), + /** The field's failure, shown under it. */ + error: (field: Field) => + failure?.field === field && ( +

+ + {failure.text} +

+ ), + clear: (field: Field) => { + if (failure?.field === field) setFailure(null); + }, + }; +} + +const checkCode = (code: string) => + plainCode(code).length === 10 + ? null + : { field: "code" as const, text: "The pairing code is 10 letters and digits." }; + +/** A pairing code field, formatted as it is typed. */ +function CodeInput({ + value, + onChange, + className, + ...props +}: Omit, "value" | "onChange"> & { + value: string; + onChange: (code: string) => void; +}) { + return ( + onChange(formatCode(event.target.value))} + /> + ); +} + +/** Pairs a new machine; nothing is stored until its code is accepted. */ +export function PairDialog({ onClose, onPaired }: { onClose: () => void; onPaired: (id: string) => void }) { + const add = useAtomSet(addAtom, { mode: "promise" }); + const form = usePairForm(); + const [address, setAddress] = useState(""); + const [code, setCode] = useState(""); + const submit = form.submit({ + check: () => + urlOf(address) === "" ? { field: "address", text: "Enter the Machine's address." } : checkCode(code), + pair: () => add({ payload: { kind: "remote", url: urlOf(address), code } }), + done: onPaired, + other: "address", + }); + return ( + !next && !form.busy && onClose()}> + { + // The first field, not the copy button before it. + event.preventDefault(); + form.address.current?.focus(); + }} + > + + Pair a Machine + It stays outside your Workspaces. Only this computer reaches it. + +
+
+ + + + + { + setAddress(event.target.value); + form.clear("address"); + }} + /> + {form.error("address")} + + + { + setCode(next); + form.clear("code"); + }} + /> + {form.error("code")} + +
+ + + + +
+
+
+ ); +} + +/** Pairs a machine again, at its address, with a new code. */ +export function PairAgain({ server }: { server: RemoteServerStatus }) { + const update = useAtomSet(updateAtom, { mode: "promise" }); + const form = usePairForm(); + const [code, setCode] = useState(""); + const submit = form.submit({ + check: () => checkCode(code), + pair: () => update({ payload: { id: server.id, code } }), + done: () => setCode(""), + other: "code", + }); + return ( +
+ + Run this on {server.name}, then enter the Code it prints. Valid 10 minutes. + + +
+
+ + { + setCode(next); + form.clear("code"); + }} + /> + +
+ {form.error("code")} +
+
+ ); +} diff --git a/apps/web/src/settings/sections.ts b/apps/web/src/settings/sections.ts index 76b86298..f83f0f98 100644 --- a/apps/web/src/settings/sections.ts +++ b/apps/web/src/settings/sections.ts @@ -4,6 +4,7 @@ import { CpuIcon, CubeIcon, DesktopTowerIcon, + DevicesIcon, HardDrivesIcon, type Icon, KeyboardIcon, @@ -27,6 +28,7 @@ export interface SettingsSection { | "/settings/tabs" | "/settings/themes" | "/settings/servers" + | "/settings/paired" | "/settings/keybindings" | "/settings/models" | "/settings/chat" @@ -80,6 +82,13 @@ const sections: readonly SettingsSection[] = [ group: "Application", keywords: ["servers", "provider", "local", "remote", "cli", "service", "install", "codework", "version", "rpc"], }, + { + to: "/settings/paired", + label: "Paired Machines", + icon: DevicesIcon, + group: "Application", + keywords: ["pair", "paired", "remote", "machine", "code", "ssh", "address", "label"], + }, { to: "/settings/keybindings", label: "Keybindings", diff --git a/apps/web/src/settings/servers/add.tsx b/apps/web/src/settings/servers/add.tsx index b5c756b1..aedf328c 100644 --- a/apps/web/src/settings/servers/add.tsx +++ b/apps/web/src/settings/servers/add.tsx @@ -15,7 +15,7 @@ import { import { Input } from "@/components/ui/input"; import { messageOf } from "@/lib/utils"; import { Server } from "../../kernel/rpc"; -import { Code, quietField } from "../blocks"; +import { Code, DialogRow, quietField } from "../blocks"; import { Badge, Mark } from "./local"; const addAtom = Server.mutation("servers.add"); @@ -107,7 +107,7 @@ export function AddServer({ {step === 1 && (
- + setName(event.target.value)} onKeyDown={(event) => event.key === "Enter" && canContinue && setStep(2)} /> - +
)} {step === 2 && (
- + setExecutable(event.target.value)} /> - - + CODEWORK_HOME_DIR path @@ -148,8 +148,8 @@ export function AddServer({ className={`${quietField} font-mono text-xs md:text-xs`} onChange={(event) => setHome(event.target.value)} /> - - + @@ -164,7 +164,7 @@ export function AddServer({ className={`${quietField} font-mono text-xs md:text-xs`} onChange={(event) => setArgs(event.target.value)} /> - +
)} @@ -226,16 +226,3 @@ function KindTile({ ); } - -/** A setting in the dialog: its title and description beside its field. */ -function Row({ title, description, children }: { title: ReactNode; description: ReactNode; children: ReactNode }) { - return ( -
- - {title} - {description} - - {children} -
- ); -} diff --git a/apps/web/src/settings/servers/local.tsx b/apps/web/src/settings/servers/local.tsx index c4a01424..ab1d3bf8 100644 --- a/apps/web/src/settings/servers/local.tsx +++ b/apps/web/src/settings/servers/local.tsx @@ -19,13 +19,11 @@ import { Button } from "@/components/ui/button"; import { messageOf } from "@/lib/utils"; import brand from "../../assets/codework.png"; import { Server } from "../../kernel/rpc"; -import { INSTALL, installAtom, serviceAtom } from "../../kernel/servers"; +import { INSTALL, installAtom, removeAtom, serviceAtom, updateAtom } from "../../kernel/servers"; import { Code, Group as Card, quietField as field, SavingInput } from "../blocks"; import { Variables } from "./variables"; import { CopyCommand } from "@/components/copyable"; -const updateAtom = Server.mutation("servers.update"); -const removeAtom = Server.mutation("servers.remove"); const setDefaultAtom = Server.mutation("servers.setDefault"); type Tone = "success" | "warning" | "danger" | "info" | "muted"; diff --git a/apps/web/src/setup.tsx b/apps/web/src/setup.tsx index 86757db1..c3d0c1bd 100644 --- a/apps/web/src/setup.tsx +++ b/apps/web/src/setup.tsx @@ -182,7 +182,7 @@ export function Setup({ workspaceId }: { readonly workspaceId: string }) { index={2} current={current} title={`Connect to ${workspaceName}`} - summary={`Connected to ${workspaceName}`} + summary={`Linked to ${workspaceName}`} line={`${name} shows up in ${workspaceName} for everyone in it.`} problem={null} command={`codework connect --workspace ${workspaceId}${home}`} From 83284d790f9fbb75cd1fac1166c370bd8b95b5d0 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Fri, 20 Nov 2026 23:53:55 +0530 Subject: [PATCH 5/6] feat: end the pairing on the machine when it is removed in the app Removing a paired machine only forgot it in the app, so the machine kept listing the computer as a device until the session lapsed. - A paired device can end its own pairing with `device.leave`. It removes that device alone and closes its sockets, the one the call came in on included, so a client takes a reply or the connection ending as done. - The app calls it before removing the row, for at most three seconds, and removes the row whether the machine answers or not. - The empty Paired Machines list has one Pair a Machine button, in the header. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/handlers.ts | 11 +++ .../test/__artifacts__/paired.remove.json | 12 +++ apps/server/test/paired.test.ts | 33 ++++++++ apps/web/src/settings/paired/list.tsx | 24 +----- apps/widget/src/codework.ts | 10 +++ packages/codework/src/server/contract.ts | 9 +++ packages/codework/src/server/handlers.ts | 21 +++-- packages/codework/src/server/principal.ts | 2 +- .../test/__artifacts__/pair.leave.json | 13 ++++ packages/codework/test/pair.test.ts | 77 +++++++++++++++++-- 10 files changed, 174 insertions(+), 38 deletions(-) create mode 100644 apps/server/test/__artifacts__/paired.remove.json create mode 100644 packages/codework/test/__artifacts__/pair.leave.json diff --git a/apps/server/src/handlers.ts b/apps/server/src/handlers.ts index 92cc98b3..144f3227 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -251,6 +251,17 @@ export const layer = Contract.Api.toLayer( yield* health.check; }), "servers.remove": Effect.fn("servers.remove")(function* ({ id }: { readonly id: string }) { + const row = yield* servers.get(id); + // Best effort: the row goes whether the machine answers or not. + if (row.kind === "remote" && row.token !== null) + yield* sync.client(id).pipe( + Effect.flatMap((client) => + Codework.call((rpc) => rpc("device.leave", {}), { timeout: "3 seconds" }).pipe( + Effect.provideService(Client, client), + ), + ), + Effect.ignore, + ); yield* servers.remove(id); yield* health.check; }), diff --git a/apps/server/test/__artifacts__/paired.remove.json b/apps/server/test/__artifacts__/paired.remove.json new file mode 100644 index 00000000..0ed3ac75 --- /dev/null +++ b/apps/server/test/__artifacts__/paired.remove.json @@ -0,0 +1,12 @@ +{ + "a running machine": { + "devices before": 1, + "servers.remove": "removed", + "devices after": 0 + }, + "a stopped machine": { + "servers.remove": "removed", + "within the bound": true + }, + "rows left": 0 +} diff --git a/apps/server/test/paired.test.ts b/apps/server/test/paired.test.ts index 80d8afc9..c6455556 100644 --- a/apps/server/test/paired.test.ts +++ b/apps/server/test/paired.test.ts @@ -102,3 +102,36 @@ it("a paired machine shows its host, build and label, goes offline and back unas for (const secret of [desk.token, machine.token, session]) expect(text).not.toContain(secret); await snapshot("paired", JSON.parse(text)); }, 90_000); + +it("removing a paired machine ends its pairing there, and a stopped machine's row goes all the same", async () => { + const appHome = tempDir("leave-app"); + const kept = await codework(tempDir("leave-kept"), await freePort()); + const stopped = await codework(tempDir("leave-stopped"), await freePort()); + const desk = await app(appHome); + const keptId = await addMachine(appHome, kept, desk.run); + const stoppedId = await addMachine(appHome, stopped, desk.run); + const devices = () => kept.run((rpc) => rpc["device.list"]({})).then((list) => list.length); + const remove = async (id: string) => { + const started = Date.now(); + const reply = await desk.run((rpc) => + rpc["servers.remove"]({ id }).pipe( + Effect.match({ onFailure: ({ _tag, message }) => ({ _tag, message }), onSuccess: () => "removed" }), + ), + ); + return { reply, elapsed: Date.now() - started }; + }; + const rows = (id: string) => query(appHome, "SELECT id FROM machine WHERE id = ?", id).length; + + const before = await devices(); + const left = await remove(keptId); + const after = await devices(); + + await stop(stopped.proc); + const away = await remove(stoppedId); + + await snapshot("paired.remove", { + "a running machine": { "devices before": before, "servers.remove": left.reply, "devices after": after }, + "a stopped machine": { "servers.remove": away.reply, "within the bound": away.elapsed < 5_000 }, + "rows left": rows(keptId) + rows(stoppedId), + }); +}, 90_000); diff --git a/apps/web/src/settings/paired/list.tsx b/apps/web/src/settings/paired/list.tsx index 00cb24fa..a68f2103 100644 --- a/apps/web/src/settings/paired/list.tsx +++ b/apps/web/src/settings/paired/list.tsx @@ -32,8 +32,8 @@ export function Status({ server }: { server: RemoteServerStatus }) { export function PairedList() { const paired = usePaired(); const [pairing, setPairing] = useState(false); - // The button that opened the dialog: it unmounts with its dialog, so focus is handed back by hand. - const opener = useRef(null); + // The dialog unmounts rather than closing, so focus is handed back to its button by hand. + const opener = useRef(null); const close = () => { setPairing(false); requestAnimationFrame(() => opener.current?.focus()); @@ -50,13 +50,7 @@ export function PairedList() { title={TITLE} description="Machines this computer reaches with a pairing code, outside any Workspace." actions={ - @@ -67,18 +61,6 @@ export function PairedList() { { - opener.current = event.currentTarget; - setPairing(true); - }} - > - Pair a Machine - - } /> ) : ( diff --git a/apps/widget/src/codework.ts b/apps/widget/src/codework.ts index b868900f..44a29496 100644 --- a/apps/widget/src/codework.ts +++ b/apps/widget/src/codework.ts @@ -571,6 +571,11 @@ export class Unauthorized extends Schema.TaggedError()("Server.Una message: Schema.String, }) {} +/** A call this caller may not make; here only so its failure decodes. */ +class Forbidden extends Schema.TaggedError()("Server.Forbidden", { + message: Schema.String, +}) {} + /** The server's door on every call; here only so its failure decodes. */ export class Door extends RpcMiddleware.Service()("@codeworksh/widget/codework/Door", { error: Unauthorized, @@ -827,6 +832,11 @@ export const Api = RpcGroup.make( success: Machine.Disconnected, error: Machine.ConnectError, }), + /** Ends this app's own pairing with the machine; the connection dropping after the call means it left. */ + Rpc.make("device.leave", { + payload: {}, + error: Forbidden, + }), /** Connects this machine to a workspace: the code a member approves, then the link once they have. */ Rpc.make("machine.connect", { payload: { workspaceId: Schema.optional(Schema.String) }, diff --git a/packages/codework/src/server/contract.ts b/packages/codework/src/server/contract.ts index 5a0bbe62..23b7fb8a 100644 --- a/packages/codework/src/server/contract.ts +++ b/packages/codework/src/server/contract.ts @@ -978,6 +978,15 @@ export const Api = RpcGroup.make( success: Schema.Struct({ applied: Schema.Boolean }), error: Principal.Forbidden, }), + /** + * Ends the calling device's own pairing, as `device.revoke` would. Its sockets end with it, this one + * too, so the reply may never arrive: the connection dropping after the call is sent means it left. + * Devices only; a local caller has no pairing to leave. + */ + Rpc.make("device.leave", { + payload: {}, + error: Principal.Forbidden, + }), /** The OS home directory, and the folder `host.create` makes projects in. */ Rpc.make("host.info", { payload: {}, diff --git a/packages/codework/src/server/handlers.ts b/packages/codework/src/server/handlers.ts index 25d278dc..03e3b346 100644 --- a/packages/codework/src/server/handlers.ts +++ b/packages/codework/src/server/handlers.ts @@ -295,6 +295,11 @@ export const layer = Contract.Api.toLayer( const global = yield* Global.Service; const pairing = yield* Pairing.Service; const connections = yield* Door.Connections; + /** Forgets a device and ends its open connections; false when none has `id`. */ + const forget = (id: string) => + pairing + .revoke(id) + .pipe(Effect.tap(() => Effect.forEach(connections.device(id), connections.end, { discard: true }))); const mcpControl = (operation: "connect" | "disconnect") => Effect.fnUntraced(function* ({ server, ...ref }: Control.ThreadRef & { readonly server: string }) { return yield* mcp[operation](yield* resolve(ref), server); @@ -706,14 +711,14 @@ export const layer = Contract.Api.toLayer( ), "device.pair": () => Principal.local(pairing.code), "device.list": () => Principal.local(pairing.list), - "device.revoke": ({ id }) => - Principal.local( - Effect.gen(function* () { - const applied = yield* pairing.revoke(id); - yield* Effect.forEach(connections.device(id), connections.end, { discard: true }); - return { applied }; - }), - ), + "device.revoke": ({ id }) => Principal.local(Effect.map(forget(id), (applied) => ({ applied }))), + "device.leave": () => + Effect.gen(function* () { + const caller = yield* Principal.Current; + if (caller.kind !== "device") + return yield* new Principal.Forbidden({ message: "This computer has no pairing to leave" }); + yield* forget(caller.id); + }), "host.info": () => Effect.succeed(host.info), "host.browse": ({ path }) => host.browse(path), "host.create": ({ name }) => host.create(name), diff --git a/packages/codework/src/server/principal.ts b/packages/codework/src/server/principal.ts index a5fc0163..a75f27a8 100644 --- a/packages/codework/src/server/principal.ts +++ b/packages/codework/src/server/principal.ts @@ -17,7 +17,7 @@ export class Unauthorized extends Schema.TaggedError()("Server.Una message: Schema.String, }) {} -/** A call a device may not make: only this computer manages who is paired. */ +/** A call this caller may not make: only this computer manages who is paired, and only a device leaves. */ export class Forbidden extends Schema.TaggedError()("Server.Forbidden", { message: Schema.String, }) {} diff --git a/packages/codework/test/__artifacts__/pair.leave.json b/packages/codework/test/__artifacts__/pair.leave.json new file mode 100644 index 00000000..03c59710 --- /dev/null +++ b/packages/codework/test/__artifacts__/pair.leave.json @@ -0,0 +1,13 @@ +{ + "device.leave": "left", + "its other socket's stream": "failed: SocketCloseError", + "a call on the socket it left on": "ended", + "a ticket it took before": 401, + "a new ticket": 401, + "device.list": [ + "" + ], + "the other device's stream sees a session made after": "live", + "the other device calls": true, + "device.leave from this computer": "Server.Forbidden" +} diff --git a/packages/codework/test/pair.test.ts b/packages/codework/test/pair.test.ts index 700faf76..9693bf89 100644 --- a/packages/codework/test/pair.test.ts +++ b/packages/codework/test/pair.test.ts @@ -116,6 +116,17 @@ const follow = Effect.fn(function* (rpc: Client.Client) { const isClientError = Schema.is(RpcClientError.RpcClientError); +/** How a device's call or stream ended, as the artifact keeps it. */ +const ending = (exit: Exit.Exit) => + Exit.match(exit, { + onSuccess: () => "completed", + onFailure: (cause) => + Result.match(Cause.findError(cause), { + onSuccess: (error) => (isClientError(error) ? `failed: ${error.reason._tag}` : "failed otherwise"), + onFailure: () => "failed otherwise", + }), + }); + it("a paired device takes a ticket per socket, calls as a device, and is cut off when revoked", async () => { const local = home("local"); // A token file an earlier build kept, which a start deletes. @@ -226,14 +237,7 @@ it("a paired device takes a ticket per socket, calls as a device, and is cut off }).pipe(Effect.timeout("5 seconds")); const revocation = { revoke: scrubbed(revoked), - "the revoked device's stream": Exit.match(ended, { - onSuccess: () => "completed", - onFailure: (cause) => - Result.match(Cause.findError(cause), { - onSuccess: (error) => (isClientError(error) ? `failed: ${error.reason._tag}` : "failed otherwise"), - onFailure: () => "failed otherwise", - }), - }), + "the revoked device's stream": ending(ended), "the other device's stream sees a session made after": tabletFeed.fiber.pollUnsafe() === undefined ? "live" : "ended", "a ticket it took before": yield* upgrade(listening, queued), @@ -325,6 +329,63 @@ it("a paired device takes a ticket per socket, calls as a device, and is cut off await expect(text).toMatchFileSnapshot("./__artifacts__/pair.json"); }, 180_000); +it("a device leaves its own pairing; another device stays, and a local caller has none to leave", async () => { + const dir = home("leave"); + const result = await Effect.gen(function* () { + const real = yield* Clock.Clock; + return yield* Effect.gen(function* () { + const listening = yield* port; + const http = routes(`http://127.0.0.1:${listening}`); + const url = `ws://127.0.0.1:${listening}/rpc/v1`; + const filed = yield* registered(dir); + const rpc = yield* connect(dir); + const names = new Map(); + const pairDevice = Effect.fn(function* (name: string) { + const paired = yield* http.pair((yield* rpc["device.pair"]({})).code, name); + names.set(paired.id, `<${name}>`); + return paired; + }); + const desktop = yield* pairDevice("Desktop"); + const tablet = yield* pairDevice("Tablet"); + const desktopRpc = yield* device(url, yield* http.ticket(desktop.token)); + const desktopFeed = yield* follow(yield* device(url, yield* http.ticket(desktop.token))); + const tabletRpc = yield* device(url, yield* http.ticket(tablet.token)); + const tabletFeed = yield* follow(tabletRpc); + const queued = yield* http.ticket(desktop.token); + + // The reply races its own socket's end, so either outcome means it left. + const left = ending(yield* Effect.exit(desktopRpc["device.leave"]({}))); + // Refused or closed, by the same race. + const own = ending(yield* Effect.exit(desktopRpc["server.info"]({}))); + const ended = yield* Fiber.await(desktopFeed.fiber).pipe(Effect.timeout("5 seconds")); + const after = yield* rpc["session.create"]({}); + yield* Effect.gen(function* () { + while (!tabletFeed.live.some((item) => item._tag === "Session" && item.session.id === after.session.id)) + yield* Effect.sleep("50 millis"); + }).pipe(Effect.timeout("5 seconds")); + const devices = yield* rpc["device.list"]({}); + const artifact = { + "device.leave": left === "completed" || left === "failed: SocketCloseError" ? "left" : left, + "its other socket's stream": ending(ended), + "a call on the socket it left on": own === "completed" ? "answered" : "ended", + "a ticket it took before": yield* upgrade(listening, queued), + "a new ticket": yield* http.ticketStatus(`Bearer ${desktop.token}`), + "device.list": devices.map((each) => names.get(each.id) ?? ""), + "the other device's stream sees a session made after": + tabletFeed.fiber.pollUnsafe() === undefined ? "live" : "ended", + "the other device calls": (yield* tabletRpc["server.info"]({})).storeId.length > 0, + "device.leave from this computer": yield* rpc["device.leave"]({}).pipe( + Effect.match({ onFailure: (error) => error._tag, onSuccess: () => "left" }), + ), + }; + return { artifact, secrets: [filed.token, desktop.token, tablet.token, queued] }; + }).pipe(Effect.provide(serve(dir, real))); + }).pipe(Effect.scoped, Effect.timeout("60 seconds"), Effect.runPromise); + const text = `${JSON.stringify(result.artifact, null, "\t")}\n`; + for (const secret of result.secrets) expect(text).not.toContain(secret); + await expect(text).toMatchFileSnapshot("./__artifacts__/pair.leave.json"); +}, 60_000); + /** An IPv4 address of this computer other than loopback, as another computer on its network reaches it. */ const lan = Object.values(networkInterfaces()) .flat() From 7454a6f6793f940ccc48caf870dc53da7c9d7ce5 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Sat, 21 Nov 2026 02:37:15 +0530 Subject: [PATCH 6/6] feat(desktop): merge paired and workspace machines into one Machines page Settings has one Machines page under Application. Every machine appears once: This Machine, Paired Machines, Waiting to Join, and the workspace's machines this computer is not paired with. A paired machine's page links it to the selected workspace, or unlinks it. - The app server's machine.connect and machine.disconnect take an optional server id, so they reach a paired machine as well as the default one. - A paired machine's status carries its machine id and the workspaces it is linked to; both are stored and refreshed after a link or an unlink. - Setup moves under the new page. The Workspaces group and the Paired Machines entry leave the settings sidebar. - Settings sections gain a description line and more room between them. Descriptions no longer end with a full stop. - The settings pages that only showed mock data are removed, with the controls only they used. Co-Authored-By: Claude Fable 5.2 --- apps/contract/src/contract.ts | 16 +- apps/server/src/db.ts | 7 + apps/server/src/handlers.ts | 81 +- apps/server/src/health.ts | 2 +- apps/server/src/servers.ts | 90 ++- apps/server/src/sync.ts | 6 +- apps/server/test/__artifacts__/door.json | 16 +- apps/server/test/__artifacts__/paired.json | 24 +- .../test/__artifacts__/paired.link.json | 36 + apps/server/test/__artifacts__/schema.json | 18 +- apps/server/test/fixtures/apps.ts | 12 +- apps/server/test/paired.test.ts | 61 ++ apps/web/src/components/busy.tsx | 24 + apps/web/src/components/ui/select.tsx | 160 ---- apps/web/src/join.tsx | 5 +- apps/web/src/routeTree.gen.ts | 327 ++------ .../src/routes/_shell.settings.archive.tsx | 5 - apps/web/src/routes/_shell.settings.chat.tsx | 5 - .../src/routes/_shell.settings.general.tsx | 5 - .../routes/_shell.settings.keybindings.tsx | 5 - ...d.tsx => _shell.settings.machines.$id.tsx} | 4 +- .../routes/_shell.settings.machines.index.tsx | 5 + apps/web/src/routes/_shell.settings.mcp.tsx | 5 - .../web/src/routes/_shell.settings.models.tsx | 5 - .../routes/_shell.settings.paired.index.tsx | 5 - .../src/routes/_shell.settings.plugins.tsx | 5 - .../src/routes/_shell.settings.sandboxes.tsx | 5 - .../web/src/routes/_shell.settings.skills.tsx | 5 - ...kspaces.$workspaceId.settings.machines.tsx | 10 - .../src/routes/settings.machines.setup.tsx | 8 + ...s.$workspaceId.settings.machines.setup.tsx | 13 - apps/web/src/settings/archive.tsx | 179 ----- apps/web/src/settings/blocks.tsx | 28 +- apps/web/src/settings/chat.tsx | 109 --- apps/web/src/settings/controls.tsx | 98 +-- apps/web/src/settings/general.tsx | 205 ----- apps/web/src/settings/keybindings.tsx | 317 -------- apps/web/src/settings/machines.tsx | 619 --------------- .../settings/{paired => machines}/machine.tsx | 196 ++++- apps/web/src/settings/machines/page.tsx | 525 +++++++++++++ .../settings/{paired => machines}/pair.tsx | 10 +- apps/web/src/settings/machines/shared.tsx | 117 +++ apps/web/src/settings/machines/unlink.tsx | 136 ++++ apps/web/src/settings/machines/waiting.tsx | 204 +++++ apps/web/src/settings/mcp.tsx | 739 ------------------ apps/web/src/settings/models.tsx | 345 -------- apps/web/src/settings/paired/list.tsx | 112 --- apps/web/src/settings/plugins.tsx | 340 -------- apps/web/src/settings/profile.tsx | 4 +- apps/web/src/settings/sandboxes.tsx | 362 --------- apps/web/src/settings/sections.ts | 142 +--- apps/web/src/settings/servers/add.tsx | 6 +- apps/web/src/settings/servers/local.tsx | 8 +- apps/web/src/settings/servers/servers.tsx | 4 +- apps/web/src/settings/skills.tsx | 386 --------- apps/web/src/settings/tabs.tsx | 4 +- apps/web/src/settings/themes.tsx | 2 +- apps/web/src/setup.tsx | 66 +- apps/web/src/shell/connect.tsx | 33 +- apps/web/src/widgets/session/config.tsx | 32 +- 60 files changed, 1648 insertions(+), 4655 deletions(-) create mode 100644 apps/server/test/__artifacts__/paired.link.json create mode 100644 apps/web/src/components/busy.tsx delete mode 100644 apps/web/src/components/ui/select.tsx delete mode 100644 apps/web/src/routes/_shell.settings.archive.tsx delete mode 100644 apps/web/src/routes/_shell.settings.chat.tsx delete mode 100644 apps/web/src/routes/_shell.settings.general.tsx delete mode 100644 apps/web/src/routes/_shell.settings.keybindings.tsx rename apps/web/src/routes/{_shell.settings.paired.$id.tsx => _shell.settings.machines.$id.tsx} (50%) create mode 100644 apps/web/src/routes/_shell.settings.machines.index.tsx delete mode 100644 apps/web/src/routes/_shell.settings.mcp.tsx delete mode 100644 apps/web/src/routes/_shell.settings.models.tsx delete mode 100644 apps/web/src/routes/_shell.settings.paired.index.tsx delete mode 100644 apps/web/src/routes/_shell.settings.plugins.tsx delete mode 100644 apps/web/src/routes/_shell.settings.sandboxes.tsx delete mode 100644 apps/web/src/routes/_shell.settings.skills.tsx delete mode 100644 apps/web/src/routes/_shell.workspaces.$workspaceId.settings.machines.tsx create mode 100644 apps/web/src/routes/settings.machines.setup.tsx delete mode 100644 apps/web/src/routes/workspaces.$workspaceId.settings.machines.setup.tsx delete mode 100644 apps/web/src/settings/archive.tsx delete mode 100644 apps/web/src/settings/chat.tsx delete mode 100644 apps/web/src/settings/general.tsx delete mode 100644 apps/web/src/settings/keybindings.tsx delete mode 100644 apps/web/src/settings/machines.tsx rename apps/web/src/settings/{paired => machines}/machine.tsx (56%) create mode 100644 apps/web/src/settings/machines/page.tsx rename apps/web/src/settings/{paired => machines}/pair.tsx (96%) create mode 100644 apps/web/src/settings/machines/shared.tsx create mode 100644 apps/web/src/settings/machines/unlink.tsx create mode 100644 apps/web/src/settings/machines/waiting.tsx delete mode 100644 apps/web/src/settings/mcp.tsx delete mode 100644 apps/web/src/settings/models.tsx delete mode 100644 apps/web/src/settings/paired/list.tsx delete mode 100644 apps/web/src/settings/plugins.tsx delete mode 100644 apps/web/src/settings/sandboxes.tsx delete mode 100644 apps/web/src/settings/skills.tsx diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index c00ab492..f9d9156a 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -429,6 +429,10 @@ export const RemoteServerStatus = Schema.Struct({ seenAt: Schema.NullOr(Schema.Number), /** The build it last reported; none before it was ever reached. */ version: Schema.NullOr(Schema.String), + /** The machine's own id, as it last reported it; none before it was reached or before its first connect. */ + machineId: Schema.NullOr(Schema.String), + /** The workspaces it is linked to, each with the thumbprint of its key, as it last reported them. */ + workspaces: Schema.Array(Schema.Struct({ id: Schema.String, keyId: Schema.String })), }); export type RemoteServerStatus = typeof RemoteServerStatus.Type; @@ -857,17 +861,17 @@ export const Api = RpcGroup.make( success: Machine.Status, error: CodeworkUnavailable, }), - /** Disconnects the default machine from a workspace. */ + /** Disconnects the default machine, or the paired machine `serverId`, from a workspace. */ Rpc.make("machine.disconnect", { - payload: Machine.Disconnect, + payload: { ...Machine.Disconnect.fields, serverId: Schema.optionalKey(Schema.String) }, success: Machine.Disconnected, - error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]), + error: Schema.Union([CodeworkUnavailable, ServersError, Machine.ConnectError]), }), - /** Connects the default machine to a workspace: the code to approve, then the link. */ + /** Connects the default machine, or the paired machine `serverId`, to a workspace: the code to approve, then the link. */ Rpc.make("machine.connect", { - payload: { workspaceId: Schema.String }, + payload: { workspaceId: Schema.String, serverId: Schema.optionalKey(Schema.String) }, success: Machine.ConnectEvent, - error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]), + error: Schema.Union([CodeworkUnavailable, ServersError, Machine.ConnectError]), stream: true, }), /** The OS home directory, and the folder `host.create` makes projects in. */ diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index 279a8763..909c94b6 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -345,6 +345,13 @@ const migrations = { yield* sql`ALTER TABLE machine ADD COLUMN seen_at INTEGER`; yield* sql`UPDATE machine SET name = NULL WHERE kind = 'remote'`; }), + + // A remote machine's own id and the workspaces it is linked to (JSON), as it last reported them. + "202611210001_identity": Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE machine ADD COLUMN identity TEXT`; + yield* sql`ALTER TABLE machine ADD COLUMN workspaces TEXT`; + }), }; const setup = Effect.gen(function* () { diff --git a/apps/server/src/handlers.ts b/apps/server/src/handlers.ts index 144f3227..525d35a1 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -86,6 +86,28 @@ export const layer = Contract.Api.toLayer( ).pipe( Effect.flatMap((reply) => ("failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.value))), ); + /** + * The connection to a paired machine, in the app's own words when there is none: refused once it is + * not paired any more, or not answering. + */ + const paired = Effect.fn("paired")(function* (id: string) { + const row = yield* servers.get(id); + if (row.kind !== "remote") + return yield* new ServersError({ message: "Only a paired Machine is reached here." }); + if (row.token === null) + return yield* new ServersError({ message: `${row.name} is not paired any more. Pair it again.` }); + const unanswered = new ServersError({ message: `${row.name} did not answer.` }); + const client = yield* sync.client(id).pipe(Effect.mapError(() => unanswered)); + return { client, unanswered }; + }); + /** Stores what a paired machine's own record says now, so a link or an unlink shows at once. */ + const reread = (id: string, client: typeof Client.Service) => + Codework.call((rpc) => rpc("machine.info", {})).pipe( + Effect.provideService(Client, client), + Effect.flatMap((status) => servers.reached(id, Servers.factsOf(status))), + Effect.andThen(health.check), + Effect.ignore, + ); // A changed default reconnects the app; the status read after waits for it to reach the server. const changingDefault = (change: Effect.Effect) => Effect.gen(function* () { @@ -119,26 +141,52 @@ export const layer = Contract.Api.toLayer( return yield* call((client) => client("machine.rename", { givenName })); }), // The CLI's own failure (not connected to that workspace) keeps its message. - "machine.disconnect": Effect.fn("machine.disconnect")(function* (input) { - const reply = yield* call((client) => + "machine.disconnect": Effect.fn("machine.disconnect")(function* ({ serverId, ...input }) { + const disconnect = (client: typeof Client.Service) => client("machine.disconnect", input).pipe( Effect.map((disconnected) => ({ disconnected })), Effect.catchTag("Machine.ConnectError", (failed) => Effect.succeed({ failed })), - ), + ); + if (serverId === undefined) { + const reply = yield* call(disconnect); + return yield* "failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.disconnected); + } + const { client, unanswered } = yield* paired(serverId); + const reply = yield* Codework.call(disconnect).pipe( + Effect.provideService(Client, client), + Effect.mapError(() => unanswered), ); - return yield* "failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.disconnected); + if ("failed" in reply) return yield* reply.failed; + yield* servers.reached(serverId, Servers.factsOf(reply.disconnected.status)); + yield* health.check; + return reply.disconnected; }), // The CLI's own connect failure (the relay unreachable, the code expired) keeps its message; only - // a dropped server reads as unavailable. - "machine.connect": ({ workspaceId }) => - Codework.stream((client) => + // a dropped server reads as unavailable, and a paired machine as not answering. + "machine.connect": ({ workspaceId, serverId }) => { + const connect = (client: typeof Client.Service) => client("machine.connect", { workspaceId }).pipe( Stream.map((event) => ({ event })), Stream.catchTag("Machine.ConnectError", (failed) => Stream.succeed({ failed })), + ); + const unwrap = Stream.flatMap((item: Stream.Success>) => + "failed" in item ? Stream.fail(item.failed) : Stream.succeed(item.event), + ); + if (serverId === undefined) return Codework.stream(connect).pipe(unwrap); + return Stream.unwrap( + paired(serverId).pipe( + Effect.map(({ client, unanswered }) => + Codework.stream(connect).pipe( + Stream.provideService(Client, client), + Stream.mapError(() => unanswered), + unwrap, + // Stored before the link reaches the app, so the machine's status already shows it. + Stream.tap((event) => (event._tag === "Connected" ? reread(serverId, client) : Effect.void)), + ), + ), ), - ).pipe( - Stream.flatMap((item) => ("failed" in item ? Stream.fail(item.failed) : Stream.succeed(item.event))), - ), + ); + }, "host.info": Effect.fn("host.info")(function* () { return yield* call((client) => client("host.info", {})); }), @@ -237,15 +285,10 @@ export const layer = Contract.Api.toLayer( const row = yield* servers.get(id); if (row.kind !== "remote") return yield* new ServersError({ message: "Only a paired Machine has a Label." }); - if (row.token === null) - return yield* new ServersError({ message: `${row.name} is not paired any more. Pair it again.` }); - const status = yield* sync.client(id).pipe( - Effect.flatMap((client) => - Codework.call((rpc) => rpc("machine.rename", { givenName: label.trim() })).pipe( - Effect.provideService(Client, client), - ), - ), - Effect.mapError(() => new ServersError({ message: `${row.name} did not answer.` })), + const { client, unanswered } = yield* paired(id); + const status = yield* Codework.call((rpc) => rpc("machine.rename", { givenName: label.trim() })).pipe( + Effect.provideService(Client, client), + Effect.mapError(() => unanswered), ); yield* servers.reached(id, { label: status.givenName }); yield* health.check; diff --git a/apps/server/src/health.ts b/apps/server/src/health.ts index a1434762..8008e843 100644 --- a/apps/server/src/health.ts +++ b/apps/server/src/health.ts @@ -78,7 +78,7 @@ export const layer = Layer.effect( rows .map((row) => row.kind === "remote" - ? `${row.id}=${row.host} ${row.label} ${row.version} ${row.seenAt} ${row.online} ${row.token === null}` + ? `${row.id}=${row.host} ${row.label} ${row.version} ${row.seenAt} ${row.online} ${row.token === null} ${row.machineId} ${JSON.stringify(row.workspaces)}` : `${row.id}=${row.host}`, ) .join("\n"), diff --git a/apps/server/src/servers.ts b/apps/server/src/servers.ts index e239d1d7..9028c6be 100644 --- a/apps/server/src/servers.ts +++ b/apps/server/src/servers.ts @@ -1,4 +1,4 @@ -import { Clock, Config, Context, Effect, FileSystem, Layer, Schema, Stream, SubscriptionRef } from "effect"; +import { Clock, Config, Context, Effect, FileSystem, Layer, Option, Schema, Stream, SubscriptionRef } from "effect"; import { SqlClient } from "effect/sql"; /* @effect-diagnostics nodeBuiltinImport:off -- paths typed in Settings expand against the OS home directory. */ import os from "node:os"; @@ -7,10 +7,12 @@ import { type CliEnvVar, LOCAL_SERVER, PairingRefused, + RemoteServerStatus, type ServerAdd, ServersError, type ServerUpdate, } from "@codeworksh/contract"; +import type { Machine } from "@codeworksh/schema"; import { Pairing } from "./pairing.ts"; /** The same home the CLI resolves: CODEWORK_HOME_DIR, else ~/.codework. Only the built-in server falls back to it. */ @@ -77,6 +79,10 @@ export interface RemoteRow { readonly seenAt: number | null; /** Whether its sync connection is up now. */ readonly online: boolean; + /** The machine's own id, as it last reported it. */ + readonly machineId: string | null; + /** The workspaces it is linked to, as it last reported them. */ + readonly workspaces: RemoteServerStatus["workspaces"]; readonly url: string; /** The session token its pairing gave; none once the server refused it, or on a row from before pairing. */ readonly token: string | null; @@ -90,8 +96,21 @@ export interface Facts { readonly host?: string | null; readonly label?: string | null; readonly version?: string; + readonly machineId?: string | null; + readonly workspaces?: RemoteServerStatus["workspaces"]; } +/** What a remote machine's own record says about it: its label, its id and its links. */ +export const factsOf = (status: Machine.Status): Facts => ({ + label: status.givenName, + machineId: status.id, + workspaces: status.workspaces.map(({ id, keyId }) => ({ id, keyId })), +}); + +const Workspaces = Schema.fromJsonString(RemoteServerStatus.fields.workspaces); +const decodeWorkspaces = Schema.decodeUnknownOption(Workspaces); +const encodeWorkspaces = Schema.encodeSync(Workspaces); + const decodeEnv = Schema.decodeUnknownEffect(Schema.fromJsonString(StoredEnv)); const fail = (message: string) => new ServersError({ message }); @@ -216,40 +235,47 @@ export const layer = Layer.effect( label: string | null; version: string | null; seenAt: number | null; + identity: string | null; + workspaces: string | null; isDefault: number; } >` - SELECT id, kind, name AS override, host, label, version, seen_at, executable, home, args, env, url, token, - is_default + SELECT id, kind, name AS override, host, label, version, seen_at, identity, workspaces, executable, home, args, + env, url, token, is_default FROM machine ORDER BY pos `.pipe( Effect.flatMap((rows) => - Effect.forEach(rows, ({ kind, url, token, env, isDefault, label, version, seenAt, ...row }) => { - const name = nameOf({ kind, url, label, ...row }); - return kind === "remote" && url !== null - ? Effect.succeed({ - id: row.id, - kind, - name, - host: row.host, - label, - version, - seenAt, - online: online.has(row.id), - url, - token, - isDefault: isDefault === 1, - }) - : decodeEnv(env).pipe( - Effect.map((env): Row => ({ - ...row, + Effect.forEach( + rows, + ({ kind, url, token, env, isDefault, label, version, seenAt, identity, workspaces, ...row }) => { + const name = nameOf({ kind, url, label, ...row }); + return kind === "remote" && url !== null + ? Effect.succeed({ + id: row.id, + kind, name, - kind: "local", - env, + host: row.host, + label, + version, + seenAt, + online: online.has(row.id), + machineId: identity, + workspaces: Option.getOrElse(decodeWorkspaces(workspaces), () => []), + url, + token, isDefault: isDefault === 1, - })), - ); - }), + }) + : decodeEnv(env).pipe( + Effect.map((env): Row => ({ + ...row, + name, + kind: "local", + env, + isDefault: isDefault === 1, + })), + ); + }, + ), ), Effect.orDie, ); @@ -333,9 +359,15 @@ export const layer = Layer.effect( defaultHome, homeChanges: SubscriptionRef.changes(current).pipe(Stream.drop(1)), watch: SubscriptionRef.changes(machines), - reached: Effect.fn("Servers.reached")(function* (id, facts) { + reached: Effect.fn("Servers.reached")(function* (id, { machineId, workspaces, ...facts }) { const seenAt = yield* Clock.currentTimeMillis; - yield* sql`UPDATE machine SET ${sql.update({ ...facts, seenAt })} WHERE id = ${id}`.pipe(Effect.orDie); + const fields = { + ...facts, + ...(machineId === undefined ? {} : { identity: machineId }), + ...(workspaces === undefined ? {} : { workspaces: encodeWorkspaces(workspaces) }), + seenAt, + }; + yield* sql`UPDATE machine SET ${sql.update(fields)} WHERE id = ${id}`.pipe(Effect.orDie); online.add(id); yield* announce; }), diff --git a/apps/server/src/sync.ts b/apps/server/src/sync.ts index f57ed1fe..fe9360dd 100644 --- a/apps/server/src/sync.ts +++ b/apps/server/src/sync.ts @@ -345,10 +345,10 @@ export const layer = Layer.effect( Effect.gen(function* () { const machineId = row.id; const info = yield* client("server.info", {}); - // Only a remote machine is named by its label; one that fails to read it still syncs, keeping the stored one. + // Only a remote machine is named by its label; one that fails to read its record still syncs, keeping the stored one. const asked = row.kind === "remote" ? yield* Effect.exit(client("machine.info", {})) : undefined; - const label = asked !== undefined && Exit.isSuccess(asked) ? { label: asked.value.givenName } : {}; - yield* servers.reached(machineId, { host: info.host?.name ?? null, version: info.version, ...label }); + const own = asked !== undefined && Exit.isSuccess(asked) ? Servers.factsOf(asked.value) : {}; + yield* servers.reached(machineId, { host: info.host?.name ?? null, version: info.version, ...own }); const [machine] = yield* sql<{ storeId: string | null; cursor: number; diff --git a/apps/server/test/__artifacts__/door.json b/apps/server/test/__artifacts__/door.json index 5bc0fb8b..6924d351 100644 --- a/apps/server/test/__artifacts__/door.json +++ b/apps/server/test/__artifacts__/door.json @@ -30,7 +30,9 @@ "paired": true, "online": true, "seenAt": "
( /** * A CodeWork server of the fixture in `home` on `port`, with its scripted model; `older` lacks * `usage.sync` and a host name. `host` is the host name it reports (`null` for none), else `Fixture`. + * `relay` is where its connects go (`CODEWORK_RELAY_URL`). */ export const codework = async ( home: string, port: number, - options: { readonly older?: boolean; readonly host?: string | null } = {}, + options: { readonly older?: boolean; readonly host?: string | null; readonly relay?: string } = {}, ) => { const args = [fixture, home, String(port), ...(options.older === true ? ["127.0.0.1", "older"] : [])]; const proc = spawn(process.execPath, ["--conditions=development", ...args], { - env: options.host === undefined ? process.env : { ...process.env, CODEWORK_FIXTURE_HOST: options.host ?? "" }, + env: { + ...process.env, + ...(options.host === undefined ? {} : { CODEWORK_FIXTURE_HOST: options.host ?? "" }), + ...(options.relay === undefined ? {} : { CODEWORK_RELAY_URL: options.relay }), + }, stdio: ["pipe", "pipe", "inherit"], }); processes.add(proc); @@ -128,13 +133,14 @@ export const codework = async ( }; export type Codework = Awaited>; -/** A status as an artifact keeps it: a remote one's build and last answer vary per run. */ +/** A status as an artifact keeps it: a remote one's build, last answer and machine id vary per run. */ export const stable = (status: ServerStatus | undefined) => status?.kind === "remote" ? { ...status, version: status.version === null ? null : "", seenAt: status.seenAt === null ? null : "
-
+
+

{title}

{actions} @@ -33,19 +33,35 @@ export function Page({ export function Section({ title, + count, description, + action, children, }: { title: string; + /** How many items it lists, after the title; none when there are none. */ + count?: number | undefined; /** A line under the title, for what is true of the whole section. */ description?: string | undefined; + /** A control at the right of the title. */ + action?: ReactNode; children: ReactNode; }) { return ( -
-
-

{title}

- {description !== undefined &&

{description}

} +
+
+
+

+ + {title} + + {count !== undefined && count > 0 && ( + · {count} + )} +

+ {description !== undefined &&

{description}

} +
+ {action}
{children}
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 d060b000..9083bfc3 100644 --- a/apps/web/src/settings/controls.tsx +++ b/apps/web/src/settings/controls.tsx @@ -1,9 +1,7 @@ -import { CheckCircleIcon, MinusIcon, PlusIcon } from "@phosphor-icons/react"; +import { CheckCircleIcon } from "@phosphor-icons/react"; import type { ReactNode } from "react"; -import { Button } from "@/components/ui/button"; import { Ago } from "../widgets/time"; -import { quietField, SavingInput } from "./blocks"; export type StatusTone = "success" | "warning" | "danger" | "info" | "muted"; @@ -52,100 +50,6 @@ export function Done({ children }: { readonly children: ReactNode }) { ); } -/** 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; -}) { - return ( -
- {options.map((option) => { - const active = option.value === value; - return ( - - ); - })} -
- ); -} - -/** 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)); - return ( -
-
- - { - const parsed = Number(typed); - if (Number.isFinite(parsed)) onChange(clamp(Math.round(parsed))); - }} - /> - -
- {unit !== undefined && {unit}} -
- ); -} - /** A quiet empty-state card inside a settings section. */ export function EmptyState({ icon, 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 && ( - !next && setWhatsNewOpen(false)}> - - - What’s new in CodeWork v{VERSION} - Highlights from the latest release. - -
    - {RELEASE_HIGHLIGHTS.map((item) => ( -
  • - - {item} -
  • - ))} -
- - - -
-
- )} -
- ); -} 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/machines.tsx b/apps/web/src/settings/machines.tsx deleted file mode 100644 index f36992d7..00000000 --- a/apps/web/src/settings/machines.tsx +++ /dev/null @@ -1,619 +0,0 @@ -import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"; -import { CaretRightIcon, DesktopTowerIcon, DotsThreeIcon } 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 { type ReactNode, useEffect, useRef, useState } from "react"; - -import { Collapse } from "@/components/collapse"; -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 { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; -import { Input } from "@/components/ui/input"; -import { messageOf } from "@/lib/utils"; -import { - approveAtom, - declineAtom, - machinesAtom, - meAtom, - pairingsAtom, - reachAtom, - relayFailure, - removeMachineAtom, -} from "../kernel/relay"; -import { Server } from "../kernel/rpc"; -import { disconnectAtom, 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"; - -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; -/** How often pending connects are asked for: a person is usually waiting at the other machine. */ -const PENDING_MS = 5_000; - -/** The machines of the workspace in the URL, this machine, and machines waiting to join. */ -export function MachinesSettings({ workspaceId }: { readonly workspaceId: string }) { - const me = useAtomValue(meAtom); - const workspace = AsyncResult.isSuccess(me) - ? me.value.workspaces.find((option) => 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, - 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); - // 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 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 === null ? ( - Not Assigned - ) : ( -
- -
- )} -
- {workspace !== undefined && ( - - - - )} -
-
-
- ); -} - -/** 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 })}> -
{ - event.preventDefault(); - submit(); - }} - > -
- { - setCode(event.target.value); - setError(null); - }} - /> - {error !== null &&

{error}

} - {added !== null && error === null && Approved {added}} -
- -
-
-
- ); -} - -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 Unlink 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 Linked Here} - - } - description={`${machine.os} ${machine.arch} · v${machine.version} · ${machine.id}`} - > - {stale ? ( - Unknown - ) : ( - - )} - {!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( - "Unlinked here, but CodeWork's servers didn't confirm. Unlink 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 ? "Unlink…" : `Unlink from ${workspace.name}…`} - - - - !busy && setAsking(next)}> - - - Unlink {name}? - - {isLocal - ? `It leaves ${workspace.name} and stops showing up here. Link it again from Setup.` - : `It's unlinked 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 ? "Unlinking…" : "Unlink"} - - -
-
- - ); -} - -/** Content that replaces a placeholder fades in where it stood, instead of cutting over. */ -function Loaded({ children }: { readonly children: ReactNode }) { - return ( -
- {children} -
- ); -} diff --git a/apps/web/src/settings/paired/machine.tsx b/apps/web/src/settings/machines/machine.tsx similarity index 56% rename from apps/web/src/settings/paired/machine.tsx rename to apps/web/src/settings/machines/machine.tsx index 47127c2d..6f482a87 100644 --- a/apps/web/src/settings/paired/machine.tsx +++ b/apps/web/src/settings/machines/machine.tsx @@ -1,10 +1,12 @@ 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, @@ -20,21 +22,24 @@ 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 { Status, TITLE, usePaired } from "./list"; 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 }: { id: string }) { +export function PairedMachine({ id }: { readonly id: string }) { const paired = usePaired(); - if (!AsyncResult.isSuccess(paired)) { + 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. @@ -47,7 +52,7 @@ export function PairedMachine({ id }: { id: string }) { } const server = paired.value.find((each) => each.id === id); if (server === undefined) return ; - return ; + return ; } /** @@ -63,10 +68,10 @@ function Missing() { } title="Machine Not Found" - description="It is no longer paired with this computer, or does not exist." + description="It is no longer paired with this computer, or does not exist" action={ } /> @@ -76,7 +81,7 @@ function Missing() { } /** The way back to the list, in the panel's top-left corner, outside the content column. */ -function Back({ focus = false }: { focus?: boolean }) { +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(() => { @@ -85,11 +90,11 @@ function Back({ focus = false }: { focus?: boolean }) { return ( - {TITLE} + Machines ); } @@ -98,7 +103,15 @@ function Back({ focus = false }: { focus?: boolean }) { * 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 }: { title: string; description?: ReactNode; children?: ReactNode }) { +function Sub({ + title, + description, + children, +}: { + readonly title: string; + readonly description?: ReactNode; + readonly children?: ReactNode; +}) { return (

@@ -109,23 +122,38 @@ function Sub({ title, description, children }: { title: string; description?: Re ); } -function Detail({ server }: { server: RemoteServerStatus }) { +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 === "") 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 && ( -
+
@@ -133,7 +161,7 @@ function Detail({ server }: { server: RemoteServerStatus }) { )}
- + - + {server.host ? (
@@ -156,7 +184,7 @@ function Detail({ server }: { server: RemoteServerStatus }) { Unknown )} - + {server.version ? ( - v{server.version} + v{server.version} ) : ( Unknown )}
+ {workspace !== undefined && ( +
+ + + +
+ )}
@@ -188,8 +227,119 @@ function Detail({ server }: { server: RemoteServerStatus }) { ); } +/** 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 }: { server: RemoteServerStatus }) { +function Remove({ server }: { readonly server: RemoteServerStatus }) { const remove = useAtomSet(removeAtom, { mode: "promise" }); const navigate = useNavigate(); const [asking, setAsking] = useState(false); @@ -199,7 +349,7 @@ function Remove({ server }: { server: RemoteServerStatus }) { setBusy(true); setError(null); remove({ payload: { id: server.id } }) - .then(() => navigate({ to: "/settings/paired" })) + .then(() => navigate({ to: "/settings/machines" })) .catch((cause: unknown) => { setBusy(false); setError(messageOf(cause)); @@ -223,7 +373,7 @@ function Remove({ server }: { server: RemoteServerStatus }) { Remove {server.name}? - Its threads leave this computer's sidebar. Nothing on the Machine is deleted, and it can be paired + Its threads leave this computer’s sidebar. Nothing on the Machine is deleted, and it can be paired again. 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 ( +
+ + + + { + setError(null); + rename({ payload: { givenName } }) + .then(refresh) + .catch((cause: unknown) => setError(messageOf(cause))); + }} + /> + + +
+ +
+
+ + {status.id === null ? ( + Not Assigned + ) : ( +
+ +
+ )} +
+ {workspace !== undefined && ( + + {linkText(link !== undefined, workspace)} + + } + description={ + link === undefined + ? `This Machine isn’t Linked to ${workspace.name} yet` + : "The Workspace this Machine belongs to" + } + > + {/* Its control changes with the link; focus comes back to whichever is here. */} +
+ {link === undefined || machineId === null ? ( + + ) : ( + + )} +
+
+ )} +
+
+ setUnlinking(null)} + returnFocus={() => action.current?.querySelector("a, button")} + /> +
+ ); +} + +/** The machines this computer reaches with a pairing code, each opening its own page. */ +function Paired({ workspace, ready }: { readonly workspace: Relay.Workspace | undefined; readonly ready: boolean }) { + const paired = usePaired(); + const [pairing, setPairing] = useState(false); + const section = useRef(null); + // The dialog unmounts rather than closing, so focus is handed back by hand: to the button that opened + // it, or once the empty card's button is gone, to the section's own. + const opener = useRef(null); + const close = () => { + setPairing(false); + requestAnimationFrame(() => { + const target = opener.current?.isConnected + ? opener.current + : section.current?.querySelector("[data-pair]:not([aria-hidden])"); + target?.focus(); + }); + }; + const open = (event: { readonly currentTarget: HTMLElement }) => { + opener.current = event.currentTarget; + setPairing(true); + }; + // The machine paired a moment ago, marked where it landed. + const [fresh, setFresh] = useState(null); + useEffect(() => { + if (fresh === null) return; + const timer = setTimeout(() => setFresh(null), 2400); + return () => clearTimeout(timer); + }, [fresh]); + const list = AsyncResult.isSuccess(paired) && ready ? paired.value : undefined; + return ( +
+ +
+ ); +} + +function PairButton({ + primary = false, + hidden = false, + onClick, +}: { + readonly primary?: boolean; + /** Held invisible, so the header keeps its height while the empty card offers the button. */ + readonly hidden?: boolean; + readonly onClick: (event: { readonly currentTarget: HTMLElement }) => void; +}) { + return ( + + ); +} + +function PairedRow({ + server, + workspace, + fresh, +}: { + readonly server: RemoteServerStatus; + readonly workspace: Relay.Workspace | undefined; + readonly fresh: boolean; +}) { + const address = addressOf(server.url); + return ( + Paired : } + open={server.id} + className={`transition-colors duration-700 ease-out hover:duration-150 motion-reduce:transition-none ${fresh ? "bg-selection-subtle" : ""}`} + /> + ); +} + +/** + * The workspace's machines this computer is not paired with. This machine's own link is in its card; + * a link under its id but another key is one it lost, which only Unlink clears, so it stays here. + */ +function NotPaired({ + workspace, + pairedIds, +}: { + readonly workspace: Relay.Workspace; + /** The paired machines' ids; unknown until the app server answers, and the list waits for them. */ + readonly pairedIds: ReadonlySet | undefined; +}) { + 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]); + + const title = `Linked to ${workspace.name}, Not Paired`; + const about = `Machines in ${workspace.name} that this computer is not paired with`; + if (AsyncResult.isInitial(machines) || AsyncResult.isInitial(local) || pairedIds === undefined) { + 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 all = AsyncResult.isSuccess(machines) ? machines.value : (last?.value ?? []); + if (seen === null && AsyncResult.isSuccess(machines)) setSeen(new Set(all.map((machine) => machine.id))); + // The newest first: a machine just added appears where you are looking. + const list = all + .filter((machine) => !(machine.id === localId && machine.keyId === localKey) && !pairedIds.has(machine.id)) + .reverse(); + const command = `codework connect --workspace ${workspace.id}`; + return ( +
+ + {list.length === 0 ? ( + } + title="No Linked Machines" + description={`A Machine that joins ${workspace.name} with codework connect shows up here`} + action={ +
+ +
+ } + /> + ) : ( + + {list.map((machine) => ( + + ))} + + )} +
+
+ ); +} + +function NotPairedRow({ + machine, + workspace, + strayLocal, + fresh, + canRemove, + stale, + onGone, +}: { + readonly machine: Relay.Machine; + readonly workspace: Relay.Workspace; + /** This machine's id under a key it doesn't hold: a link it lost, which only Unlink clears. */ + readonly strayLocal: boolean; + readonly fresh: boolean; + readonly canRemove: boolean; + /** The last list the relay gave, while it can't be reached: online state is unknown and nothing acts. */ + readonly stale: boolean; + readonly onGone: () => void; +}) { + const [leaving, setLeaving] = useState(false); + const [tint, setTint] = useState(fresh); + const [unlinking, setUnlinking] = useState(null); + const trigger = useRef(null); + useEffect(() => { + if (!tint) return; + const timer = setTimeout(() => setTint(false), 1600); + return () => clearTimeout(timer); + }, [tint]); + const name = machine.givenName ?? machine.localHostName; + return ( +
+
+ This Machine · Not Linked Here} + description={`${machine.os} ${machine.arch} · v${machine.version} · ${machine.id}`} + status={ + stale ? ( + Unknown + ) : ( + + ) + } + menu={ + !stale && + (canRemove || strayLocal) && ( + + + + + + + setUnlinking({ + name, + workspace, + machineId: machine.id, + keyId: machine.keyId, + via: { kind: "relay" }, + }) + } + > + Unlink from {workspace.name}… + + + + ) + } + className={`transition-colors duration-700 ease-out motion-reduce:transition-none ${tint ? "bg-selection-subtle" : ""} ${fresh ? "animate-in duration-300 ease-(--ease-out) fade-in-0 slide-in-from-top-1 motion-reduce:animate-none" : ""}`} + /> +
+ setUnlinking(null)} + onDone={() => { + setLeaving(true); + setTimeout(onGone, 260); + }} + returnFocus={() => trigger.current} + /> +
+ ); +} diff --git a/apps/web/src/settings/paired/pair.tsx b/apps/web/src/settings/machines/pair.tsx similarity index 96% rename from apps/web/src/settings/paired/pair.tsx rename to apps/web/src/settings/machines/pair.tsx index 6f380e59..3707a927 100644 --- a/apps/web/src/settings/paired/pair.tsx +++ b/apps/web/src/settings/machines/pair.tsx @@ -171,7 +171,7 @@ export function PairDialog({ onClose, onPaired }: { onClose: () => void; onPaire const [code, setCode] = useState(""); const submit = form.submit({ check: () => - urlOf(address) === "" ? { field: "address", text: "Enter the Machine's address." } : checkCode(code), + urlOf(address) === "" ? { field: "address", text: "Enter the Machine’s address." } : checkCode(code), pair: () => add({ payload: { kind: "remote", url: urlOf(address), code } }), done: onPaired, other: "address", @@ -188,16 +188,16 @@ export function PairDialog({ onClose, onPaired }: { onClose: () => void; onPaire > Pair a Machine - It stays outside your Workspaces. Only this computer reaches it. + Only this computer reaches it.
- + void; onPaire server.kind === "remote"; + +/** This computer's paired machines, kept current. */ +export function usePaired() { + return AsyncResult.map(useAtomValue(serversAtom), (servers) => servers.filter(isPaired)); +} + +/** + * The workspace the app works in, and whether that is known yet. An app without sign-in has none, at + * once; signed in, it waits for the account. + */ +export function useWorkspace(): { readonly ready: boolean; readonly workspace: Relay.Workspace | undefined } { + const current = useAtomValue(workspaceAtom); + if (!isSignedInApp) return { ready: true, workspace: undefined }; + return { + ready: !AsyncResult.isInitial(current), + workspace: AsyncResult.isSuccess(current) ? current.value : undefined, + }; +} + +/** Whether a paired machine is linked to the workspace, as it last said. */ +export const isLinked = (server: RemoteServerStatus, workspace: Relay.Workspace) => + server.workspaces.some((link) => link.id === workspace.id); + +export const linkText = (linked: boolean, workspace: Relay.Workspace) => + linked ? `Linked to ${workspace.name}` : "Not Linked"; + +/** Whether it is paired, then whether it answers. */ +export function Status({ server }: { readonly server: RemoteServerStatus }) { + return server.paired ? ( + + ) : ( + Not Paired + ); +} + +/** + * One machine in a list. A paired one opens its page from anywhere on the row; any other has only its + * menu. Status and the chevron or menu sit in fixed columns, so the lists line up. + */ +export function MachineRow({ + name, + marks, + description, + status, + open, + menu, + className = "", +}: { + readonly name: string; + readonly marks?: ReactNode; + readonly description: string; + readonly status: ReactNode; + /** The paired machine whose page the row opens. */ + readonly open?: string | undefined; + readonly menu?: ReactNode; + readonly className?: string; +}) { + return ( +
+ + + {open === undefined ? ( + + {name} + + ) : ( + + {name} + + )} + {marks} + + + {description} + + + {status} + {open === undefined ? ( + {menu} + ) : ( + + + + )} +
+ ); +} + +/** Content that replaces a placeholder fades in where it stood, instead of cutting over. */ +export function Loaded({ children }: { readonly children: ReactNode }) { + return ( +
+ {children} +
+ ); +} diff --git a/apps/web/src/settings/machines/unlink.tsx b/apps/web/src/settings/machines/unlink.tsx new file mode 100644 index 00000000..7673d463 --- /dev/null +++ b/apps/web/src/settings/machines/unlink.tsx @@ -0,0 +1,136 @@ +import { useAtomRefresh, useAtomSet } from "@effect/atom-react"; +import type { Relay } from "@codeworksh/schema"; +import { useState } from "react"; + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { relayFailure, removeMachineAtom } from "../../kernel/relay"; +import { disconnectAtom, useMachineAtom } from "../../shell/connect"; + +/** A machine's link to a workspace, and who ends it. */ +export interface Target { + readonly name: string; + readonly workspace: Relay.Workspace; + readonly machineId: string; + readonly keyId: string; + /** + * This machine, or one paired with this computer, ends its own link; any other is removed from the + * relay by its owner or a workspace owner or admin. + */ + readonly via: + | { readonly kind: "local" } + | { readonly kind: "paired"; readonly serverId: string } + | { readonly kind: "relay" }; +} + +const descriptionOf = ({ workspace, via }: Target) => { + switch (via.kind) { + case "local": + return `It leaves ${workspace.name}. Link it again from Setup.`; + case "paired": + return `It leaves ${workspace.name}. This computer stays paired with it.`; + case "relay": + return `It leaves ${workspace.name}. It can join again with codework connect.`; + } +}; + +/** Ends a link once confirmed. It stays open with the failure until the link is gone. */ +export function UnlinkDialog({ + target, + onClose, + onDone, + returnFocus, +}: { + readonly target: Target | null; + readonly onClose: () => void; + readonly onDone?: () => void; + /** Where focus goes when it closes: the control that opened it, or what took its place. */ + readonly returnFocus: () => HTMLElement | null | undefined; +}) { + const disconnect = useAtomSet(disconnectAtom, { mode: "promise" }); + const remove = useAtomSet(removeMachineAtom, { mode: "promise" }); + const refreshLocal = useAtomRefresh(useMachineAtom()); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + // Kept while it closes, so its text doesn't blank out mid-exit. + const [shown, setShown] = useState(target); + if (target !== null && target !== shown) { + setShown(target); + setError(null); + } + const confirm = (target: Target) => { + const { workspace, machineId, keyId, via } = target; + const removeAsPerson = (afterDisconnect: boolean) => + remove({ workspaceId: workspace.id, machineId, keyId, afterDisconnect }); + const left = + via.kind === "relay" + ? removeAsPerson(false) + : disconnect({ + payload: { + workspaceId: workspace.id, + keyId, + ...(via.kind === "paired" ? { serverId: via.serverId } : {}), + }, + }) + // The relay didn't confirm the machine's own revoke: remove it as the signed-in person instead. + .then(({ revoked }) => + revoked + ? undefined + : removeAsPerson(true).catch(() => { + throw new Error( + "Unlinked on the Machine, but CodeWork’s servers didn’t confirm. Unlink it again when you’re back online.", + ); + }), + ) + .finally(() => { + if (via.kind === "local") refreshLocal(); + }); + setBusy(true); + setError(null); + left + .then(() => { + onClose(); + onDone?.(); + }) + .catch((cause: unknown) => setError(relayFailure(cause))) + .finally(() => setBusy(false)); + }; + return ( + !next && !busy && onClose()}> + { + event.preventDefault(); + requestAnimationFrame(() => returnFocus()?.focus()); + }} + > + + Unlink {shown?.name}? + {shown === null ? "" : descriptionOf(shown)} + + {error !== null &&

{error}

} + + Cancel + { + // Held open until the call returns, so a failure shows here. + event.preventDefault(); + if (target !== null) confirm(target); + }} + > + {busy ? "Unlinking…" : "Unlink"} + + +
+
+ ); +} diff --git a/apps/web/src/settings/machines/waiting.tsx b/apps/web/src/settings/machines/waiting.tsx new file mode 100644 index 00000000..85d154b2 --- /dev/null +++ b/apps/web/src/settings/machines/waiting.tsx @@ -0,0 +1,204 @@ +import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { CaretRightIcon } from "@phosphor-icons/react"; +import type { Relay } from "@codeworksh/schema"; +import { AsyncResult } from "effect/reactivity"; +import { useEffect, useRef, useState } from "react"; + +import { Collapse } from "@/components/collapse"; +import { CopyCommand } from "@/components/copyable"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { approveAtom, declineAtom, machinesAtom, pairingsAtom, relayFailure } from "../../kernel/relay"; +import { Group, Row, Section } from "../blocks"; +import { Done } from "../controls"; + +/** How often pending connects are asked for: a person is usually waiting at the other machine. */ +const PENDING_MS = 5_000; + +/** Machines that ran `codework connect --workspace` for this workspace, each with the code to check. */ +export 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 ( +
+ + {list.map((pairing) => { + const approved = pairing.status === "approved"; + const working = busy.has(pairing.userCode) || approved; + return ( +
+ + {pairing.machine.givenName ?? pairing.machine.localHostName} + + } + description={ + <> + {pairing.machine.os} {pairing.machine.arch} · {pairing.machine.id} · Code{" "} + {pairing.userCode} + {pairing.replaces && <> · Replaces the connected Machine} + + } + > +
+ + +
+
+
+ ); + })} +
+ + Run this on a Machine, then approve its Code here + + + {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 })}> + { + event.preventDefault(); + submit(); + }} + > +
+ { + setCode(event.target.value); + setError(null); + }} + /> + {error !== null &&

{error}

} + {added !== null && error === null && Approved {added}} +
+ + +
+
+ ); +} diff --git a/apps/web/src/settings/mcp.tsx b/apps/web/src/settings/mcp.tsx deleted file mode 100644 index 0367678a..00000000 --- a/apps/web/src/settings/mcp.tsx +++ /dev/null @@ -1,739 +0,0 @@ -import { - ArrowClockwiseIcon, - CaretRightIcon, - GlobeIcon, - HardDrivesIcon, - PlugsConnectedIcon, - PlusIcon, - TrashIcon, - WarningIcon, -} from "@phosphor-icons/react"; -import { useState } from "react"; - -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { Input } from "@/components/ui/input"; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; -import { Switch } from "@/components/ui/switch"; -import { Code, Group, Page, quietField, Row, Section } from "./blocks"; -import { EmptyState, Segmented, StatusDot, type StatusTone, Stepper } from "./controls"; -import { Badge } from "./servers/local"; - -type Exposure = "direct" | "deferred" | "codemode" | "hidden"; -type SharingScope = "session" | "space" | "app"; -type ConfigLayer = "user" | "project"; -type ServerState = "connected" | "authenticate" | "failed" | "disconnected" | "disabled"; - -interface McpToolItem { - readonly name: string; - readonly exposure: Exposure; -} - -interface McpServerEntry { - readonly id: string; - readonly name: string; - readonly description: string; - readonly transport: "stdio" | "http"; - readonly endpoint: string; - readonly layer: ConfigLayer; - readonly configPath: string; - readonly scope: SharingScope; - readonly exposure: Exposure; - readonly enabled: boolean; - readonly state: ServerState; - readonly oauthSignedIn?: boolean | undefined; - readonly error?: string | undefined; - readonly resources: boolean; - readonly tools: readonly McpToolItem[]; - readonly skipped?: readonly string[] | undefined; -} - -const INITIAL_SERVERS: readonly McpServerEntry[] = [ - { - id: "linear", - name: "linear", - description: "Search, create, and update Linear issues, cycles, and projects.", - transport: "http", - endpoint: "https://mcp.linear.app/mcp", - layer: "user", - configPath: "~/.codework/mcp.json", - scope: "app", - exposure: "deferred", - enabled: true, - state: "connected", - oauthSignedIn: true, - resources: true, - tools: [ - { name: "list_issues", exposure: "deferred" }, - { name: "get_issue", exposure: "deferred" }, - { name: "create_issue", exposure: "deferred" }, - { name: "update_issue", exposure: "deferred" }, - { name: "list_projects", exposure: "deferred" }, - { name: "list_teams", exposure: "deferred" }, - ], - }, - { - id: "filesystem", - name: "filesystem", - description: "Read and manage workspace files through the MCP reference server.", - transport: "stdio", - endpoint: "npx -y @modelcontextprotocol/server-filesystem .", - layer: "project", - configPath: ".codework/mcp.json", - scope: "session", - exposure: "direct", - enabled: true, - state: "connected", - resources: true, - tools: [ - { name: "read_text_file", exposure: "direct" }, - { name: "write_file", exposure: "direct" }, - { name: "list_directory", exposure: "direct" }, - { name: "search_files", exposure: "direct" }, - ], - }, - { - id: "sentry", - name: "sentry", - description: "Inspect production issues, stack traces, and release health from Sentry.", - transport: "http", - endpoint: "https://mcp.sentry.dev/mcp", - layer: "user", - configPath: "~/.codework/mcp.json", - scope: "space", - exposure: "deferred", - enabled: true, - state: "authenticate", - oauthSignedIn: false, - error: 'MCP server "sentry" requires sign-in. Authenticate via OAuth to load its tools.', - resources: false, - tools: [], - }, - { - id: "postgres", - name: "postgres", - description: "Inspect schema and run read-only SQL queries against local Postgres.", - transport: "stdio", - endpoint: "uvx mcp-server-postgres --dsn ${DATABASE_URL}", - layer: "project", - configPath: ".codework/mcp.json", - scope: "session", - exposure: "direct", - enabled: true, - state: "failed", - error: "Environment variable DATABASE_URL is not set or empty.", - resources: true, - tools: [{ name: "query", exposure: "direct" }], - skipped: ["raw_admin_dump"], - }, - { - id: "playwright", - name: "playwright", - description: "Drive a headless browser for UI inspection and end-to-end verification.", - transport: "stdio", - endpoint: "npx @playwright/mcp@latest", - layer: "user", - configPath: "~/.codework/mcp.json", - scope: "session", - exposure: "deferred", - enabled: false, - state: "disabled", - resources: false, - tools: [ - { name: "browser_navigate", exposure: "deferred" }, - { name: "browser_snapshot", exposure: "deferred" }, - { name: "browser_click", exposure: "deferred" }, - ], - }, -]; - -function stateMeta(server: McpServerEntry): { tone: StatusTone; badge: string; detail: string } { - if (!server.enabled || server.state === "disabled") { - return { tone: "muted", badge: "Disabled", detail: "Disabled in configuration" }; - } - switch (server.state) { - case "connected": - return { - tone: "success", - badge: "Connected", - detail: `${server.tools.length} ${server.tools.length === 1 ? "tool" : "tools"}${server.resources ? " · resources" : ""}`, - }; - case "authenticate": - return { tone: "warning", badge: "Needs sign-in", detail: "OAuth authentication required" }; - case "failed": - return { tone: "danger", badge: "Failed", detail: server.error ?? "Connection failed" }; - case "disconnected": - return { tone: "muted", badge: "Disconnected", detail: "Closed until reconnected" }; - } -} - -export function McpSettings() { - const [servers, setServers] = useState(INITIAL_SERVERS); - const [filter, setFilter] = useState<"all" | ConfigLayer>("all"); - const [expandedId, setExpandedId] = useState("linear"); - const [refreshing, setRefreshing] = useState(false); - const [busyId, setBusyId] = useState(null); - const [adding, setAdding] = useState(false); - - const [toolSearchEnabled, setToolSearchEnabled] = useState(true); - const [startupTimeoutSec, setStartupTimeoutSec] = useState(10); - const [idleTimeoutMin, setIdleTimeoutMin] = useState(10); - - const visible = servers.filter((server) => filter === "all" || server.layer === filter); - - const refreshAll = () => { - setRefreshing(true); - setTimeout(() => setRefreshing(false), 500); - }; - - const updateServer = (id: string, patch: Partial) => { - setServers((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item))); - }; - - const signInServer = (server: McpServerEntry) => { - setBusyId(server.id); - setTimeout(() => { - updateServer(server.id, { - state: "connected", - oauthSignedIn: true, - error: undefined, - tools: - server.tools.length > 0 - ? server.tools - : [ - { name: "list_issues", exposure: server.exposure }, - { name: "get_event_trace", exposure: server.exposure }, - { name: "search_releases", exposure: server.exposure }, - ], - }); - setBusyId(null); - }, 500); - }; - - const reconnectServer = (server: McpServerEntry) => { - setBusyId(server.id); - setTimeout(() => { - updateServer(server.id, { - state: "connected", - error: undefined, - }); - setBusyId(null); - }, 450); - }; - - return ( - - - -
- } - > -
- s.layer === "user").length})` }, - { value: "project", label: `Project (${servers.filter((s) => s.layer === "project").length})` }, - ]} - onChange={setFilter} - /> - - Tools reach the model as mcp__<server>__<tool> - -
- -
- {visible.length === 0 ? ( - } - title="No MCP servers in this scope" - description="Add a stdio or streamable HTTP MCP server to give its tools and resources to the model." - action={ - - } - /> - ) : ( - - {visible.map((server) => { - const meta = stateMeta(server); - const expanded = expandedId === server.id; - const busy = busyId === server.id; - return ( -
-
- - -
- {server.enabled && server.state === "authenticate" && ( - - )} - {server.enabled && (server.state === "failed" || server.state === "disconnected") && ( - - )} - - updateServer(server.id, { - enabled, - state: enabled ? "connected" : "disabled", - }) - } - /> -
-
- - {expanded && ( -
- {server.error !== undefined && ( -
- - {server.error} -
- )} - - {server.skipped !== undefined && server.skipped.length > 0 && ( -
- - - Skipped {server.skipped.length} invalid tool schema ( - {server.skipped.join(", ")}). See ~/.codework/mcp.log. - -
- )} - -
-
- - {server.transport === "http" ? "Endpoint URL" : "Command"} - - - {server.endpoint} - -
-
- Tool exposure - -
-
- Instance sharing scope - -
-
- - {server.tools.length > 0 && ( -
- - Tools ({server.tools.length}){server.resources && " + MCP resource tools"} - -
- {server.tools.map((tool) => ( - - {tool.name} - · {server.exposure} - - ))} -
-
- )} - -
- - Defined in {server.configPath} - -
- {server.enabled && server.state === "connected" && ( - - )} - {server.oauthSignedIn && ( - - )} - -
-
-
- )} -
- ); - })} -
- )} -
- -
- - - Deferred tool search - codework.tool.toolsearch - - } - description="Let the model search and load tools on demand from servers configured with deferred exposure." - > - - - - - - - - - -
- - {adding && ( - setAdding(false)} - onAdd={(entry) => { - setServers((current) => [...current, entry]); - setExpandedId(entry.id); - setAdding(false); - }} - /> - )} - - ); -} - -function AddMcpServerDialog({ - onClose, - onAdd, -}: { - readonly onClose: () => void; - readonly onAdd: (server: McpServerEntry) => void; -}) { - const [transport, setTransport] = useState<"stdio" | "http">("stdio"); - const [layer, setLayer] = useState("user"); - const [name, setName] = useState(""); - const [description, setDescription] = useState(""); - const [endpoint, setEndpoint] = useState(""); - const [exposure, setExposure] = useState("direct"); - const [scope, setScope] = useState("session"); - - const canSubmit = name.trim() !== "" && endpoint.trim() !== ""; - - const submit = () => { - if (!canSubmit) return; - const cleanName = name.trim().replace(/[^A-Za-z0-9_-]/g, "-"); - onAdd({ - id: `${cleanName}-${Date.now()}`, - name: cleanName, - description: description.trim() || `Custom ${transport.toUpperCase()} MCP server.`, - transport, - endpoint: endpoint.trim(), - layer, - configPath: layer === "user" ? "~/.codework/mcp.json" : ".codework/mcp.json", - scope, - exposure, - enabled: true, - state: "connected", - resources: false, - tools: [{ name: "example_tool", exposure }], - }); - }; - - return ( - !next && onClose()}> - - - Add MCP Server - - Write a new entry to {layer === "user" ? "~/.codework/mcp.json" : ".codework/mcp.json"}. - - - -
- - -
- -
- - - -
-
- Exposure - -
-
- Sharing scope - -
-
-
- - - - - -
-
- ); -} diff --git a/apps/web/src/settings/models.tsx b/apps/web/src/settings/models.tsx deleted file mode 100644 index 1d40f447..00000000 --- a/apps/web/src/settings/models.tsx +++ /dev/null @@ -1,345 +0,0 @@ -import { ArrowClockwiseIcon } from "@phosphor-icons/react"; -import { useState } from "react"; - -import { ProviderIcon } from "@/components/provider"; -import { Button } from "@/components/ui/button"; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; -import { Code, Group, Page, quietField, Row, Section } from "./blocks"; -import { Segmented, StatusDot, Stepper } from "./controls"; -import { Badge } from "./servers/local"; - -interface OAuthAccount { - readonly id: "openai-codex" | "github-copilot"; - readonly providerIcon: string; - readonly name: string; - readonly subtitle: string; - readonly connected: boolean; - readonly detail: string; -} - -interface EnvProvider { - readonly id: string; - readonly name: string; - readonly envVar: string; - readonly modelsCount: number; - readonly configured: boolean; -} - -const DEFAULT_MODELS = [ - { value: "openai/gpt-5.4", provider: "openai", label: "GPT-5.4 (OpenAI)" }, - { value: "openai-codex/gpt-5.3-codex", provider: "openai-codex", label: "GPT-5.3 Codex (Codex OAuth)" }, - { value: "anthropic/claude-sonnet-4-6", provider: "anthropic", label: "Claude Sonnet 4.6 (Anthropic)" }, - { value: "anthropic/claude-opus-4-6", provider: "anthropic", label: "Claude Opus 4.6 (Anthropic)" }, - { value: "google/gemini-2.5-pro", provider: "google", label: "Gemini 2.5 Pro (Google)" }, - { - value: "openrouter/deepseek/deepseek-v4.1-flash", - provider: "openrouter", - label: "DeepSeek V4.1 Flash (OpenRouter)", - }, -] as const; - -const THINKING_LEVELS = [ - { value: "off", label: "Off" }, - { value: "minimal", label: "Minimal" }, - { value: "low", label: "Low" }, - { value: "medium", label: "Medium" }, - { value: "high", label: "High" }, - { value: "xhigh", label: "Extra High" }, - { value: "max", label: "Max" }, -] as const; - -export function ModelsSettings() { - const [scope, setScope] = useState<"user" | "project">("user"); - const [oauth, setOauth] = useState([ - { - id: "openai-codex", - providerIcon: "openai-codex", - name: "OpenAI Codex", - subtitle: "ChatGPT Plus or Pro subscription via OAuth", - connected: true, - detail: "Connected · acct_94f2a8 · expires in 6d", - }, - { - id: "github-copilot", - providerIcon: "github-copilot", - name: "GitHub Copilot", - subtitle: "GitHub Copilot subscription token", - connected: false, - detail: "Not signed in", - }, - ]); - const [busyOauth, setBusyOauth] = useState(null); - - const [envProviders] = useState([ - { id: "anthropic", name: "Anthropic", envVar: "ANTHROPIC_API_KEY", modelsCount: 8, configured: true }, - { id: "openai", name: "OpenAI", envVar: "OPENAI_API_KEY", modelsCount: 11, configured: true }, - { id: "openrouter", name: "OpenRouter", envVar: "OPENROUTER_API_KEY", modelsCount: 42, configured: true }, - { id: "google", name: "Google Gemini", envVar: "GEMINI_API_KEY", modelsCount: 6, configured: false }, - { id: "xai", name: "xAI", envVar: "XAI_API_KEY", modelsCount: 4, configured: false }, - ]); - - const [defaultModel, setDefaultModel] = useState("anthropic/claude-sonnet-4-6"); - const [thinkingLevel, setThinkingLevel] = useState("medium"); - const [toolExecution, setToolExecution] = useState<"sequential" | "parallel">("sequential"); - const [cacheRetention, setCacheRetention] = useState<"none" | "short" | "long">("short"); - - const [maxRetries, setMaxRetries] = useState(3); - const [baseDelayMs, setBaseDelayMs] = useState(2000); - const [maxDelayMs, setMaxDelayMs] = useState(60000); - - const toggleOauth = (id: OAuthAccount["id"]) => { - setBusyOauth(id); - setTimeout(() => { - setOauth((current) => - current.map((item) => - item.id !== id - ? item - : item.connected - ? { ...item, connected: false, detail: "Not signed in" } - : { - ...item, - connected: true, - detail: - id === "openai-codex" - ? "Connected · acct_94f2a8 · expires in 7d" - : "Connected · 14 models available", - }, - ), - ); - setBusyOauth(null); - }, 450); - }; - - return ( - - } - > -
- - {oauth.map((account) => { - const busy = busyOauth === account.id; - return ( -
-
- - - -
-
- {account.name} - - {account.connected ? "Connected" : "Signed out"} - -
- {account.subtitle} - {account.detail} -
-
-
- {account.connected ? ( - <> - - - - ) : ( - - )} -
-
- ); - })} -
-
- -
- - {envProviders.map((provider) => ( -
-
- - - -
-
- {provider.name} - {`\${${provider.envVar}}`} -
- - {provider.configured - ? `${provider.modelsCount} catalog models enabled` - : "Set this variable in your provider server environment to enable."} - -
-
- - {provider.configured ? "Detected" : "Not set"} - -
- ))} -
-
- -
- - - - - - - - - - - - - - -
- -
- - - - - - - - - - - -
-
- ); -} diff --git a/apps/web/src/settings/paired/list.tsx b/apps/web/src/settings/paired/list.tsx deleted file mode 100644 index a68f2103..00000000 --- a/apps/web/src/settings/paired/list.tsx +++ /dev/null @@ -1,112 +0,0 @@ -import { useAtomValue } from "@effect/atom-react"; -import type { RemoteServerStatus, ServerStatus } from "@codeworksh/contract"; -import { CaretRightIcon, PlusIcon } from "@phosphor-icons/react"; -import { Link } from "@tanstack/react-router"; -import { AsyncResult } from "effect/reactivity"; -import { useEffect, useRef, useState } from "react"; - -import { Button } from "@/components/ui/button"; -import { serversAtom } from "../../kernel/servers"; -import { Group, Page, Placeholder } from "../blocks"; -import { Done, EmptyState, SeenStatus, StatusDot } from "../controls"; -import { addressOf, PairDialog } from "./pair"; - -export const TITLE = "Paired Machines"; - -const isPaired = (server: ServerStatus): server is RemoteServerStatus => server.kind === "remote"; - -/** This computer's paired machines, kept current. */ -export function usePaired() { - return AsyncResult.map(useAtomValue(serversAtom), (servers) => servers.filter(isPaired)); -} - -/** Whether it is paired, then whether it answers. */ -export function Status({ server }: { server: RemoteServerStatus }) { - return server.paired ? ( - - ) : ( - Not Paired - ); -} - -export function PairedList() { - const paired = usePaired(); - const [pairing, setPairing] = useState(false); - // The dialog unmounts rather than closing, so focus is handed back to its button by hand. - const opener = useRef(null); - const close = () => { - setPairing(false); - requestAnimationFrame(() => opener.current?.focus()); - }; - // The machine paired a moment ago, marked where it landed. - const [fresh, setFresh] = useState(null); - useEffect(() => { - if (fresh === null) return; - const timer = setTimeout(() => setFresh(null), 2400); - return () => clearTimeout(timer); - }, [fresh]); - return ( - setPairing(true)}> - - Pair a Machine - - } - > - {AsyncResult.isSuccess(paired) ? ( - paired.value.length === 0 ? ( - - ) : ( - - {paired.value.map((server) => ( - - ))} - - ) - ) : AsyncResult.isFailure(paired) ? ( -

- The app server did not answer. -

- ) : ( - - )} - {pairing && ( - { - close(); - setFresh(id); - }} - /> - )} -
- ); -} - -function Item({ server, fresh }: { server: RemoteServerStatus; fresh: boolean }) { - const address = addressOf(server.url); - return ( - - - - {server.name} - - - {address} - - - {fresh ? Paired : } - - - ); -} diff --git a/apps/web/src/settings/plugins.tsx b/apps/web/src/settings/plugins.tsx deleted file mode 100644 index 55d26e5c..00000000 --- a/apps/web/src/settings/plugins.tsx +++ /dev/null @@ -1,340 +0,0 @@ -import { ArrowClockwiseIcon, PlusIcon, PuzzlePieceIcon, TrashIcon } from "@phosphor-icons/react"; -import { useState } from "react"; - -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { Input } from "@/components/ui/input"; -import { Switch } from "@/components/ui/switch"; -import { Code, Group, Page, quietField, Section } from "./blocks"; -import { EmptyState, Segmented, StatusDot } from "./controls"; -import { Badge } from "./servers/local"; - -interface BuiltinPlugin { - readonly id: string; - readonly domain: "tool" | "prompt"; - readonly description: string; - readonly optIn?: boolean; - readonly enabled: boolean; -} - -interface ExternalPlugin { - readonly id: string; - readonly spec: string; - readonly kind: "npm" | "local"; - readonly layer: "user" | "project"; - readonly domain: "tool" | "prompt" | "mcp" | "sandbox"; - readonly description: string; - readonly enabled: boolean; -} - -const INITIAL_BUILTINS: readonly BuiltinPlugin[] = [ - { - id: "codework.tool.bash", - domain: "tool", - description: "Execute shell commands in the session's active sandbox.", - enabled: true, - }, - { - id: "codework.tool.read", - domain: "tool", - description: "Read file contents and inspect images with line offset and limit.", - enabled: true, - }, - { - id: "codework.tool.write", - domain: "tool", - description: "Create new files or overwrite existing files in the workspace.", - enabled: true, - }, - { - id: "codework.tool.edit", - domain: "tool", - description: "Perform targeted, non-overlapping text replacements in files.", - enabled: true, - }, - { - id: "codework.tool.grep", - domain: "tool", - description: "Search file contents with regular expressions and glob filters.", - optIn: true, - enabled: true, - }, - { - id: "codework.tool.find", - domain: "tool", - description: "Find files by name and glob pattern across the workspace.", - optIn: true, - enabled: true, - }, - { - id: "codework.tool.toolsearch", - domain: "tool", - description: "Discover and activate deferred tools from MCP servers and plugins.", - enabled: true, - }, - { - id: "codework.prompt.default", - domain: "prompt", - description: "Render the default system prompt foundation and workspace environment sections.", - enabled: true, - }, -]; - -const INITIAL_EXTERNAL: readonly ExternalPlugin[] = [ - { - id: "proc", - spec: "@codeworksh/codework-tool-proc@0.3.1", - kind: "npm", - layer: "user", - domain: "tool", - description: "Manage long-running background processes and inspect their output streams.", - enabled: true, - }, - { - id: "prompt-life", - spec: "@codeworksh/codework-prompt-life@0.2.0", - kind: "npm", - layer: "user", - domain: "prompt", - description: "Inject persistent project notes and session continuity context into the prompt.", - enabled: true, - }, - { - id: "house-style", - spec: "./extras/plugins/house-style.ts", - kind: "local", - layer: "project", - domain: "prompt", - description: "Project-specific TypeScript, Effect, and testing conventions for this repository.", - enabled: true, - }, -]; - -export function PluginsSettings() { - const [builtins, setBuiltins] = useState(INITIAL_BUILTINS); - const [external, setExternal] = useState(INITIAL_EXTERNAL); - const [reloading, setReloading] = useState(false); - const [reloadNote, setReloadNote] = useState(null); - const [adding, setAdding] = useState(false); - - const reloadAll = () => { - setReloading(true); - setTimeout(() => { - setReloading(false); - setReloadNote( - `Reloaded ${builtins.filter((b) => b.enabled).length + external.filter((e) => e.enabled).length} active plugins.`, - ); - }, 450); - }; - - return ( - - - -
- } - > - {reloadNote !== null && ( -
- {reloadNote} - -
- )} - -
- {external.length === 0 ? ( - } - title="No external plugins configured" - description="Add an npm package or a local TypeScript/JavaScript module to settings.jsonc." - /> - ) : ( - - {external.map((plugin) => ( -
-
- - - -
-
- {plugin.spec} - {plugin.kind} - {plugin.domain} - {plugin.layer} -
-

{plugin.description}

-
-
-
- - - setExternal((current) => - current.map((item) => (item.id === plugin.id ? { ...item, enabled } : item)), - ) - } - /> -
-
- ))} -
- )} -
- -
- - {builtins.map((plugin) => ( -
-
-
- {plugin.id} - {plugin.domain} - {plugin.optIn && Opt-in} -
- {plugin.description} -
- - setBuiltins((current) => - current.map((item) => (item.id === plugin.id ? { ...item, enabled } : item)), - ) - } - /> -
- ))} -
-
- - {adding && ( - setAdding(false)} - onAdd={(entry) => { - setExternal((current) => [...current, entry]); - setAdding(false); - }} - /> - )} - - ); -} - -function AddPluginDialog({ - onClose, - onAdd, -}: { - readonly onClose: () => void; - readonly onAdd: (plugin: ExternalPlugin) => void; -}) { - const [layer, setLayer] = useState<"user" | "project">("user"); - const [spec, setSpec] = useState(""); - const [description, setDescription] = useState(""); - - const trimmed = spec.trim(); - const isLocal = - trimmed.startsWith(".") || trimmed.startsWith("/") || trimmed.startsWith("~/") || trimmed.startsWith("file:"); - - const submit = () => { - if (!trimmed) return; - onAdd({ - id: `plugin-${Date.now()}`, - spec: trimmed, - kind: isLocal ? "local" : "npm", - layer, - domain: "tool", - description: - description.trim() || (isLocal ? "Local workspace plugin module." : "Installed npm plugin package."), - enabled: true, - }); - }; - - return ( - !next && onClose()}> - - - Add Plugin - - Register an npm package or local module in{" "} - {layer === "user" ? "~/.codework/settings.jsonc" : ".codework/settings.jsonc"}. - - - -
- Settings layer - -
- -
- - -
- - - - - -
-
- ); -} diff --git a/apps/web/src/settings/profile.tsx b/apps/web/src/settings/profile.tsx index 90fd0de6..e3ded438 100644 --- a/apps/web/src/settings/profile.tsx +++ b/apps/web/src/settings/profile.tsx @@ -13,7 +13,7 @@ export function ProfileSettings() { {isSignedInApp ? ( ) : ( - + )} ); @@ -27,7 +27,7 @@ function Account() { } | null>(null); if (!isLoaded) return null; if (user === null || user === undefined) - return ; + return ; const failed = (field: "picture" | "first" | "last") => (cause: unknown) => setError({ field, message: messageOf(cause) }); const errorOf = (field: "picture" | "first" | "last") => (error?.field === field ? error.message : undefined); diff --git a/apps/web/src/settings/sandboxes.tsx b/apps/web/src/settings/sandboxes.tsx deleted file mode 100644 index 4904bb02..00000000 --- a/apps/web/src/settings/sandboxes.tsx +++ /dev/null @@ -1,362 +0,0 @@ -import { CubeIcon, GitBranchIcon, PlusIcon, StopIcon, TrashIcon, TreeStructureIcon } from "@phosphor-icons/react"; -import { useState } from "react"; - -import { Button } from "@/components/ui/button"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { Input } from "@/components/ui/input"; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; -import { Code, Group, Page, quietField, Row, Section } from "./blocks"; -import { EmptyState, StatusDot } from "./controls"; -import { Badge } from "./servers/local"; - -interface SandboxInstanceItem { - readonly id: string; - readonly driver: "memory" | "vercel" | "daytona"; - readonly kind: "local" | "remote"; - readonly resourceId?: string; - readonly refCount: number; - readonly status: "running" | "stopping"; - readonly createdAgo: string; -} - -interface WorktreeItem { - readonly id: string; - readonly name: string; - readonly path: string; - readonly branch: string; - readonly sessions: number; - readonly dirty: boolean; - readonly unpushed: number; -} - -const DRIVERS = [ - { - id: "host", - name: "Local Host", - kind: "local", - ready: true, - detail: "Runs directly in the project's host folder.", - }, - { - id: "memory", - name: "Memory", - kind: "local", - ready: true, - detail: "Isolated copy-on-write virtual filesystem in RAM.", - }, - { id: "vercel", name: "Vercel Sandbox", kind: "remote", ready: true, detail: "Cloud microVM via @vercel/sandbox." }, - { - id: "daytona", - name: "Daytona", - kind: "remote", - ready: false, - detail: "Set DAYTONA_API_KEY to provision cloud workspaces.", - }, -] as const; - -const INITIAL_INSTANCES: readonly SandboxInstanceItem[] = [ - { - id: "sbx_01jp9k2m7v", - driver: "vercel", - kind: "remote", - resourceId: "vcel_vm_8821a", - refCount: 2, - status: "running", - createdAgo: "18m ago", - }, - { - id: "sbx_01jp8w4a1c", - driver: "memory", - kind: "local", - refCount: 1, - status: "running", - createdAgo: "42m ago", - }, -]; - -const INITIAL_WORKTREES: readonly WorktreeItem[] = [ - { - id: "wt-mcp-settings", - name: "codework-mcp-settings", - path: "~/personal/open-source/worktrees/codework-mcp-settings", - branch: "feat/mcp-settings", - sessions: 2, - dirty: true, - unpushed: 1, - }, - { - id: "wt-rpc-sync", - name: "codework-rpc-sync", - path: "~/personal/open-source/worktrees/codework-rpc-sync", - branch: "fix/rpc-reconnect", - sessions: 0, - dirty: false, - unpushed: 0, - }, -]; - -let nextSandboxSeq = 1; - -export function SandboxesSettings() { - const [defaultDriver, setDefaultDriver] = useState("host"); - const [instances, setInstances] = useState(INITIAL_INSTANCES); - const [worktrees, setWorktrees] = useState(INITIAL_WORKTREES); - const [creatingWorktree, setCreatingWorktree] = useState(false); - - const provisionSandbox = (driver: "memory" | "vercel") => { - const seq = nextSandboxSeq++; - const id = `sbx_01jp9x${String(seq).padStart(4, "0")}`; - setInstances((current) => [ - { - id, - driver, - kind: driver === "vercel" ? "remote" : "local", - ...(driver === "vercel" ? { resourceId: `vcel_vm_9${String(seq).padStart(4, "0")}` } : {}), - refCount: 0, - status: "running", - createdAgo: "just now", - }, - ...current, - ]); - }; - - return ( - -
- - - - - -
- -
- - {DRIVERS.map((driver) => ( -
-
- - - -
-
- {driver.name} - {driver.id} - - {driver.ready ? "Available" : "Not configured"} - - {driver.kind} -
- {driver.detail} -
-
- {(driver.id === "memory" || driver.id === "vercel") && ( - - )} -
- ))} -
-
- -
- {instances.length === 0 ? ( - } - title="No active sandboxes" - description="Managed sandboxes start automatically when a session requests one and stop when you end them." - /> - ) : ( - - {instances.map((instance) => ( -
-
-
- {instance.id} - {instance.driver} - {instance.resourceId !== undefined && {instance.resourceId}} -
- - Running · {instance.refCount}{" "} - {instance.refCount === 1 ? "session attached" : "sessions attached"} · created{" "} - {instance.createdAgo} - -
- -
- ))} -
- )} -
- -
-
- - Linked worktrees let sessions work on separate branches concurrently without stashing. - - -
- {worktrees.length === 0 ? ( - } - title="No additional worktrees" - description="Create a worktree to run sessions on another branch in an isolated folder." - /> - ) : ( - - {worktrees.map((tree) => ( -
-
- - - -
-
- {tree.name} - - - {tree.branch} - - - {tree.dirty ? "Uncommitted changes" : "Clean"} - -
- {tree.path} - - {tree.sessions} {tree.sessions === 1 ? "session" : "sessions"} in this worktree - {tree.unpushed > 0 ? ` · ${tree.unpushed} unpushed commit` : ""} - -
-
- -
- ))} -
- )} -
- - {creatingWorktree && ( - setCreatingWorktree(false)} - onCreate={(tree) => { - setWorktrees((current) => [tree, ...current]); - setCreatingWorktree(false); - }} - /> - )} -
- ); -} - -function CreateWorktreeDialog({ - onClose, - onCreate, -}: { - readonly onClose: () => void; - readonly onCreate: (tree: WorktreeItem) => void; -}) { - const [branch, setBranch] = useState(""); - const cleanBranch = branch.trim(); - const folderName = `codework-${cleanBranch.replace(/[^a-zA-Z0-9-_]+/g, "-") || "branch"}`; - - return ( - !next && onClose()}> - - - Create Worktree - - Check out a new or existing branch into a linked folder under{" "} - ~/personal/open-source/worktrees. - - - -

- Folder: {`~/personal/open-source/worktrees/${folderName}`} -

- - - - -
-
- ); -} diff --git a/apps/web/src/settings/sections.ts b/apps/web/src/settings/sections.ts index f83f0f98..1a85ec58 100644 --- a/apps/web/src/settings/sections.ts +++ b/apps/web/src/settings/sections.ts @@ -1,21 +1,4 @@ -import { - ArchiveIcon, - ChatTextIcon, - CpuIcon, - CubeIcon, - DesktopTowerIcon, - DevicesIcon, - HardDrivesIcon, - type Icon, - KeyboardIcon, - PaletteIcon, - PlugsConnectedIcon, - PuzzlePieceIcon, - SlidersHorizontalIcon, - SparkleIcon, - StackIcon, - UserIcon, -} from "@phosphor-icons/react"; +import { DesktopTowerIcon, HardDrivesIcon, type Icon, PaletteIcon, StackIcon, UserIcon } from "@phosphor-icons/react"; /** Whether a path is a settings page: the app's own, or the account's and workspace's under a workspace. */ export const isSettingsPath = (pathname: string) => @@ -24,24 +7,14 @@ export const isSettingsPath = (pathname: string) => export interface SettingsSection { readonly to: | "/workspaces/$workspaceId/settings/account/profile" - | "/settings/general" | "/settings/tabs" | "/settings/themes" | "/settings/servers" - | "/settings/paired" - | "/settings/keybindings" - | "/settings/models" - | "/settings/chat" - | "/settings/mcp" - | "/settings/skills" - | "/settings/plugins" - | "/workspaces/$workspaceId/settings/machines" - | "/settings/sandboxes" - | "/settings/archive"; + | "/settings/machines"; readonly label: string; readonly icon: Icon; /** Sidebar heading the section sits under. */ - readonly group: "Personal" | "Application" | "Workspaces"; + readonly group: "Personal" | "Application"; /** Extra words the search matches, beyond the label. */ readonly keywords: readonly string[]; } @@ -54,13 +27,6 @@ const sections: readonly SettingsSection[] = [ group: "Personal", keywords: ["account", "name", "email", "picture", "photo", "avatar"], }, - { - to: "/settings/general", - label: "General", - icon: SlidersHorizontalIcon, - group: "Application", - keywords: ["notifications", "sounds", "alerts", "quick", "composer", "editor", "terminal", "version", "updates"], - }, { to: "/settings/tabs", label: "Tabs", @@ -83,84 +49,23 @@ const sections: readonly SettingsSection[] = [ keywords: ["servers", "provider", "local", "remote", "cli", "service", "install", "codework", "version", "rpc"], }, { - to: "/settings/paired", - label: "Paired Machines", - icon: DevicesIcon, - group: "Application", - keywords: ["pair", "paired", "remote", "machine", "code", "ssh", "address", "label"], - }, - { - to: "/settings/keybindings", - label: "Keybindings", - icon: KeyboardIcon, - group: "Application", - keywords: ["shortcuts", "hotkeys", "keyboard", "bindings", "keys", "palette"], - }, - { - to: "/settings/models", - label: "Models", - icon: CpuIcon, - group: "Application", - keywords: [ - "accounts", - "oauth", - "codex", - "copilot", - "anthropic", - "openai", - "gemini", - "openrouter", - "thinking", - "retry", - "cache", - ], - }, - { - to: "/settings/chat", - label: "Chat", - icon: ChatTextIcon, - group: "Application", - keywords: ["transcript", "composer", "prompt", "steer", "queue", "follow-up", "usage", "tokens", "games"], - }, - { - to: "/settings/mcp", - label: "MCP", - icon: PlugsConnectedIcon, - group: "Application", - keywords: [ - "mcp", - "tools", - "servers", - "stdio", - "http", - "oauth", - "exposure", - "deferred", - "toolsearch", - "resources", - ], - }, - { - to: "/settings/skills", - label: "Skills", - icon: SparkleIcon, - group: "Application", - keywords: ["skills", "skill.md", "instructions", "workflows", "project", "personal"], - }, - { - to: "/settings/plugins", - label: "Plugins", - icon: PuzzlePieceIcon, - group: "Application", - keywords: ["plugins", "extensions", "npm", "tools", "prompt", "bash", "grep", "find", "reload"], - }, - { - to: "/workspaces/$workspaceId/settings/machines", + to: "/settings/machines", label: "Machines", icon: DesktopTowerIcon, - group: "Workspaces", + group: "Application", keywords: [ "machines", + "pair", + "paired", + "remote", + "code", + "ssh", + "address", + "label", + "link", + "linked", + "unlink", + "workspace", "connect", "online", "offline", @@ -174,23 +79,8 @@ const sections: readonly SettingsSection[] = [ "install", "cli", "server", - "paired", ], }, - { - to: "/settings/sandboxes", - label: "Sandboxes", - icon: CubeIcon, - group: "Application", - keywords: ["sandboxes", "worktrees", "git", "branch", "vercel", "daytona", "memory", "isolation"], - }, - { - to: "/settings/archive", - label: "Archive", - icon: ArchiveIcon, - group: "Application", - keywords: ["archived", "restore", "unarchive", "sessions", "projects", "hidden"], - }, ]; /** Sections whose label or keywords contain every word of the query, in sidebar order. */ diff --git a/apps/web/src/settings/servers/add.tsx b/apps/web/src/settings/servers/add.tsx index aedf328c..bc810745 100644 --- a/apps/web/src/settings/servers/add.tsx +++ b/apps/web/src/settings/servers/add.tsx @@ -107,7 +107,7 @@ export function AddServer({ {step === 1 && (
- + - + CODEWORK_HOME_DIR path } - description="codework home and config directory, its own: a home names one server." + description="codework home and config directory, its own: a home names one server" > - + - Additional CLI arguments passed to codework service start. + Additional CLI arguments passed to codework service start } value={status.args} diff --git a/apps/web/src/settings/servers/servers.tsx b/apps/web/src/settings/servers/servers.tsx index d5d88dbb..f78e4051 100644 --- a/apps/web/src/settings/servers/servers.tsx +++ b/apps/web/src/settings/servers/servers.tsx @@ -45,7 +45,7 @@ export function ServersSettings() { return ( - -
- } - > -
-
- - setQuery(event.target.value)} - /> -
- -
- -
- {visible.length === 0 ? ( - } - title="No matching skills" - description={ - query.trim() !== "" - ? `No skill matches “${query}”.` - : "Create a SKILL.md in your project or personal folder to teach the agent repeatable workflows." - } - /> - ) : ( - - {visible.map((skill) => { - const badge = SCOPE_BADGE[skill.scope]; - const previewing = previewId === skill.id; - const copied = copiedId === skill.id; - return ( -
-
- - -
- - {skill.scope !== "builtin" && ( - - )} - - setSkills((current) => - current.map((item) => (item.id === skill.id ? { ...item, enabled } : item)), - ) - } - /> -
-
- - {previewing && ( -
-
- - Previewing {skill.path} - - SKILL.md -
-
-												{skill.content}
-											
-
- )} -
- ); - })} -
- )} -
- -

- CodeWork scans .codework/skills/*/SKILL.md in the project and{" "} - ~/.codework/skills/*/SKILL.md in your home directory. -

- - {creating && ( - setCreating(false)} - onCreate={(item) => { - setSkills((current) => [item, ...current]); - setPreviewId(item.id); - setCreating(false); - }} - /> - )} - - ); -} - -function CreateSkillDialog({ - onClose, - onCreate, -}: { - readonly onClose: () => void; - readonly onCreate: (skill: SkillItem) => void; -}) { - const [scope, setScope] = useState<"project" | "personal">("project"); - const [name, setName] = useState(""); - const [description, setDescription] = useState(""); - - const slug = name - .trim() - .toLowerCase() - .replace(/[^a-z0-9-_]+/g, "-") - .replace(/^-+|-+$/g, ""); - const path = - scope === "project" - ? `.codework/skills/${slug || "my-skill"}/SKILL.md` - : `~/.codework/skills/${slug || "my-skill"}/SKILL.md`; - - const submit = () => { - if (!slug) return; - const desc = description.trim() || `Custom ${scope} skill instructions.`; - onCreate({ - id: `${slug}-${Date.now()}`, - name: slug, - description: desc, - scope, - path, - enabled: true, - content: `---\nname: ${slug}\ndescription: ${desc}\n---\n\n# ${slug}\n\nWrite instructions and examples for the agent here.`, - }); - }; - - return ( - !next && onClose()}> - - - Create Skill - - Scaffold a new SKILL.md instruction file. - - - -
- Location - -
- -
- - -

- Will create {path} -

-
- - - - - -
-
- ); -} diff --git a/apps/web/src/settings/tabs.tsx b/apps/web/src/settings/tabs.tsx index 2560fa99..529b64bd 100644 --- a/apps/web/src/settings/tabs.tsx +++ b/apps/web/src/settings/tabs.tsx @@ -105,7 +105,7 @@ export function TabsSettings() { return (
- + {shortcutLabel(1)}–{MAX_TABS} diff --git a/apps/web/src/settings/themes.tsx b/apps/web/src/settings/themes.tsx index 625e397b..979a1db5 100644 --- a/apps/web/src/settings/themes.tsx +++ b/apps/web/src/settings/themes.tsx @@ -56,7 +56,7 @@ export function ThemesSettings() { const [current, setTheme] = useAtom(themeAtom); return ( - +
Appearance
diff --git a/apps/web/src/setup.tsx b/apps/web/src/setup.tsx index c3d0c1bd..12b25a6e 100644 --- a/apps/web/src/setup.tsx +++ b/apps/web/src/setup.tsx @@ -1,17 +1,19 @@ import { shellQuoted } from "@codeworksh/schema"; import { useAtom, useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"; -import { CaretRightIcon, CheckIcon, CircleNotchIcon } from "@phosphor-icons/react"; +import type { Relay } from "@codeworksh/schema"; +import { CaretRightIcon, CheckIcon } from "@phosphor-icons/react"; import { useNavigate } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import { type ReactNode, useEffect, useState } from "react"; +import { BusyLabel } from "@/components/busy"; import { Collapse } from "@/components/collapse"; import { CopyCommand } from "@/components/copyable"; import { Button } from "@/components/ui/button"; import { messageOf } from "@/lib/utils"; import { Frame } from "./frame"; import { isSignedInApp } from "./auth"; -import { meAtom, workspaceAtom } from "./kernel/relay"; +import { workspaceAtom } from "./kernel/relay"; import { defaultServerAtom, INSTALL, installAtom, serviceAtom } from "./kernel/servers"; import { approveLabel, canAct, CodeSlot, useMachineAtom, useConnect } from "./shell/connect"; @@ -64,36 +66,37 @@ export function SetupGate() { if (checked || !isSignedInApp || workspace === undefined || needs === undefined) return; setChecked(true); if (needs && !putOff(workspace.id)) { - void navigate({ - to: "/workspaces/$workspaceId/settings/machines/setup", - params: { workspaceId: workspace.id }, - replace: true, - }); + void navigate({ to: "/settings/machines/setup", replace: true }); } }, [checked, setChecked, needs, workspace, navigate]); return null; } +/** Setup for the workspace the app works in, started over when another is picked. */ +export function SetupPage() { + const current = useAtomValue(workspaceAtom); + const workspace = AsyncResult.isSuccess(current) ? current.value : undefined; + return ; +} + /** * Sets up this machine for a workspace in three steps: install the CLI, start its server, connect to - * the workspace. Only the current step is open; each also offers its terminal command. + * the workspace. Only the current step is open; each also offers its terminal command. Until the + * workspace is known, there is nothing to connect to. */ -export function Setup({ workspaceId }: { readonly workspaceId: string }) { +function Setup({ workspace }: { readonly workspace: Relay.Workspace | undefined }) { const navigate = useNavigate(); const status = useAtomValue(defaultServerAtom); const machineAtom = useMachineAtom(); const machine = useAtomValue(machineAtom); const refreshMachine = useAtomRefresh(machineAtom); - const me = useAtomValue(meAtom); const install = useAtomSet(installAtom, { mode: "promise" }); const service = useAtomSet(serviceAtom, { mode: "promise" }); const [busy, setBusy] = useState<"install" | "start" | null>(null); const [error, setError] = useState(null); const [connecting, setConnecting] = useState(false); - const workspace = AsyncResult.isSuccess(me) - ? me.value.workspaces.find((option) => option.id === workspaceId) - : undefined; + const workspaceId = workspace?.id; const workspaceName = workspace?.name ?? "Your Workspace"; const cli = status?.cli ?? null; const version = cli !== null && "version" in cli ? cli.version : undefined; @@ -168,7 +171,7 @@ export function Setup({ workspaceId }: { readonly workspaceId: string }) { line="It keeps running in the background, also after the app quits." problem={ status?.server._tag === "Incompatible" - ? `The running server is v${status.server.version}, which this app can't read. Restart it with the installed CLI.` + ? `The running server is v${status.server.version}, which this app can’t read. Restart it with the installed CLI.` : null } command={`codework service start${home}`} @@ -185,13 +188,15 @@ export function Setup({ workspaceId }: { readonly workspaceId: string }) { summary={`Linked to ${workspaceName}`} line={`${name} shows up in ${workspaceName} for everyone in it.`} problem={null} - command={`codework connect --workspace ${workspaceId}${home}`} + command={`codework connect${workspaceId === undefined ? "" : ` --workspace ${workspaceId}`}${home}`} error={null} > - {connecting ? ( + {connecting && workspaceId !== undefined ? ( setConnecting(false)} /> ) : ( - + )} @@ -199,8 +204,8 @@ export function Setup({ workspaceId }: { readonly workspaceId: string }) {