From c36406cca88dd08426e866934cd86e0651dd47c4 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Tue, 10 Nov 2026 22:40:07 +0530 Subject: [PATCH 1/9] feat(web): frame menu with thread rows, sidebar current and color, menu motion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Frames get a ⋯ menu: Move (workspaces, New Tab) and, for sessions, Status, Priority, Group and Color with their current values. The session frame keeps the thread list mounted so the menu opens whole. - Sidebar marks the focused session with a background and other sessions on screen with full text, at one font weight; a thread's color washes in from the row's right edge. - The sidebar takes the main thread's color over the session's, as All Threads does, and refreshes on a thread color change. - Display menus show their current grouping and ordering. - Menus slide out of their trigger without scaling; submenus slide out of their row toward the side they open on. Co-Authored-By: Claude Opus 5.5 --- apps/contract/src/contract.ts | 2 +- apps/server/src/reads.ts | 3 +- apps/web/src/components/display.tsx | 2 +- apps/web/src/components/menu.tsx | 15 ++- apps/web/src/components/ui/dropdown-menu.tsx | 9 +- apps/web/src/landing/sidebar.tsx | 53 +++++++-- apps/web/src/widgets/session/menu.tsx | 115 +++++++++++++++++++ apps/web/src/widgets/session/projects.ts | 6 +- apps/web/src/widgets/session/view.tsx | 4 +- apps/web/src/widgets/threads/toolbar.tsx | 2 + apps/web/src/wm/desktop.tsx | 3 + apps/web/src/wm/frame.tsx | 62 +++++++--- 12 files changed, 233 insertions(+), 43 deletions(-) create mode 100644 apps/web/src/widgets/session/menu.tsx diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index d68560ef..8a800782 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -47,7 +47,7 @@ export const SidebarSession = Schema.Struct({ /** Its main thread. */ threadId: Schema.String, spaceKind: SpaceInfo.fields.kind, - /** Hex; null is the default. */ + /** Its main thread's color, else its own, as All Threads shows it; hex, null is the default. */ color: Schema.NullOr(Schema.String), /** The main thread's title, or what an untitled one is called. */ title: Schema.String, diff --git a/apps/server/src/reads.ts b/apps/server/src/reads.ts index e8043823..4dae22f3 100644 --- a/apps/server/src/reads.ts +++ b/apps/server/src/reads.ts @@ -80,7 +80,8 @@ export const sidebar = Effect.fn("Reads.sidebar")(function* ({ createdAt: number; updatedAt: number; }>` - SELECT session.id, session.machine_id, space.project_id, space.kind AS space_kind, session.color, + SELECT session.id, session.machine_id, space.project_id, space.kind AS space_kind, + COALESCE(thread.color, session.color) AS color, session.dir, session.hostdir, thread.id AS thread_id, thread.title, thread.model_provider, thread.model_id, thread.run_state, thread.status, thread.priority, thread.created_at, (SELECT MAX(activity.updated_at) FROM thread AS activity diff --git a/apps/web/src/components/display.tsx b/apps/web/src/components/display.tsx index 143a4e62..31de5d95 100644 --- a/apps/web/src/components/display.tsx +++ b/apps/web/src/components/display.tsx @@ -29,7 +29,7 @@ export function DisplayMenu({ - + {children} diff --git a/apps/web/src/components/menu.tsx b/apps/web/src/components/menu.tsx index a9b4c646..fc219968 100644 --- a/apps/web/src/components/menu.tsx +++ b/apps/web/src/components/menu.tsx @@ -25,12 +25,14 @@ export function MenuCheck() { /** * One choice of a menu: its mark and name, opening its picks beside it with the current one checked. - * `after` holds actions rather than picks, such as clearing it, below a separator. + * `current` names the pick on the row itself, before the chevron. `after` holds actions rather than + * picks, such as clearing it, below a separator. */ export function MenuChoice({ label, mark, value, + current, options, onChange, after, @@ -38,15 +40,22 @@ export function MenuChoice({ readonly label: string; readonly mark: ReactNode; readonly value: A | undefined; + readonly current?: string | undefined; readonly options: ReadonlyArray<{ readonly value: A; readonly label: string; readonly mark: ReactNode }>; readonly onChange: (value: A) => void; readonly after?: ReactNode; }) { return ( - svg:last-child]:size-3.5`}> - {mark} + svg:last-child]:size-3.5 ${current === undefined ? "" : "[&>svg:last-child]:ml-0"}`} + > + {/* One width for every mark, so a dot's label lines up with an icon's. */} + {mark} {label} + {current !== undefined && ( + {current} + )} {/* Shifted up by its padding and border, so its first row lines up with the trigger. */} diff --git a/apps/web/src/components/ui/dropdown-menu.tsx b/apps/web/src/components/ui/dropdown-menu.tsx index 5bd29baa..a336fb00 100644 --- a/apps/web/src/components/ui/dropdown-menu.tsx +++ b/apps/web/src/components/ui/dropdown-menu.tsx @@ -15,6 +15,8 @@ function DropdownMenuTrigger({ ...props }: React.ComponentProps; } +// A menu comes out of its trigger: a short slide away from it as it fades in, no growth. It leaves +// by fading alone, quicker than it came. function DropdownMenuContent({ className, sideOffset = 4, @@ -26,7 +28,7 @@ function DropdownMenuContent({ data-slot="dropdown-menu-content" sideOffset={sideOffset} className={cn( - "z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-[12px] border bg-popover p-1 text-[13px] text-popover-foreground shadow-(--cw-menu-shadow) [-webkit-app-region:no-drag] data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:duration-100 data-[state=closed]:ease-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:duration-150 data-[state=open]:ease-out data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95", + "z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-[12px] border bg-popover p-1 text-[13px] text-popover-foreground shadow-(--cw-menu-shadow) [-webkit-app-region:no-drag] data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1 data-[state=closed]:animate-out data-[state=closed]:duration-100 data-[state=closed]:ease-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:duration-150 data-[state=open]:ease-(--ease-out) data-[state=open]:fade-in-0 motion-reduce:animate-none", className, )} {...props} @@ -179,7 +181,8 @@ function DropdownMenuSubTrigger({ ); } -// Submenus open as an OS menu's do, at once: they are browsed by hover many times in a row. +// A submenu slides out of its row toward the side it opens on, shorter than a menu: rows are browsed +// by hover many times in a row. It closes at once, so moving to the next row never shows two. function DropdownMenuSubContent({ className, ...props @@ -188,7 +191,7 @@ function DropdownMenuSubContent({ instance.id === focusedId)?.address; + const workspace = useWorkspaces().find((candidate) => candidate.id === workspaceId); + const focusedId = workspace === undefined ? undefined : focusedOn.get(workspace.id); + const current = threadRef(instances.find((instance) => instance.id === focusedId)?.address)?.sessionId; + const shown = new Set( + workspace === undefined + ? [] + : instances.flatMap((instance) => + (instance.tags & workspaceTag(workspace)) === 0 ? [] : (threadRef(instance.address)?.sessionId ?? []), + ), + ); // A new session starts on the start page, in the current session's project when one is in front. const startNew = () => { const project = AsyncResult.isSuccess(result) - ? result.value.find((candidate) => candidate.sessions.some(({ id }) => sessionAddress(id) === current)) + ? result.value.find((candidate) => candidate.sessions.some(({ id }) => id === current)) : undefined; if (project !== undefined) setPlace({ kind: "folder", path: project.path }); void navigate({ to: "/" }); @@ -200,6 +209,7 @@ export function SessionsSidebar() { label="Grouping" mark={} value={display.group} + current={GROUPS.find(({ value }) => value === display.group)?.label} options={marked(GROUPS)} onChange={(group) => changeDisplay({ group })} /> @@ -207,6 +217,7 @@ export function SessionsSidebar() { label="Ordering" mark={} value={display.order} + current={ORDERS.find(({ value }) => value === display.order)?.label} options={marked(ORDERS)} onChange={(order) => changeDisplay({ order })} /> @@ -218,6 +229,7 @@ export function SessionsSidebar() { group={group} expanded={needle !== "" || !collapsed.has(group.key)} current={current} + shown={shown} onToggle={() => toggle(group.key)} onStartNew={group.kind === "project" ? () => startIn(group.project.path) : undefined} onOpen={open} @@ -248,27 +260,31 @@ function GroupSection({ group, expanded, current, + shown, onToggle, onStartNew, onOpen, }: { readonly group: Group; readonly expanded: boolean; + /** The session id in front on the workspace on screen. */ readonly current: string | undefined; + /** Every session id the workspace on screen shows. */ + readonly shown: ReadonlySet; readonly onToggle: () => void; /** A project's new thread; other groups have none. */ readonly onStartNew: (() => void) | undefined; readonly onOpen: (sessionId: string, projectName: string, event: MouseEvent) => void; }) { const label = groupLabel(group); - const open = expanded ? undefined : group.entries.find(({ session }) => sessionAddress(session.id) === current); + const open = expanded ? undefined : group.entries.find(({ session }) => session.id === current); const row = ({ session, project }: Entry) => ( ); @@ -328,14 +344,15 @@ const SessionRow = memo(function SessionRow({ session, projectName, machineName, - current, + state, onOpen, }: { /** Kept across reads while it does not change, with the project's parts as plain values, so the row renders only for its own changes. */ readonly session: SidebarSession; readonly projectName: string; readonly machineName: string; - readonly current: boolean; + /** In front on the workspace on screen, or shown there in another frame. */ + readonly state: "current" | "shown" | undefined; readonly onOpen: (sessionId: string, projectName: string, event: MouseEvent) => void; }) { // The main thread's key is its session's id. @@ -345,12 +362,24 @@ const SessionRow = memo(function SessionRow({ + +
{ + if (event.key !== "Escape" || event.defaultPrevented) return; + event.preventDefault(); + onBack(); + }} + className="min-h-0 flex-1 overflow-y-auto outline-none" + > + {SECTIONS.map((Section, index) => ( +
+
+
+ ))} +
+ + ); +} diff --git a/apps/web/src/widgets/session/view.tsx b/apps/web/src/widgets/session/view.tsx index 369d365c..09c1637e 100644 --- a/apps/web/src/widgets/session/view.tsx +++ b/apps/web/src/widgets/session/view.tsx @@ -14,9 +14,10 @@ import { threadAddress, threadRef } from "./address"; import { SessionComposer } from "./composer"; import { useFollow } from "./follow"; import { Markdown } from "./markdown"; -import { menuThreads } from "./menu"; +import { menuThreads, useSettings } from "./menu"; import { Message } from "./message"; import { Queue } from "./queue"; +import { ProjectSettings } from "./settings"; import { type Handoff, handoffs } from "./handoff"; import { type Display, displayLabel, usePendingPrompts, useRunDisplay, useSent } from "./display"; import { useNowSecond } from "../../hooks/now"; @@ -47,8 +48,17 @@ export function Session({ address, instanceId }: WidgetProps) { const [shown, setShown] = useState<{ readonly key: string; readonly previous?: string }>({ key }); if (shown.key !== key) setShown({ key, previous: shown.key }); useAtomMount(menuThreads); + const [settings, setSettings] = useSettings(instanceId); if (thread === undefined) return

Not a session: {address}

; - return ; + // The thread stays mounted under its project's settings, so it comes back as it was left. + return ( + <> + + {settings && setSettings(false)} />} + + ); } type State = @@ -498,7 +508,13 @@ function Conversation({ const project = state.status === "ready" ? state.info.project : listed?.project; const projectName = project?.name; + const [settings] = useSettings(instanceId); useEffect(() => { + if (settings) { + setTitle("Settings", projectName); + setTab(projectName === undefined ? "Settings" : `${projectName} / Settings`); + return; + } if (title === undefined) return; // The project leads, so sessions from different projects tell apart at a glance. setTitle(title, projectName); @@ -507,7 +523,7 @@ function Conversation({ if (projectName !== undefined) setIcon(); // While focused, the workspace's tab reads as this session: its project, then its title. setTab(projectName === undefined ? title : `${projectName} / ${title}`); - }, [title, projectName, setTitle, setIcon, setTab]); + }, [settings, title, projectName, setTitle, setIcon, setTab]); // Models that can't be listed first: a state that clears itself, so it can't be dismissed. Then a // refused send, else why the last run failed; dismissing hides that one notice only. diff --git a/apps/web/src/wm/desktop.tsx b/apps/web/src/wm/desktop.tsx index a1f40536..44fa259b 100644 --- a/apps/web/src/wm/desktop.tsx +++ b/apps/web/src/wm/desktop.tsx @@ -466,7 +466,11 @@ export function Desktop({ workspace }: DesktopProps) { if (destination !== undefined) move(widget.id, destination); }} onMoveNew={workspaces.length < MAX_WORKSPACES ? () => void moveNew(widget.id) : undefined} - menu={instance.kind === session.kind ? : undefined} + menu={ + instance.kind === session.kind ? ( + + ) : undefined + } onClose={() => close(widget.id)} onDragStart={() => setDrag({ widgetId: widget.id, deltaX: 0, deltaY: 0, target: null })} onDragMove={({ clientX, clientY, deltaX, deltaY }) => From a72788e3f0e9880d75294862fa694f3eb659b428 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Wed, 11 Nov 2026 10:20:43 +0530 Subject: [PATCH 3/9] feat(web): project banner with an editable name in project settings - Project settings open on a banner: the project's folder tile, its name as the page title, and its folder and machine. The name is a field: type, then Enter or leave it to save; Esc puts it back. The new name shows until the rename syncs back. - The placeholder sections leave the page; features return one by one. - projects.rename forwards to CodeWork's project.rename through the app server; the widget contract mirrors the call. - The frame header takes the project name from the list, so it follows a rename instead of keeping the name the thread opened with. Co-Authored-By: Claude Opus 5.5 --- apps/contract/src/contract.ts | 11 +++ apps/server/src/handlers.ts | 18 ++++- apps/web/src/widgets/session/settings.tsx | 88 +++++++++++++++++++---- apps/web/src/widgets/session/view.tsx | 5 +- apps/widget/src/codework.ts | 10 +++ 5 files changed, 114 insertions(+), 18 deletions(-) diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index 8a800782..ced0939f 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -82,6 +82,11 @@ export class HostError extends Schema.TaggedError()("Server.HostError message: Schema.String, }) {} +/** A project operation that failed, such as renaming one the server no longer has. */ +export class ProjectError extends Schema.TaggedError()("Server.ProjectError", { + message: Schema.String, +}) {} + export { Clone, ClonePhase, CloneStage, Folder, Repository }; /** The models could not be listed: a settings file or the model catalog, at `path`, is broken. */ @@ -477,6 +482,12 @@ export const Api = RpcGroup.make( success: Schema.Struct({ path: Schema.String, commitError: Schema.optionalKey(Schema.String) }), error: Schema.Union([CodeworkUnavailable, HostError]), }), + /** Renames a project on the CodeWork server; the sidebar follows once the change syncs back. */ + Rpc.make("projects.rename", { + payload: { projectId: Schema.String, name: Schema.Trimmed.check(Schema.isNonEmpty()) }, + success: Schema.Struct({ id: Schema.String, name: Schema.String }), + error: Schema.Union([CodeworkUnavailable, HostError, ProjectError]), + }), /** An existing folder as an absolute path; a missing one is created. */ Rpc.make("host.add", { payload: { path: Schema.String }, diff --git a/apps/server/src/handlers.ts b/apps/server/src/handlers.ts index 70108f90..16db86b7 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -2,7 +2,14 @@ import { Effect, Stream } from "effect"; import { SqlClient } from "effect/sql"; import { Cli } from "./cli.ts"; import { Codework } from "./codework.ts"; -import { type CliAction, Contract, ModelsError, type ServerAdd, type ServerUpdate } from "@codeworksh/contract"; +import { + type CliAction, + Contract, + ModelsError, + ProjectError, + type ServerAdd, + type ServerUpdate, +} from "@codeworksh/contract"; import { Desk } from "./desk.ts"; import { Event } from "./event.ts"; import { Health } from "./health.ts"; @@ -58,6 +65,15 @@ export const layer = Contract.Api.toLayer( "host.create": Effect.fn("host.create")(function* ({ name }) { return yield* callHost((client) => client("host.create", { name }), { timeout: "60 seconds" }); }), + "projects.rename": Effect.fn("projects.rename")(function* ({ projectId, name }) { + return yield* callHost((client) => + client("project.rename", { projectId, name }).pipe( + Effect.catchTag("ProjectNotFoundError", () => + Effect.fail(new ProjectError({ message: "This project is no longer on its server." })), + ), + ), + ); + }), "host.add": Effect.fn("host.add")(function* ({ path }) { return yield* callHost((client) => client("host.add", { path })); }), diff --git a/apps/web/src/widgets/session/settings.tsx b/apps/web/src/widgets/session/settings.tsx index 6fbafc3b..72d34257 100644 --- a/apps/web/src/widgets/session/settings.tsx +++ b/apps/web/src/widgets/session/settings.tsx @@ -1,17 +1,21 @@ -import { useEffect, useRef } from "react"; +import type { SidebarProject } from "@codeworksh/contract"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import { useEffect, useRef, useState } from "react"; -import { ArrowLeft } from "@/components/vuesax"; -import { McpSettings } from "../../settings/mcp"; -import { ModelsSettings } from "../../settings/models"; -import { PluginsSettings } from "../../settings/plugins"; -import { SandboxesSettings } from "../../settings/sandboxes"; -import { SkillsSettings } from "../../settings/skills"; +import { ArrowLeft, Folder } from "@/components/vuesax"; +import { Server } from "../../kernel/rpc"; +import { failed } from "../threads/common"; +import { projectsAtom } from "./projects"; -/** The sections a project has, one page after another. */ -const SECTIONS = [ModelsSettings, McpSettings, SkillsSettings, PluginsSettings, SandboxesSettings]; +const renameProject = Server.mutation("projects.rename"); /** A session's project settings in place of its thread; Esc or the back row returns to the thread. */ -export function ProjectSettings({ onBack }: { readonly onBack: () => void }) { +export function ProjectSettings({ sessionId, onBack }: { readonly sessionId: string; readonly onBack: () => void }) { + const result = useAtomValue(projectsAtom); + const project = AsyncResult.isSuccess(result) + ? result.value.find((candidate) => candidate.sessions.some(({ id }) => id === sessionId)) + : undefined; const scroller = useRef(null); // Takes focus as it opens, so Esc returns from this frame only. useEffect(() => scroller.current?.focus({ preventScroll: true }), []); @@ -37,12 +41,66 @@ export function ProjectSettings({ onBack }: { readonly onBack: () => void }) { }} className="min-h-0 flex-1 overflow-y-auto outline-none" > - {SECTIONS.map((Section, index) => ( -
-
-
- ))} +
+ {project !== undefined && } +
); } + +/** The project as a tile, its name as the page's title and where it lives. The name is a field: type, then Enter or leave it. */ +function Banner({ project }: { readonly project: SidebarProject }) { + const rename = useAtomSet(renameProject, { mode: "promise" }); + // What is typed, until it is saved or put back. + const [draft, setDraft] = useState(); + // The saved name, shown until the rename syncs back to the list. + const [pending, setPending] = useState(); + if (pending !== undefined && project.name === pending) setPending(undefined); + const name = pending ?? project.name; + const commit = (value: string) => { + const next = value.trim(); + setDraft(undefined); + if (next === "" || next === name) return; + setPending(next); + void rename({ payload: { projectId: project.id, name: next } }).catch((error: unknown) => { + setPending(undefined); + failed(error); + }); + }; + return ( +
+ + + +
+ setDraft(event.target.value)} + onBlur={(event) => commit(event.currentTarget.value)} + onKeyDown={(event) => { + if (event.key === "Enter") event.currentTarget.blur(); + if (event.key === "Escape") { + // Puts the saved name back; the settings stay open. + event.preventDefault(); + setDraft(undefined); + event.currentTarget.value = name; + event.currentTarget.blur(); + } + }} + className="-mx-1.5 h-8 w-full min-w-0 truncate rounded-md bg-transparent px-1.5 text-[22px]/8 font-semibold tracking-tight outline-none transition-colors duration-150 ease-out hover:bg-ink/4 focus:bg-ink/4" + /> +
+ {/* From its end: the last parts tell projects apart, not the home directory. */} + + {project.path} + + · + {project.machine.name} +
+
+
+ ); +} diff --git a/apps/web/src/widgets/session/view.tsx b/apps/web/src/widgets/session/view.tsx index 09c1637e..27c87b91 100644 --- a/apps/web/src/widgets/session/view.tsx +++ b/apps/web/src/widgets/session/view.tsx @@ -56,7 +56,7 @@ export function Session({ address, instanceId }: WidgetProps) { - {settings && setSettings(false)} />} + {settings && setSettings(false)} />} ); } @@ -505,7 +505,8 @@ function Conversation({ // Named from the sessions list at once, so the frame never shows its default title while loading. const listed = useListedSession(thread.sessionId); const title = state.status === "ready" ? state.info.title : listed?.title; - const project = state.status === "ready" ? state.info.project : listed?.project; + // The list follows a rename; the loaded thread keeps the name it was opened with. + const project = listed?.project ?? (state.status === "ready" ? state.info.project : undefined); const projectName = project?.name; const [settings] = useSettings(instanceId); diff --git a/apps/widget/src/codework.ts b/apps/widget/src/codework.ts index bcaf4776..c1f8a31d 100644 --- a/apps/widget/src/codework.ts +++ b/apps/widget/src/codework.ts @@ -373,6 +373,10 @@ export const RuntimeConfig = Schema.Struct({ export type RuntimeConfig = typeof RuntimeConfig.Type; /** A host folder operation that failed: unreadable, not a directory, taken, or git/gh refused. */ +export class ProjectNotFoundError extends Schema.TaggedError()("ProjectNotFoundError", { + projectId: Schema.String, +}) {} + export class HostError extends Schema.TaggedError()("Server.HostError", { message: Schema.String, }) {} @@ -522,6 +526,12 @@ export const Api = RpcGroup.make( success: ThreadInfo, error: CreateError, }), + /** Renames a project. Trimmed, non-empty. */ + Rpc.make("project.rename", { + payload: { projectId: Schema.String, name: Schema.String }, + success: Schema.Struct({ id: Schema.String, name: Schema.String }), + error: ProjectNotFoundError, + }), /** The models a session anchored at `hostDir` can use; without it, only the user's settings apply. */ Rpc.make("model.list", { payload: { hostDir: Schema.optionalKey(Schema.String) }, From f0c82a532838e513bf111f385a875b5d2ed97e93 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Wed, 11 Nov 2026 11:36:08 +0530 Subject: [PATCH 4/9] feat(web): Repositories section with the project's remote URL - Project settings gain a Repositories section: the remote URL the project was cloned from, with a copy button, and its main checkout. Headings and rows follow Linear's settings type and spacing, a step quieter; the banner shows the project's folder only. - Switching threads keeps the page whole: it waits for the next project's directories and remote before swapping in one render. - project.remote in CodeWork reads origin of the project's main checkout on the host, with credentials taken out of http(s) URLs; null for a folder, a sandbox or no origin. The e2e test covers it. - projects.remote and projects.spaces (directories from the synced space table) through the app server. Co-Authored-By: Claude Opus 5.5 --- apps/contract/src/contract.ts | 22 +++ apps/server/src/handlers.ts | 10 ++ apps/server/src/reads.ts | 17 +++ apps/web/src/widgets/session/projects.ts | 22 +++ apps/web/src/widgets/session/settings.tsx | 131 ++++++++++++++++-- apps/widget/src/codework.ts | 6 + packages/codework/src/server/contract.ts | 6 + packages/codework/src/server/handlers.ts | 5 + packages/codework/src/server/host.ts | 22 ++- .../__artifacts__/server.project-name.json | 9 +- packages/codework/test/server.test.ts | 28 ++++ packages/harness/src/project/project.ts | 15 ++ 12 files changed, 276 insertions(+), 17 deletions(-) diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index ced0939f..a43d6ff0 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -77,6 +77,17 @@ export const SidebarProject = Schema.Struct({ }); export type SidebarProject = typeof SidebarProject.Type; +/** One of a project's directories: its main checkout, a worktree, a copy or a plain folder. */ +export const ProjectSpace = Schema.Struct({ + id: Schema.String, + location: Schema.String, + kind: SpaceInfo.fields.kind, + /** The sandbox it is in; null for the host. */ + env: Schema.NullOr(Schema.String), + status: SpaceInfo.fields.status, +}); +export type ProjectSpace = typeof ProjectSpace.Type; + /** A host folder operation that failed: unreadable, not a directory, taken, or git/gh refused. */ export class HostError extends Schema.TaggedError()("Server.HostError", { message: Schema.String, @@ -444,6 +455,11 @@ export const Api = RpcGroup.make( * An organization's active projects, newest activity first, each with its sessions that are not * deleted: on the default machine only, or on every machine. Read from app.db alone. */ + /** A project's directories, its main checkout first; read from app.db alone. */ + Rpc.make("projects.spaces", { + payload: { machineId: Schema.String, projectId: Schema.String }, + success: Schema.Array(ProjectSpace), + }), Rpc.make("sidebar.list", { payload: { organizationId: Schema.String, machines: Schema.Literals(["default", "all"]) }, success: Schema.Array(SidebarProject), @@ -482,6 +498,12 @@ export const Api = RpcGroup.make( success: Schema.Struct({ path: Schema.String, commitError: Schema.optionalKey(Schema.String) }), error: Schema.Union([CodeworkUnavailable, HostError]), }), + /** The `origin` URL of a project's main checkout, credentials taken out; null when it has none. */ + Rpc.make("projects.remote", { + payload: { projectId: Schema.String }, + success: Schema.Struct({ url: Schema.NullOr(Schema.String) }), + error: Schema.Union([CodeworkUnavailable, HostError, ProjectError]), + }), /** Renames a project on the CodeWork server; the sidebar follows once the change syncs back. */ Rpc.make("projects.rename", { payload: { projectId: Schema.String, name: Schema.Trimmed.check(Schema.isNonEmpty()) }, diff --git a/apps/server/src/handlers.ts b/apps/server/src/handlers.ts index 16db86b7..6e372990 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -52,6 +52,7 @@ export const layer = Contract.Api.toLayer( ...tracking, "sidebar.list": (input) => Reads.sidebar(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)), + "projects.spaces": (input) => Reads.spaces(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)), "threads.list": (input) => Reads.threads(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)), "threads.line": (input) => Reads.line(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)), @@ -65,6 +66,15 @@ export const layer = Contract.Api.toLayer( "host.create": Effect.fn("host.create")(function* ({ name }) { return yield* callHost((client) => client("host.create", { name }), { timeout: "60 seconds" }); }), + "projects.remote": Effect.fn("projects.remote")(function* ({ projectId }) { + return yield* callHost((client) => + client("project.remote", { projectId }).pipe( + Effect.catchTag("ProjectNotFoundError", () => + Effect.fail(new ProjectError({ message: "This project is no longer on its server." })), + ), + ), + ); + }), "projects.rename": Effect.fn("projects.rename")(function* ({ projectId, name }) { return yield* callHost((client) => client("project.rename", { projectId, name }).pipe( diff --git a/apps/server/src/reads.ts b/apps/server/src/reads.ts index 4dae22f3..57323e5d 100644 --- a/apps/server/src/reads.ts +++ b/apps/server/src/reads.ts @@ -9,6 +9,7 @@ import { type LineRequest, LineThread, type Priority, + type ProjectSpace, type SidebarProject, type SidebarSession, SyncError, @@ -428,4 +429,20 @@ export const line = Effect.fn("Reads.line")(function* (request: LineRequest) { }).pipe(Effect.orDie); }); +/** A project's directories, its main checkout first, then by folder. */ +export const spaces = Effect.fn("Reads.spaces")(function* ({ + machineId, + projectId, +}: { + readonly machineId: string; + readonly projectId: string; +}) { + const sql = yield* SqlClient.SqlClient; + return yield* sql` + SELECT id, location, kind, env, status FROM space + WHERE machine_id = ${machineId} AND project_id = ${projectId} + ORDER BY kind <> 'primary', location + `; +}, Effect.orDie); + export * as Reads from "./reads.ts"; diff --git a/apps/web/src/widgets/session/projects.ts b/apps/web/src/widgets/session/projects.ts index 289136ce..55eeb3db 100644 --- a/apps/web/src/widgets/session/projects.ts +++ b/apps/web/src/widgets/session/projects.ts @@ -97,6 +97,28 @@ export const projectsAtom = Server.runtime ) .pipe(Atom.keepAlive); +/** A project's directories, by `/`: read when subscribed, and again after their sync changes. */ +export const spacesAtom = Atom.family((key: string) => { + const [machineId = "", projectId = ""] = key.split("/"); + return Server.runtime.atom( + Stream.unwrap( + Server.use((client) => + Effect.succeed( + client("event.subscribe", { topics: [syncTopics.changed] }).pipe( + Stream.filter( + (item) => + "_tag" in item || + Option.exists(decodeChanged(item.payload), (notice) => notice.space.length > 0), + ), + Stream.debounce("50 millis"), + Stream.mapEffect(() => client("projects.spaces", { machineId, projectId })), + ), + ), + ), + ).pipe(Stream.retry(Schedule.spaced("1 second"))), + ); +}); + /** Each session's main thread's run state, as synced. */ const mainRunStatesAtom = Atom.make((get) => { const result = get(projectsAtom); diff --git a/apps/web/src/widgets/session/settings.tsx b/apps/web/src/widgets/session/settings.tsx index 72d34257..3fee828b 100644 --- a/apps/web/src/widgets/session/settings.tsx +++ b/apps/web/src/widgets/session/settings.tsx @@ -1,14 +1,16 @@ -import type { SidebarProject } from "@codeworksh/contract"; +import type { ProjectSpace, SidebarProject } from "@codeworksh/contract"; import { useAtomSet, useAtomValue } from "@effect/atom-react"; import { AsyncResult } from "effect/reactivity"; import { useEffect, useRef, useState } from "react"; +import { toast } from "sonner"; -import { ArrowLeft, Folder } from "@/components/vuesax"; +import { ArrowLeft, Check, Copy, Folder, FolderGit2 } from "@/components/vuesax"; import { Server } from "../../kernel/rpc"; import { failed } from "../threads/common"; -import { projectsAtom } from "./projects"; +import { projectsAtom, spacesAtom } from "./projects"; const renameProject = Server.mutation("projects.rename"); +const remoteOf = (projectId: string) => Server.query("projects.remote", { projectId }); /** A session's project settings in place of its thread; Esc or the back row returns to the thread. */ export function ProjectSettings({ sessionId, onBack }: { readonly sessionId: string; readonly onBack: () => void }) { @@ -41,15 +43,46 @@ export function ProjectSettings({ sessionId, onBack }: { readonly sessionId: str }} className="min-h-0 flex-1 overflow-y-auto outline-none" > -
- {project !== undefined && } +
+ {project !== undefined && }
); } -/** The project as a tile, its name as the page's title and where it lives. The name is a field: type, then Enter or leave it. */ +interface View { + readonly project: SidebarProject; + readonly main: ProjectSpace | undefined; + /** Null when the project has no remote, or it could not be read. */ + readonly url: string | null; +} + +/** + * The page for `project`, drawn once its directories and remote are both in. Until then the page last + * drawn stays, whole: switching threads never shows one project's banner over a section still loading. + */ +function Page({ project }: { readonly project: SidebarProject }) { + const spaces = useAtomValue(spacesAtom(`${project.machine.id}/${project.id}`)); + const remote = useAtomValue(remoteOf(project.id)); + const settled = (result: AsyncResult.AsyncResult) => + AsyncResult.isSuccess(result) || AsyncResult.isFailure(result); + const main = AsyncResult.isSuccess(spaces) ? spaces.value.find((space) => space.kind === "primary") : undefined; + const url = AsyncResult.isSuccess(remote) ? remote.value.url : null; + const ready = settled(spaces) && settled(remote); + const [view, setView] = useState(); + if (ready && (view?.project !== project || view.main !== main || view.url !== url)) setView({ project, main, url }); + if (view === undefined) return null; + return ( + <> + {/* Keyed, so a name typed for one project never carries into the next. */} + + {view.main !== undefined && } + + ); +} + +/** The project as a tile, its name as the page's title and its folder. The name is a field: type, then Enter or leave it. */ function Banner({ project }: { readonly project: SidebarProject }) { const rename = useAtomSet(renameProject, { mode: "promise" }); // What is typed, until it is saved or put back. @@ -90,17 +123,85 @@ function Banner({ project }: { readonly project: SidebarProject }) { event.currentTarget.blur(); } }} - className="-mx-1.5 h-8 w-full min-w-0 truncate rounded-md bg-transparent px-1.5 text-[22px]/8 font-semibold tracking-tight outline-none transition-colors duration-150 ease-out hover:bg-ink/4 focus:bg-ink/4" + className="-mx-1.5 h-8 w-full min-w-0 truncate rounded-md bg-transparent px-1.5 text-[22px]/8 font-medium tracking-[-0.01em] outline-none transition-colors duration-150 ease-out hover:bg-ink/4 focus:bg-ink/4" /> -
- {/* From its end: the last parts tell projects apart, not the home directory. */} - - {project.path} - - · - {project.machine.name} -
+ {/* From its end: the last parts tell projects apart, not the home directory. */} + + {project.path} + ); } + +/** A section heading as Linear sets one, a step quieter: medium weight, in line with its rows' text. */ +function Heading({ children }: { readonly children: string }) { + return

{children}

; +} + +/** The project's repository: the URL it was cloned from, then its main checkout. */ +function Repository({ main, url }: { readonly main: ProjectSpace; readonly url: string | null }) { + return ( +
+ Repositories +
+
+
+ Remote URL + Where this repository was cloned from +
+ {url === null ? ( + No remote + ) : ( + // Text to read and copy, not a field: nothing here suggests it can be changed. +
+ + {url} + + +
+ )} +
+
+ +
+ {nameOf(main.location)} + {/* From its end: the last parts tell checkouts apart. */} + + {main.location} + +
+ Main +
+
+
+ ); +} + +/** Copies `text`, then shows a check for a moment so the copy is seen to have happened. */ +function CopyButton({ text }: { readonly text: string }) { + const [copied, setCopied] = useState(false); + useEffect(() => { + if (!copied) return; + const timer = setTimeout(() => setCopied(false), 1500); + return () => clearTimeout(timer); + }, [copied]); + return ( + + ); +} + +const nameOf = (location: string) => location.split("/").filter(Boolean).at(-1) ?? location; diff --git a/apps/widget/src/codework.ts b/apps/widget/src/codework.ts index c1f8a31d..60456cd8 100644 --- a/apps/widget/src/codework.ts +++ b/apps/widget/src/codework.ts @@ -526,6 +526,12 @@ export const Api = RpcGroup.make( success: ThreadInfo, error: CreateError, }), + /** The `origin` URL of a project's main checkout on the host, credentials taken out; null when there is none. */ + Rpc.make("project.remote", { + payload: { projectId: Schema.String }, + success: Schema.Struct({ url: Schema.NullOr(Schema.String) }), + error: ProjectNotFoundError, + }), /** Renames a project. Trimmed, non-empty. */ Rpc.make("project.rename", { payload: { projectId: Schema.String, name: Schema.String }, diff --git a/packages/codework/src/server/contract.ts b/packages/codework/src/server/contract.ts index c3db2716..3078147d 100644 --- a/packages/codework/src/server/contract.ts +++ b/packages/codework/src/server/contract.ts @@ -493,6 +493,12 @@ export const Api = RpcGroup.make( /** `HostError` when `hostDir` is a clone still running, failed or cancelled. */ error: Schema.Union([SessionErrors, SandboxErrors, LocationErrors, HostError]), }), + /** The `origin` URL of a project's main checkout on the host, credentials taken out; null when there is none. */ + Rpc.make("project.remote", { + payload: { projectId: Schema.String }, + success: Schema.Struct({ url: Schema.NullOr(Schema.String) }), + error: Project.ProjectNotFoundError, + }), Rpc.make("project.rename", { payload: { projectId: Schema.String, name: ProjectName }, success: Schema.Struct({ id: Schema.String, name: Schema.String }), diff --git a/packages/codework/src/server/handlers.ts b/packages/codework/src/server/handlers.ts index 42777b52..abaee83c 100644 --- a/packages/codework/src/server/handlers.ts +++ b/packages/codework/src/server/handlers.ts @@ -308,6 +308,11 @@ export const layer = Contract.Api.toLayer( }, }; }), + "project.remote": Effect.fnUntraced(function* ({ projectId }) { + const checkout = yield* Project.mainCheckout(projectId); + const url = checkout === undefined ? undefined : yield* host.remote(checkout); + return { url: url ?? null }; + }), "project.rename": Effect.fnUntraced(function* ({ projectId, name }) { const renamed = yield* Project.rename({ projectId, name }); return { id: renamed.id, name: renamed.name }; diff --git a/packages/codework/src/server/host.ts b/packages/codework/src/server/host.ts index 3cf72d6d..3fcf22b8 100644 --- a/packages/codework/src/server/host.ts +++ b/packages/codework/src/server/host.ts @@ -26,6 +26,8 @@ interface Interface { ) => Effect.Effect<{ readonly path: string; readonly commitError?: string }, Contract.HostError>; readonly status: () => Effect.Effect; readonly lookup: (repository: string) => Effect.Effect; + /** The `origin` URL of the checkout at `directory`, with any credentials taken out; none without one. */ + readonly remote: (directory: string) => Effect.Effect; } export class Service extends Context.Service()("@codeworksh/cli/server/host/Service") {} @@ -113,6 +115,19 @@ export const parseRepository = (selector: string): Selector | undefined => { return parts.length === 3 && host !== undefined && isGitHubHost(host) ? named(host, second, third) : undefined; }; +/** + * A remote URL safe to show: an http(s) URL loses its user and password, which may be a token + * (`https://x-access-token:...@github.com/...`). SSH and local forms carry none and pass as they are. + */ +export const shownRemote = (url: string) => { + if (!/^https?:\/\//i.test(url)) return url; + const parsed = URL.parse(url); + if (parsed === null) return url; + parsed.username = ""; + parsed.password = ""; + return parsed.toString(); +}; + const decodeRepository = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Struct({ full_name: Schema.String, html_url: Schema.String, ssh_url: Schema.String })), ); @@ -280,7 +295,12 @@ const make = Effect.gen(function* () { return { nameWithOwner: found.full_name, url: found.html_url, sshUrl: found.ssh_url }; }); - return Service.of({ info, browse, add, create, status, lookup }); + const remote = Effect.fn("Host.remote")(function* (directory: string) { + const url = yield* git.remote(directory); + return url === undefined ? undefined : shownRemote(url); + }); + + return Service.of({ info, browse, add, create, status, lookup, remote }); }); // Git runs on the host; every call names its own directory, so the mount root is never read. diff --git a/packages/codework/test/__artifacts__/server.project-name.json b/packages/codework/test/__artifacts__/server.project-name.json index e9adfa52..58996afb 100644 --- a/packages/codework/test/__artifacts__/server.project-name.json +++ b/packages/codework/test/__artifacts__/server.project-name.json @@ -42,5 +42,12 @@ "rename": "rejected" } }, - "sessionsCreatedByInvalid": 0 + "sessionsCreatedByInvalid": 0, + "remote": { + "repo": "https://github.com/org/named-upstream", + "tokened": "https://github.com/org/tokened", + "folder": null, + "memory": null, + "missing": "ProjectNotFoundError" + } } diff --git a/packages/codework/test/server.test.ts b/packages/codework/test/server.test.ts index 6d96ac7a..69427d09 100644 --- a/packages/codework/test/server.test.ts +++ b/packages/codework/test/server.test.ts @@ -500,6 +500,26 @@ describe("server", () => { const after = (yield* rpc["thread.list"]({})).length; expect(after).toBe(before); + // 7. The origin URL of the main checkout on the host: credentials never leave the server. + const tokened = yield* Effect.promise(async () => { + const path = await repo(dir("tokened"), "tokened"); + await git(path, "remote", "set-url", "origin", "https://x-access-token:secret@github.com/org/tokened"); + return path; + }); + const tokenedSession = yield* rpc["session.create"]({ directory: tokened }); + const remoteOf = (sessionId: Session.SessionSchema.ID) => + projectOf(sessionId).pipe( + Effect.flatMap((project) => rpc["project.remote"]({ projectId: project?.id ?? "" })), + Effect.map(({ url }) => url), + ); + const remote = { + repo: yield* remoteOf(repoNamed.session.id), + tokened: yield* remoteOf(tokenedSession.session.id), + folder: yield* remoteOf(folderNamed.session.id), + memory: yield* remoteOf(memoryNamed.session.id), + missing: (yield* rpc["project.remote"]({ projectId: "prj_missing" }).pipe(Effect.flip))._tag, + }; + const artifact = { memory: { named: yield* nameOf(memoryNamed.session.id), unnamed: yield* nameOf(memoryUnnamed.session.id) }, folder: { named: yield* nameOf(folderNamed.session.id), unnamed: yield* nameOf(folderUnnamed.session.id) }, @@ -517,6 +537,7 @@ describe("server", () => { }, invalid, sessionsCreatedByInvalid: after - before, + remote, }; expect(artifact.memory).toEqual({ named: "In Memory", unnamed: "" }); expect(artifact.folder).toEqual({ named: "Plain", unnamed: "plain-unnamed" }); @@ -525,6 +546,13 @@ describe("server", () => { expect(artifact.rename).toMatchObject({ first: "C", second: "C", result: { sameId: true, name: "C" } }); for (const outcome of Object.values(invalid)) expect(outcome).toEqual({ create: "rejected", rename: "rejected" }); + expect(artifact.remote).toEqual({ + repo: "https://github.com/org/named-upstream", + tokened: "https://github.com/org/tokened", + folder: null, + memory: null, + missing: "ProjectNotFoundError", + }); return artifact; }) .pipe(Effect.scoped, Effect.provide(layer()), Effect.runPromise) diff --git a/packages/harness/src/project/project.ts b/packages/harness/src/project/project.ts index 689a7b76..0b36417b 100644 --- a/packages/harness/src/project/project.ts +++ b/packages/harness/src/project/project.ts @@ -260,6 +260,21 @@ export const rename = Effect.fn("Project.rename")(function* (input: { }); }); +/** + * A project's main checkout on the host, if it has an active one. Needs only the database; a + * checkout inside a sandbox has no host path to run git in. + */ +export const mainCheckout = Effect.fn("Project.mainCheckout")(function* (projectId: string) { + const sql = yield* SqlClient.SqlClient; + const found = yield* sql<{ id: string }>`SELECT id FROM project WHERE id = ${projectId}`.pipe(Effect.orDie); + if (found.length === 0) return yield* new ProjectNotFoundError({ projectId }); + const rows = yield* sql<{ location: string }>` + SELECT location FROM space + WHERE project_id = ${projectId} AND env IS NULL AND kind = 'primary' AND status = 'active' + `.pipe(Effect.orDie); + return rows[0]?.location; +}); + /** Takes an assembled sandbox — local or remote — not a local backend. */ export const layerWith = (sandbox: Sandbox.Sandbox) => layer.pipe( From 8b3d7b3ac950a2c943bb37f54e9083d9dc3d95c9 Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Wed, 11 Nov 2026 13:35:04 +0530 Subject: [PATCH 5/9] feat(codework): read and edit settings files over RPC settings.read, settings.write and settings.set edit a project's or the user's settings.jsonc and mcp.json. Writes keep comments and formatting, run under the settings lock, and are refused when the runtime would reject the result; a whole-file write is also refused when the file changed since it was read. settings.read returns the parsed file and, for settings.jsonc, what applies where the file sets nothing. The CLI's settings edits now share the same harness module. Writes no longer leave an empty temp directory beside the file, and removals are formatted. A project that is not a repository now has a main checkout too. Co-Authored-By: Claude Opus 5.5 --- packages/codework/src/cli/error.ts | 2 + packages/codework/src/cli/jsonc.ts | 60 ++------ packages/codework/src/server/contract.ts | 54 +++++++ packages/codework/src/server/handlers.ts | 40 +++++ .../test/__artifacts__/server.settings.json | 82 ++++++++++ packages/codework/test/server.test.ts | 143 +++++++++++++++++ packages/harness/src/effect.ts | 1 + packages/harness/src/mcp/config.ts | 28 +++- packages/harness/src/project/project.ts | 10 +- packages/harness/src/settings/file.ts | 144 ++++++++++++++++++ packages/harness/src/settings/settings.ts | 43 +++++- packages/harness/test/runner.loop.test.ts | 1 + packages/harness/test/store.test.ts | 7 +- packages/harness/test/thread.test.ts | 7 +- .../harness/test/tools.toolsearch.test.ts | 7 +- 15 files changed, 570 insertions(+), 59 deletions(-) create mode 100644 packages/codework/test/__artifacts__/server.settings.json create mode 100644 packages/harness/src/settings/file.ts diff --git a/packages/codework/src/cli/error.ts b/packages/codework/src/cli/error.ts index eceb0e13..283d4bbc 100644 --- a/packages/codework/src/cli/error.ts +++ b/packages/codework/src/cli/error.ts @@ -187,6 +187,8 @@ const settingsHint = (reason: Settings.SettingsError["reason"]): string => { switch (reason) { case "read": return "the file exists but could not be read; check that it is a file and readable"; + case "write": + return "the file could not be written; check that its directory is writable"; case "parse": return "the file is not valid JSON; the location above is where parsing stopped"; case "decode": diff --git a/packages/codework/src/cli/jsonc.ts b/packages/codework/src/cli/jsonc.ts index 53ae25fe..ce67d791 100644 --- a/packages/codework/src/cli/jsonc.ts +++ b/packages/codework/src/cli/jsonc.ts @@ -1,15 +1,12 @@ -import { Plugin } from "@codeworksh/harness/effect"; -import { Effect, FileSystem, Path } from "effect"; -import { applyEdits, modify, parse as parseJsonc, type ParseError } from "jsonc-parser"; +import { SettingsFile } from "@codeworksh/harness/effect"; +import { Effect, FileSystem } from "effect"; +import { parse as parseJsonc, type ParseError } from "jsonc-parser"; import { InvalidInputError } from "./error.ts"; /** * Reading and rewriting one value of a JSONC file the CLI edits for its owner: `settings.jsonc`, - * `mcp.json`. - * - * Edits go through `jsonc-parser`, so a hand-written file keeps its comments, key order and - * formatting. The write is a temp file renamed over the original, so an interrupted run leaves the - * previous file intact rather than a half-written document. + * `mcp.json`. The edit and the write are the harness's {@link SettingsFile}, shared with the app + * server. */ /** The file's text and its top-level object; a missing file reads as `{}`. */ @@ -25,51 +22,14 @@ export const read = Effect.fn("CLI.jsonc.read")(function* (path: string, what: s }); /** Set the value at `at` in `source`, or remove it when `value` is undefined, and write the file. */ -export const write = Effect.fn("CLI.jsonc.write")(function* ( - path: string, - source: string, - at: ReadonlyArray, - value: unknown, -) { - const fs = yield* FileSystem.FileSystem; - const nodePath = yield* Path.Path; - // A removal is not formatted: the formatter would reflow the sibling before it as well. - const edited = applyEdits( - source, - modify( - source, - [...at], - value, - value === undefined ? {} : { formattingOptions: { tabSize: 2, insertSpaces: false } }, - ), - ); - const directory = nodePath.dirname(path); - yield* fs.makeDirectory(directory, { recursive: true }); - const mode = (yield* fs.exists(path)) ? (yield* fs.stat(path)).mode & 0o777 : 0o600; - const temporary = yield* fs.makeTempFile({ directory, prefix: `.${nodePath.basename(path)}.`, suffix: ".tmp" }); - yield* fs - .writeFileString(temporary, edited.endsWith("\n") ? edited : `${edited}\n`) - .pipe( - Effect.andThen(fs.chmod(temporary, mode)), - Effect.andThen(fs.rename(temporary, path)), - Effect.ensuring(fs.remove(temporary, { force: true }).pipe(Effect.ignore)), - ); -}); +export const write = (path: string, source: string, at: ReadonlyArray, value: unknown) => + SettingsFile.save(path, SettingsFile.edit(source, at, value)); /** - * Serialize one read-modify-rename of `path` across CLI processes. Only the local edit is locked, so - * work that precedes it does not wait behind another process. + * Serialize one read-modify-rename of `path` across CLI processes and the app server. Only the local + * edit is locked, so work that precedes it does not wait behind another process. */ export const locked = (path: string, edit: Effect.Effect) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const nodePath = yield* Path.Path; - yield* fs.makeDirectory(nodePath.dirname(path), { recursive: true }); - yield* Plugin.settingsLock( - `${path}.lock`, - () => new InvalidInputError({ message: `timed out waiting to edit ${path}` }), - ); - return yield* edit; - }).pipe(Effect.scoped); + SettingsFile.locked(path, () => new InvalidInputError({ message: `timed out waiting to edit ${path}` }), edit); export * as Jsonc from "./jsonc.ts"; diff --git a/packages/codework/src/server/contract.ts b/packages/codework/src/server/contract.ts index 3078147d..9ab75873 100644 --- a/packages/codework/src/server/contract.ts +++ b/packages/codework/src/server/contract.ts @@ -14,6 +14,7 @@ import { Session, SessionStore, Settings, + SettingsFile, ThreadSchema, ThreadStore, } from "@codeworksh/harness/effect"; @@ -413,6 +414,17 @@ export type McpStatus = typeof McpStatus.Type; const McpErrors = Schema.Union([ThreadErrors, McpError.UnknownServerError]); +const SettingsFileRef = { projectId: optional(Schema.String), file: Schema.Literals(["settings", "mcp"]) }; +/** The settings a project's `settings.jsonc` falls back to, as the page shows them. */ +const Inherited = Schema.Struct({ + retry: Schema.Struct({ maxRetries: Schema.Int, baseDelayMs: Schema.Int, maxDelayMs: Schema.Int }), +}); +const SettingsFileErrors = Schema.Union([ + Settings.SettingsError, + Project.ProjectNotFoundError, + Project.ProjectCheckoutError, +]); + export const Api = RpcGroup.make( /** * The server's own identity: the process and build a client is talking to. @@ -504,6 +516,48 @@ export const Api = RpcGroup.make( success: Schema.Struct({ id: Schema.String, name: Schema.String }), error: Project.ProjectNotFoundError, }), + /** + * A settings file as written: the project's when `projectId` is given -- the one sessions in its + * main checkout read -- otherwise the user's. `version` is what `settings.write` is held to; + * `error` is what the runtime would reject in the file as it stands. + */ + Rpc.make("settings.read", { + payload: SettingsFileRef, + success: Schema.Struct({ + path: Schema.String, + source: Schema.String, + exists: Schema.Boolean, + version: Schema.String, + /** The file's JSONC as a value; absent when it does not parse. */ + value: optional(Schema.Unknown), + error: optional(Schema.String), + /** + * For `settings.jsonc`: what applies where this file sets nothing -- the user's settings over the + * defaults for a project's file, the defaults for the user's. Absent when a lower file is broken. + */ + inherited: optional(Inherited), + }), + error: SettingsFileErrors, + }), + /** The whole file, written only when it is still at `version` and the runtime would accept it. */ + Rpc.make("settings.write", { + payload: { ...SettingsFileRef, source: Schema.String, version: Schema.String }, + success: Schema.Struct({ version: Schema.String }), + error: Schema.Union([SettingsFileErrors, SettingsFile.SettingsConflictError]), + }), + /** + * One value at `at` set in place, keeping the rest of the file as written; no `value` removes it. + * Refused when the result would not be accepted. + */ + Rpc.make("settings.set", { + payload: { + ...SettingsFileRef, + at: Schema.NonEmptyArray(Schema.Union([Schema.String, Schema.Int])), + value: optional(Schema.Unknown), + }, + success: Schema.Struct({ version: Schema.String }), + error: SettingsFileErrors, + }), /** * The models a session anchored at `hostDir` can use: providers this server holds credentials * for, in the catalog plus that project's settings, and the model settings pick when a session diff --git a/packages/codework/src/server/handlers.ts b/packages/codework/src/server/handlers.ts index abaee83c..de609980 100644 --- a/packages/codework/src/server/handlers.ts +++ b/packages/codework/src/server/handlers.ts @@ -13,6 +13,7 @@ import { Session, SessionStore, Settings, + SettingsFile, State, Store, Sync, @@ -235,6 +236,15 @@ export const layer = Contract.Api.toLayer( return yield* mcp[operation](yield* resolve(ref), server); }); + const settings = yield* Settings.Service; + /** The project's file is the one sessions in its main checkout read. */ + const settingsTarget = Effect.fnUntraced(function* (projectId: string | undefined, file: "settings" | "mcp") { + if (projectId === undefined) return yield* settings.locate(undefined, file); + const checkout = yield* Project.mainCheckout(projectId); + if (checkout === undefined) return yield* new Project.ProjectCheckoutError({ projectId }); + return yield* settings.locate(checkout, file); + }); + return Contract.Api.of({ "server.info": Effect.fnUntraced(function* () { const head = yield* store.head; @@ -317,6 +327,36 @@ export const layer = Contract.Api.toLayer( const renamed = yield* Project.rename({ projectId, name }); return { id: renamed.id, name: renamed.name }; }), + "settings.read": Effect.fnUntraced(function* ({ projectId, file }) { + const target = yield* settingsTarget(projectId, file); + const current = yield* SettingsFile.read(target.path); + const problem = yield* Effect.flip(SettingsFile.check(target, current.source)).pipe(Effect.option); + const parsed = SettingsFile.parse(current.source); + // Below a project's file are the user's settings; below the user's, the defaults. + const below = + file !== "settings" + ? Option.none() + : projectId === undefined + ? Option.some(Settings.defaults) + : yield* settings.load(undefined).pipe(Effect.option); + return { + path: target.path, + source: current.source, + exists: current.exists, + version: current.version, + ...("value" in parsed ? { value: parsed.value } : {}), + ...(Option.isSome(problem) ? { error: problem.value.detail } : {}), + ...(Option.isSome(below) ? { inherited: { retry: below.value.retry } } : {}), + }; + }), + "settings.write": Effect.fnUntraced(function* ({ projectId, file, source, version }) { + const target = yield* settingsTarget(projectId, file); + return { version: yield* SettingsFile.replace(target, source, version) }; + }), + "settings.set": Effect.fnUntraced(function* ({ projectId, file, at, value }) { + const target = yield* settingsTarget(projectId, file); + return { version: yield* SettingsFile.set(target, at, value) }; + }), "plugin.reload": Effect.fnUntraced(function* () { return yield* state.reload; }), diff --git a/packages/codework/test/__artifacts__/server.settings.json b/packages/codework/test/__artifacts__/server.settings.json new file mode 100644 index 00000000..98823726 --- /dev/null +++ b/packages/codework/test/__artifacts__/server.settings.json @@ -0,0 +1,82 @@ +{ + "empty": { + "path": "/app/.codework/settings.jsonc", + "source": "", + "exists": false, + "inherited": { + "retry": { + "maxRetries": 3, + "baseDelayMs": 2000, + "maxDelayMs": 60000 + } + } + }, + "afterWrite": "// Team defaults.\n{\n\t\"model\": { \"provider\": \"anthropic\", \"id\": \"claude-sonnet-5\" }, // pinned\n}\n", + "afterSet": "// Team defaults.\n{\n\t\"model\": {\n\t\t\"provider\": \"anthropic\",\n\t\t\"id\": \"claude-sonnet-5\"\n\t},\n\t\"retry\": {\n\t\t\"maxRetries\": 5\n\t}, // pinned\n}\n", + "afterRemove": "// Team defaults.\n{\n\t\"model\": {\n\t\t\"provider\": \"anthropic\",\n\t\t\"id\": \"claude-sonnet-5\"\n\t}, // pinned\n}\n", + "default": { + "provider": "anthropic", + "id": "claude-sonnet-5", + "thinkingLevel": "medium", + "name": "Claude Sonnet 5", + "providerName": "Anthropic" + }, + "refusals": { + "stale": { + "_tag": "SettingsConflictError", + "message": "/app/.codework/settings.jsonc changed since it was read" + }, + "invalidWrite": { + "_tag": "SettingsError", + "message": "/app/.codework/settings.jsonc: parse: InvalidSymbol at 1:3" + }, + "invalidSet": { + "_tag": "SettingsError", + "message": "/app/.codework/settings.jsonc: decode: retry.maxRetries: Expected a value greater than or equal to 0" + }, + "unchanged": true + }, + "broken": { + "error": "retry.maxRetries: Expected number | undefined", + "fixed": true + }, + "mcp": { + "user": { + "path": "/mcp.json", + "file": "{\n\t\"mcpServers\": {\n\t\t\"echo\": {\n\t\t\t\"command\": \"node\",\n\t\t\t\"args\": [\n\t\t\t\t\"echo.mjs\"\n\t\t\t]\n\t\t}\n\t}\n}\n" + }, + "project": { + "path": "/app/.codework/mcp.json", + "source": "{\n\t\"mcpServers\": {\n\t\t\"echo\": {\n\t\t\t\"enabled\": false\n\t\t}\n\t}\n}\n", + "error": null + }, + "orphan": { + "_tag": "SettingsError", + "message": "/app/.codework/mcp.json: decode: server \"ghost\" needs \"command\" or \"url\", or a user server to override" + }, + "borrowed": { + "_tag": "SettingsError", + "message": "/app/.codework/mcp.json: decode: server \"remote\": auth is only allowed in the user mcp.json" + } + }, + "user": { + "path": "/settings.jsonc", + "exists": false, + "inherited": { + "retry": { + "maxRetries": 3, + "baseDelayMs": 2000, + "maxDelayMs": 60000 + } + } + }, + "inheritedByMcp": null, + "missing": { + "_tag": "ProjectNotFoundError", + "message": "" + }, + "noCheckout": { + "_tag": "ProjectCheckoutError", + "message": "" + } +} diff --git a/packages/codework/test/server.test.ts b/packages/codework/test/server.test.ts index 69427d09..04059df2 100644 --- a/packages/codework/test/server.test.ts +++ b/packages/codework/test/server.test.ts @@ -657,6 +657,149 @@ describe("server", () => { ); }); + it("settings.read, settings.write and settings.set edit a project's and the user's files", () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "codework-server-settings-"))); + homes.push(root); + const app = join(root, "app"); + mkdirSync(app); + const fileOf = (path: string) => readFileSync(path, "utf8"); + + return Effect.gen(function* () { + const rpc = yield* RpcTest.makeClient(Contract.Api); + const created = yield* rpc["session.create"]({ directory: app }); + const projectId = created.session.project?.id ?? ""; + const memory = yield* rpc["session.create"]({ sandbox: { driver: "memory" } }); + const failure = ( + effect: Effect.Effect, + ) => + effect.pipe( + Effect.flip, + Effect.map((error) => ({ _tag: error._tag, message: error.message })), + ); + + // 1. A project with no `.codework/` yet: its file is named, empty, and absent. + const empty = yield* rpc["settings.read"]({ projectId, file: "settings" }); + + // 2. The editor's whole-file save keeps the text as written, comments included. + const written = `// Team defaults.\n{\n\t"model": { "provider": "anthropic", "id": "claude-sonnet-5" }, // pinned\n}\n`; + const saved = yield* rpc["settings.write"]({ + projectId, + file: "settings", + source: written, + version: empty.version, + }); + const afterWrite = fileOf(empty.path); + + // 3. One value set in place: the comments and the other keys stay. + yield* rpc["settings.set"]({ projectId, file: "settings", at: ["retry", "maxRetries"], value: 5 }); + const afterSet = fileOf(empty.path); + const removed = yield* rpc["settings.set"]({ projectId, file: "settings", at: ["retry"] }); + const afterRemove = fileOf(empty.path); + + // 4. Sessions in the project read the result. + const models = yield* rpc["model.list"]({ hostDir: Session.AbsolutePath.make(app) }); + + // 5. Refusals leave the file alone: a stale version, and values the runtime would reject. + const stale = yield* failure( + rpc["settings.write"]({ projectId, file: "settings", source: "{}", version: saved.version }), + ); + const invalidWrite = yield* failure( + rpc["settings.write"]({ projectId, file: "settings", source: "{ not json", version: removed.version }), + ); + const invalidSet = yield* failure( + rpc["settings.set"]({ projectId, file: "settings", at: ["retry", "maxRetries"], value: -1 }), + ); + const afterRefusals = fileOf(empty.path); + + // 6. A broken file is read with what is wrong, so the editor can show it and fix it. + writeFileSync(empty.path, `{ "retry": { "maxRetries": "many" } }\n`); + const broken = yield* rpc["settings.read"]({ projectId, file: "settings" }); + const fixed = yield* rpc["settings.write"]({ + projectId, + file: "settings", + source: afterRemove, + version: broken.version, + }); + + // 7. mcp.json: a user server, turned off in the project by an override. + const userMcp = yield* rpc["settings.read"]({ file: "mcp" }); + yield* rpc["settings.set"]({ + file: "mcp", + at: ["mcpServers", "echo"], + value: { command: "node", args: ["echo.mjs"] }, + }); + yield* rpc["settings.set"]({ projectId, file: "mcp", at: ["mcpServers", "echo", "enabled"], value: false }); + const projectMcp = yield* rpc["settings.read"]({ projectId, file: "mcp" }); + const orphan = yield* failure( + rpc["settings.set"]({ projectId, file: "mcp", at: ["mcpServers", "ghost", "enabled"], value: false }), + ); + const borrowed = yield* failure( + rpc["settings.set"]({ + projectId, + file: "mcp", + at: ["mcpServers", "remote"], + value: { url: "https://mcp.example.com", auth: { provider: "anthropic" } }, + }), + ); + + // 8. The user's settings file, and projects without a file of their own. + const userSettings = yield* rpc["settings.read"]({ file: "settings" }); + const missing = yield* failure(rpc["settings.read"]({ projectId: "prj_missing", file: "settings" })); + const noCheckout = yield* failure( + rpc["settings.read"]({ projectId: memory.session.project?.id ?? "", file: "settings" }), + ); + + const home = join(userSettings.path, ".."); + const normal = (value: unknown): unknown => + JSON.parse(JSON.stringify(value).replaceAll(root, "").replaceAll(home, "")); + const artifact = normal({ + empty: { path: empty.path, source: empty.source, exists: empty.exists, inherited: empty.inherited }, + afterWrite, + afterSet, + afterRemove, + default: models.default, + refusals: { stale, invalidWrite, invalidSet, unchanged: afterRefusals === afterRemove }, + broken: { error: broken.error, fixed: fixed.version === removed.version }, + mcp: { + user: { path: userMcp.path, file: fileOf(userMcp.path) }, + project: { path: projectMcp.path, source: projectMcp.source, error: projectMcp.error ?? null }, + orphan, + borrowed, + }, + user: { path: userSettings.path, exists: userSettings.exists, inherited: userSettings.inherited }, + inheritedByMcp: projectMcp.inherited ?? null, + missing, + noCheckout, + }); + expect(empty).toMatchObject({ path: join(app, ".codework", "settings.jsonc"), source: "", exists: false }); + // The project's file falls back to the user's settings over the defaults. + expect(empty.inherited?.retry.maxRetries).toBe(3); + expect(projectMcp.inherited).toBeUndefined(); + expect(afterWrite).toBe(written); + expect(afterSet).toContain("// pinned"); + expect(afterSet).toContain('"maxRetries": 5'); + expect(afterRemove).not.toContain("retry"); + expect(models.default).toMatchObject({ provider: "anthropic", id: "claude-sonnet-5" }); + expect(stale._tag).toBe("SettingsConflictError"); + expect(invalidWrite._tag).toBe("SettingsError"); + expect(invalidSet._tag).toBe("SettingsError"); + expect(afterRefusals).toBe(afterRemove); + expect(broken.error).toContain("retry.maxRetries"); + expect(projectMcp.error).toBeUndefined(); + expect(orphan._tag).toBe("SettingsError"); + expect(borrowed._tag).toBe("SettingsError"); + expect(missing._tag).toBe("ProjectNotFoundError"); + expect(noCheckout._tag).toBe("ProjectCheckoutError"); + return artifact; + }) + .pipe(Effect.scoped, Effect.provide(layer()), Effect.runPromise) + .then((artifact) => + expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot( + "./__artifacts__/server.settings.json", + ), + ); + }); + it("thread.message reports an unknown prompt as absent", () => Effect.gen(function* () { const rpc = yield* RpcTest.makeClient(Contract.Api); diff --git a/packages/harness/src/effect.ts b/packages/harness/src/effect.ts index 8a59f60b..6e059124 100644 --- a/packages/harness/src/effect.ts +++ b/packages/harness/src/effect.ts @@ -30,6 +30,7 @@ export * as Tool from "./tool/tool.ts"; export { Global } from "./global.ts"; export { expandTilde } from "./util/home.ts"; export { Settings } from "./settings/settings.ts"; +export { SettingsFile } from "./settings/file.ts"; export { State } from "./state/state.ts"; export * as Plugin from "./plugin/index.ts"; diff --git a/packages/harness/src/mcp/config.ts b/packages/harness/src/mcp/config.ts index f933a3f2..d180cd2a 100644 --- a/packages/harness/src/mcp/config.ts +++ b/packages/harness/src/mcp/config.ts @@ -155,7 +155,11 @@ const read = Effect.fnUntraced(function* (path: string, scope: "user" | "project if (reason !== "NotFound") state.errors.push(`${path}: cannot be read: ${reason}`); return; } - const document = Jsonc.parse(source.success); + apply(path, source.success, scope, state); +}); + +const apply = (path: string, source: string, scope: "user" | "project", state: State) => { + const document = Jsonc.parse(source); if ("error" in document) { state.errors.push(`${path}: ${document.error}`); return; @@ -197,7 +201,7 @@ const read = Effect.fnUntraced(function* (path: string, scope: "user" | "project } servers.set(name, { name, config, file: path }); } -}); +}; /** * Both layers. `userDir` is where the user `settings.jsonc` is read from; `root` is the session's @@ -214,4 +218,24 @@ export const load = Effect.fn("Mcp.loadConfig")(function* (input: { return { servers: [...state.servers.values()], errors: state.errors } satisfies McpSettings; }); +/** + * What is wrong with `source` as the `mcp.json` at `path`, read the way {@link load} would read it: + * a project file over the user one in `userDir`, so an override is checked against the server it + * overrides. Problems in the user file itself are not this file's. + */ +export const check = Effect.fn("Mcp.checkConfig")(function* (input: { + readonly path: string; + readonly source: string; + readonly scope: "user" | "project"; + readonly userDir: string; +}) { + const state: State = { servers: new Map(), errors: [] }; + if (input.scope === "project") { + yield* read(hostPath.join(input.userDir, "mcp.json"), "user", state); + state.errors.length = 0; + } + apply(input.path, input.source, input.scope, state); + return state.errors as ReadonlyArray; +}); + export * as McpConfig from "./config.ts"; diff --git a/packages/harness/src/project/project.ts b/packages/harness/src/project/project.ts index 0b36417b..5e752102 100644 --- a/packages/harness/src/project/project.ts +++ b/packages/harness/src/project/project.ts @@ -235,6 +235,11 @@ export class ProjectNotFoundError extends Schema.TaggedError()("ProjectCheckoutError", { + projectId: Schema.String, +}) {} + /** Renames a project. Needs only the database, not a mount: a name is the same in every env. */ export const rename = Effect.fn("Project.rename")(function* (input: { readonly projectId: string; @@ -261,7 +266,8 @@ export const rename = Effect.fn("Project.rename")(function* (input: { }); /** - * A project's main checkout on the host, if it has an active one. Needs only the database; a + * A project's main checkout on the host, if it has an active one: its repository's main worktree, + * or the folder of a project that is not a repository. Needs only the database; a * checkout inside a sandbox has no host path to run git in. */ export const mainCheckout = Effect.fn("Project.mainCheckout")(function* (projectId: string) { @@ -270,7 +276,7 @@ export const mainCheckout = Effect.fn("Project.mainCheckout")(function* (project if (found.length === 0) return yield* new ProjectNotFoundError({ projectId }); const rows = yield* sql<{ location: string }>` SELECT location FROM space - WHERE project_id = ${projectId} AND env IS NULL AND kind = 'primary' AND status = 'active' + WHERE project_id = ${projectId} AND env IS NULL AND kind IN ('primary', 'plain') AND status = 'active' `.pipe(Effect.orDie); return rows[0]?.location; }); diff --git a/packages/harness/src/settings/file.ts b/packages/harness/src/settings/file.ts new file mode 100644 index 00000000..eb801071 --- /dev/null +++ b/packages/harness/src/settings/file.ts @@ -0,0 +1,144 @@ +/* + * @file Reading and editing one settings file -- `settings.jsonc` or `mcp.json` -- for the CLI and + * the app server. + * + * Edits go through `jsonc-parser`, so a hand-written file keeps its comments, key order and + * formatting. A write is a temp file renamed over the original under the settings lock, so an + * interrupted run leaves the previous file intact and two writers never interleave. + * + * `replace` and `set` refuse to write a file the runtime would reject: an invalid `settings.jsonc` + * fails every turn in its project, so the check has to happen before the write, not at the next + * turn. + */ + +import { Effect, Schema } from "effect"; +import { applyEdits, modify } from "jsonc-parser"; +import { fileSystem, hostPath } from "../host.ts"; +import { McpConfig } from "../mcp/config.ts"; +import { lock } from "../plugin/lock.ts"; +import { Hash } from "../util/hash.ts"; +import * as Jsonc from "../util/jsonc.ts"; +import { parse as decode, SettingsError, type Target } from "./settings.ts"; + +/** The file changed since the caller read it. */ +export class SettingsConflictError extends Schema.TaggedError()("SettingsConflictError", { + path: Schema.String, +}) { + override get message(): string { + return `${this.path} changed since it was read`; + } +} + +/** What a caller holds to write back: a missing file reads as empty. */ +export const version = (source: string) => Hash.sha256(source); + +export const read = Effect.fn("SettingsFile.read")(function* (path: string) { + const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false)); + const source = exists + ? yield* fileSystem + .readFileString(path) + .pipe(Effect.mapError((error) => new SettingsError({ path, reason: "read", detail: error.reason._tag }))) + : ""; + return { source, exists, version: version(source) }; +}); + +/** The file's JSONC as a value, an empty file as `{}`; or why it does not parse. */ +export const parse = (source: string) => Jsonc.parse(source.trim() === "" ? "{}" : source); + +/** Fails with what the runtime would reject in `source` as `target`'s file. */ +export const check = Effect.fn("SettingsFile.check")(function* (target: Target, source: string) { + // An empty file is no settings at all, not a syntax error. + const text = source.trim() === "" ? "{}" : source; + if (target.kind === "settings") return yield* Effect.asVoid(decode(target.path, text)); + const errors = yield* McpConfig.check({ + path: target.path, + source: text, + scope: target.scope, + userDir: target.userDir, + }); + if (errors.length > 0) + return yield* new SettingsError({ + path: target.path, + reason: "decode", + detail: errors.map((error) => error.replace(`${target.path}: `, "")).join("; "), + }); +}); + +/** `source` with the value at `at` set, or removed when `value` is undefined. */ +export const edit = (source: string, at: ReadonlyArray, value: unknown) => + // A removal is formatted too: unformatted, removing a first key leaves `{"next": {` on one line. + applyEdits(source, modify(source, [...at], value, { formattingOptions: { tabSize: 2, insertSpaces: false } })); + +/** + * Write `text` over `path`, keeping its mode; a new file is private to its owner. Callers hold the + * settings lock, so one fixed temp name beside the file is enough -- `makeTempFile` would leave a + * directory behind for every write. + */ +export const save = Effect.fn("SettingsFile.save")(function* (path: string, text: string) { + const directory = hostPath.dirname(path); + yield* fileSystem.makeDirectory(directory, { recursive: true }); + const mode = (yield* fileSystem.exists(path)) ? (yield* fileSystem.stat(path)).mode & 0o777 : 0o600; + const temporary = hostPath.join(directory, `.${hostPath.basename(path)}.tmp`); + yield* fileSystem + .writeFileString(temporary, text.endsWith("\n") ? text : `${text}\n`) + .pipe( + Effect.andThen(fileSystem.chmod(temporary, mode)), + Effect.andThen(fileSystem.rename(temporary, path)), + Effect.ensuring(fileSystem.remove(temporary, { force: true }).pipe(Effect.ignore)), + ); +}); + +/** Run one read-modify-write of `path` under the settings lock, across processes. */ +export const locked = (path: string, onTimeout: () => T, change: Effect.Effect) => + lock(`${path}.lock`, onTimeout).pipe(Effect.andThen(change), Effect.scoped); + +const timeout = (path: string) => () => + new SettingsError({ path, reason: "write", detail: "timed out waiting to edit" }); + +/** {@link locked}, failing as the file's own write error. */ +const exclusive = (path: string, change: Effect.Effect) => + lock(`${path}.lock`, timeout(path)).pipe( + Effect.catchTag("LockError", (error) => + Effect.fail(new SettingsError({ path, reason: "write", detail: error.message })), + ), + Effect.andThen(change), + Effect.scoped, + ); + +const written = (path: string, text: string) => + save(path, text).pipe( + Effect.mapError((error) => new SettingsError({ path, reason: "write", detail: error.message })), + Effect.as(version(text.endsWith("\n") ? text : `${text}\n`)), + ); + +/** The whole file, as the editor holds it: written only when the file is still at `expected`. */ +export const replace = Effect.fn("SettingsFile.replace")(function* (target: Target, source: string, expected: string) { + return yield* exclusive( + target.path, + Effect.gen(function* () { + const current = yield* read(target.path); + if (current.version !== expected) return yield* new SettingsConflictError({ path: target.path }); + yield* check(target, source); + return yield* written(target.path, source); + }), + ); +}); + +/** One value, applied in place over whatever the file holds now. */ +export const set = Effect.fn("SettingsFile.set")(function* ( + target: Target, + at: ReadonlyArray, + value: unknown, +) { + return yield* exclusive( + target.path, + Effect.gen(function* () { + const current = yield* read(target.path); + const text = edit(current.source.trim() === "" ? "{}" : current.source, at, value); + yield* check(target, text); + return yield* written(target.path, text); + }), + ); +}); + +export * as SettingsFile from "./file.ts"; diff --git a/packages/harness/src/settings/settings.ts b/packages/harness/src/settings/settings.ts index eaf372ed..c50fa937 100644 --- a/packages/harness/src/settings/settings.ts +++ b/packages/harness/src/settings/settings.ts @@ -37,7 +37,7 @@ * is a log line. Failing is what gets it fixed. */ -import { Context, Effect, Layer, Predicate, Result, Schema, SchemaIssue } from "effect"; +import { Context, Effect, Layer, Option, Predicate, Result, Schema, SchemaIssue } from "effect"; import { Global } from "../global.ts"; import { McpConfig } from "../mcp/config.ts"; import { fileSystem, hostPath } from "../host.ts"; @@ -150,9 +150,44 @@ export function paths(input: { ]; } +/** One settings file a person edits: `settings.jsonc` or `mcp.json`, in the user or the project layer. */ +export interface Target { + readonly path: string; + readonly kind: "settings" | "mcp"; + readonly scope: "user" | "project"; + /** The user layer's directory, which a project `mcp.json` is checked against. */ + readonly userDir: string; +} + +/** + * The file an edit lands in: the one a session at `hostDir` reads, or the user layer's without + * `hostDir`. A directory in no project becomes one, at `hostDir`, when the file is written. + * An existing `settings.json` is kept over creating `settings.jsonc` beside it. + */ +export const locate = Effect.fn("Settings.locate")(function* (input: { + readonly home: string; + readonly userConfigDir?: string | undefined; + readonly hostDir?: string | undefined; + readonly kind: Target["kind"]; +}) { + const userDir = input.userConfigDir ?? input.home; + const directory = + input.hostDir === undefined + ? userDir + : hostPath.join((yield* projectRoot(input.hostDir, input.home)) ?? input.hostDir, Global.appConfigDir); + const scope: Target["scope"] = input.hostDir === undefined ? "user" : "project"; + if (input.kind === "mcp") + return { path: hostPath.join(directory, "mcp.json"), kind: input.kind, scope, userDir } satisfies Target; + const candidates = settingsIn(directory); + const existing = yield* Effect.findFirst(candidates, (path) => + fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false)), + ); + return { path: Option.getOrElse(existing, () => candidates[0]!), kind: input.kind, scope, userDir } satisfies Target; +}); + export class SettingsError extends Schema.TaggedError()("SettingsError", { path: Schema.String, - reason: Schema.Literals(["read", "parse", "decode"]), + reason: Schema.Literals(["read", "write", "parse", "decode"]), detail: Schema.String, }) { override get message(): string { @@ -212,6 +247,8 @@ export interface Interface { * session that was never given one -- the user layer alone, with no walk (see {@link Options}). */ readonly load: (hostDir: string | undefined) => Effect.Effect; + /** The file {@link locate} names for this app's home and `--user-config-dir`. */ + readonly locate: (hostDir: string | undefined, kind: Target["kind"]) => Effect.Effect; } export class Service extends Context.Service()("@codeworksh/harness/settings/settings/Service") {} @@ -324,6 +361,8 @@ export const layer = (options: Omit = {}) => const global = yield* Global.Service; return Service.of({ load: (hostDir) => load({ ...options, home: global.home, hostDir }), + locate: (hostDir, kind) => + locate({ home: global.home, userConfigDir: options.userConfigDir, hostDir, kind }), }); }), ); diff --git a/packages/harness/test/runner.loop.test.ts b/packages/harness/test/runner.loop.test.ts index 624fdae3..3e2589d6 100644 --- a/packages/harness/test/runner.loop.test.ts +++ b/packages/harness/test/runner.loop.test.ts @@ -84,6 +84,7 @@ const runtime = ( Effect.suspend(() => options.beforeSettings?.run ?? Effect.void).pipe( Effect.as(options.settings ?? Settings.defaults), ), + locate: () => Effect.die("unused"), }), ), Layer.provideMerge(sandbox), diff --git a/packages/harness/test/store.test.ts b/packages/harness/test/store.test.ts index 08603a63..7f3699c7 100644 --- a/packages/harness/test/store.test.ts +++ b/packages/harness/test/store.test.ts @@ -106,7 +106,12 @@ const layer = () => { Layer.provideMerge(State.layer({}, seeded.ref, seeded.references, seeded.follow, seeded.rebuild)), Layer.provideMerge(Mcp.layer({ hostCwd: "/", home: "/unused/home" }).pipe(Layer.provide(Process.host))), Layer.provideMerge(SessionRuntime.layer), - Layer.provideMerge(Layer.succeed(Settings.Service, { load: () => Effect.succeed(Settings.defaults) })), + Layer.provideMerge( + Layer.succeed(Settings.Service, { + load: () => Effect.succeed(Settings.defaults), + locate: () => Effect.die("unused"), + }), + ), Layer.provideMerge(sandbox), Layer.provideMerge(Context.layer), Layer.provideMerge(SessionProjector.layer), diff --git a/packages/harness/test/thread.test.ts b/packages/harness/test/thread.test.ts index e83ba90a..bf64ef77 100644 --- a/packages/harness/test/thread.test.ts +++ b/packages/harness/test/thread.test.ts @@ -139,7 +139,12 @@ const layer = () => { Layer.provideMerge(State.layer({}, seeded.ref, seeded.references, seeded.follow, seeded.rebuild)), Layer.provideMerge(Mcp.layer({ hostCwd: "/", home: "/unused/home" }).pipe(Layer.provide(Process.host))), Layer.provideMerge(SessionRuntime.layer), - Layer.provideMerge(Layer.succeed(Settings.Service, { load: () => Effect.succeed(Settings.defaults) })), + Layer.provideMerge( + Layer.succeed(Settings.Service, { + load: () => Effect.succeed(Settings.defaults), + locate: () => Effect.die("unused"), + }), + ), Layer.provideMerge(sandbox), Layer.provideMerge(Context.layer), Layer.provideMerge(SessionProjector.layer), diff --git a/packages/harness/test/tools.toolsearch.test.ts b/packages/harness/test/tools.toolsearch.test.ts index 9cbca7cb..996cc983 100644 --- a/packages/harness/test/tools.toolsearch.test.ts +++ b/packages/harness/test/tools.toolsearch.test.ts @@ -199,7 +199,12 @@ const layer = (tools: Plugin) => { Layer.provideMerge(State.layer({}, seeded.ref, seeded.references, seeded.follow, seeded.rebuild)), Layer.provideMerge(Mcp.layer({ hostCwd: "/", home: "/unused/home" }).pipe(Layer.provide(Process.host))), Layer.provideMerge(SessionRuntime.layer), - Layer.provideMerge(Layer.succeed(Settings.Service, { load: () => Effect.succeed(Settings.defaults) })), + Layer.provideMerge( + Layer.succeed(Settings.Service, { + load: () => Effect.succeed(Settings.defaults), + locate: () => Effect.die("unused"), + }), + ), Layer.provideMerge(sandbox), Layer.provideMerge(Context.layer), Layer.provideMerge(SessionProjector.layer), From 8660e4c3d036b3edc2970562cd2462dc3cdacb0d Mon Sep 17 00:00:00 2001 From: Sanchit Rk <0xsanchit@gmail.com> Date: Wed, 11 Nov 2026 13:35:04 +0530 Subject: [PATCH 6/9] feat(web): project settings for model, retries, MCP and files The project settings page gains General (default model with reasoning, retries), MCP (a switch per server, project overrides for user servers) and Advanced (settings.jsonc and mcp.json edited in place) sections, through the app server's settings calls. The repository section shows the host directory with a main tag, paths are shortened with ~, and rows share one style. Co-Authored-By: Claude Opus 5.5 --- apps/contract/src/contract.ts | 60 +++ apps/server/src/handlers.ts | 48 ++- apps/web/src/widgets/session/config.tsx | 471 ++++++++++++++++++++++ apps/web/src/widgets/session/settings.tsx | 91 ++--- apps/widget/src/codework.ts | 56 +++ 5 files changed, 676 insertions(+), 50 deletions(-) create mode 100644 apps/web/src/widgets/session/config.tsx diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index a43d6ff0..3e81fa0e 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -107,6 +107,44 @@ export class ModelsError extends Schema.TaggedError()("Server.Model message: Schema.String, }) {} +/** A settings file the runtime would reject, at `path`; nothing was written. */ +export class SettingsError extends Schema.TaggedError()("Server.SettingsError", { + path: Schema.String, + message: Schema.String, +}) {} + +/** A settings file changed since it was read; nothing was written. */ +export class SettingsConflict extends Schema.TaggedError()("Server.SettingsConflict", { + path: Schema.String, +}) {} + +/** `settings.jsonc` or `mcp.json`: the project's with `projectId`, else the user's. */ +export const SettingsFileRef = { + projectId: Schema.optionalKey(Schema.String), + file: Schema.Literals(["settings", "mcp"]), +}; + +/** A settings file as written. `version` is what a write is held to; `error` is what the runtime would reject. */ +export const SettingsFile = Schema.Struct({ + path: Schema.String, + source: Schema.String, + exists: Schema.Boolean, + version: Schema.String, + /** The file's JSONC as a value; absent when it does not parse. */ + value: Schema.optionalKey(Schema.Unknown), + error: Schema.optionalKey(Schema.String), + /** For `settings.jsonc`: what applies where this file sets nothing. */ + inherited: Schema.optionalKey( + Schema.Struct({ + retry: Schema.Struct({ maxRetries: Schema.Int, baseDelayMs: Schema.Int, maxDelayMs: Schema.Int }), + }), + ), +}); +export type SettingsFile = typeof SettingsFile.Type; + +/** Every settings call's: only a write can conflict, but one set keeps the app server's mapping single. */ +const SettingsErrors = [CodeworkUnavailable, HostError, ProjectError, SettingsError, SettingsConflict] as const; + export const Layout = Schema.Literals(["tile", "monocle"]); export type Layout = typeof Layout.Type; @@ -504,6 +542,28 @@ export const Api = RpcGroup.make( success: Schema.Struct({ url: Schema.NullOr(Schema.String) }), error: Schema.Union([CodeworkUnavailable, HostError, ProjectError]), }), + /** A settings file on the CodeWork server, as written. */ + Rpc.make("settings.read", { + payload: SettingsFileRef, + success: SettingsFile, + error: Schema.Union(SettingsErrors), + }), + /** The whole file, written only when it is still at `version` and the runtime would accept it. */ + Rpc.make("settings.write", { + payload: { ...SettingsFileRef, source: Schema.String, version: Schema.String }, + success: Schema.Struct({ version: Schema.String }), + error: Schema.Union(SettingsErrors), + }), + /** One value at `at` set in place, the rest of the file kept as written; no `value` removes it. */ + Rpc.make("settings.set", { + payload: { + ...SettingsFileRef, + at: Schema.NonEmptyArray(Schema.Union([Schema.String, Schema.Int])), + value: Schema.optionalKey(Schema.Unknown), + }, + success: Schema.Struct({ version: Schema.String }), + error: Schema.Union(SettingsErrors), + }), /** Renames a project on the CodeWork server; the sidebar follows once the change syncs back. */ Rpc.make("projects.rename", { payload: { projectId: Schema.String, name: Schema.Trimmed.check(Schema.isNonEmpty()) }, diff --git a/apps/server/src/handlers.ts b/apps/server/src/handlers.ts index 6e372990..ec1f0c60 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -1,4 +1,5 @@ -import { Effect, Stream } from "effect"; +import type * as Mirror from "@codeworksh/widget/codework"; +import { Effect, Predicate, Stream } from "effect"; import { SqlClient } from "effect/sql"; import { Cli } from "./cli.ts"; import { Codework } from "./codework.ts"; @@ -8,6 +9,8 @@ import { ModelsError, ProjectError, type ServerAdd, + SettingsConflict, + SettingsError, type ServerUpdate, } from "@codeworksh/contract"; import { Desk } from "./desk.ts"; @@ -20,6 +23,34 @@ import { Sync } from "./sync.ts"; import { Tracking } from "./tracking.ts"; import { Workspaces } from "./workspaces.ts"; +type SettingsRefusal = + | Mirror.SettingsError + | Mirror.SettingsConflictError + | Mirror.ProjectNotFoundError + | Mirror.ProjectCheckoutError; + +const refusals: ReadonlyArray = [ + "SettingsError", + "SettingsConflictError", + "ProjectNotFoundError", + "ProjectCheckoutError", +]; +const isRefusal = (error: unknown): error is SettingsRefusal => + Predicate.hasProperty(error, "_tag") && refusals.includes(error._tag as string); + +const refusal = (error: SettingsRefusal) => { + switch (error._tag) { + case "SettingsError": + return new SettingsError({ path: error.path, message: error.detail }); + case "SettingsConflictError": + return new SettingsConflict({ path: error.path }); + case "ProjectNotFoundError": + return new ProjectError({ message: "This project is no longer on its server." }); + case "ProjectCheckoutError": + return new ProjectError({ message: "This project has no folder on its server." }); + } +}; + export const layer = Contract.Api.toLayer( Effect.gen(function* () { const workspaces = yield* Workspaces.handlers; @@ -38,6 +69,18 @@ export const layer = Contract.Api.toLayer( Codework.callHost(use, options).pipe( Effect.tapError((error) => (error._tag === "Server.CodeworkUnavailable" ? health.poke : Effect.void)), ); + /** A settings call: the server's refusals reach the app with their reason; anything else is an unreachable server. */ + const settingsCall = (use: Parameters>[0]) => + call((client) => + use(client).pipe( + Effect.map((value) => ({ value })), + Effect.catch((error) => + isRefusal(error) ? Effect.succeed({ failed: refusal(error) }) : Effect.fail(error), + ), + ), + ).pipe( + Effect.flatMap((reply) => ("failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.value))), + ); // 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* () { @@ -75,6 +118,9 @@ export const layer = Contract.Api.toLayer( ), ); }), + "settings.read": (input) => settingsCall((client) => client("settings.read", input)), + "settings.write": (input) => settingsCall((client) => client("settings.write", input)), + "settings.set": (input) => settingsCall((client) => client("settings.set", input)), "projects.rename": Effect.fn("projects.rename")(function* ({ projectId, name }) { return yield* callHost((client) => client("project.rename", { projectId, name }).pipe( diff --git a/apps/web/src/widgets/session/config.tsx b/apps/web/src/widgets/session/config.tsx new file mode 100644 index 00000000..67eca772 --- /dev/null +++ b/apps/web/src/widgets/session/config.tsx @@ -0,0 +1,471 @@ +import type { SettingsFile } from "@codeworksh/contract"; +import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { Cause, Option, Predicate } from "effect"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { type ReactNode, useId, useState } from "react"; + +import { ModelPicker, ThinkingPicker } from "@/components/model"; +import { Switch } from "@/components/ui/switch"; +import { Server } from "../../kernel/rpc"; +import { codeworkKey } from "../../kernel/servers"; +import { tilde } from "../../shell/paths"; +import { failed } from "../threads/common"; + +type File = "settings" | "mcp"; + +/** Settings reads refresh after every write; so does what they feed, such as the model list. */ +const keys = ["settings", ...codeworkKey]; + +/** One file, keyed `:`; an empty project id is the user's file. */ +const fileAtom = Atom.family((key: string) => { + const at = key.lastIndexOf(":"); + const projectId = key.slice(0, at); + const file = key.slice(at + 1) as File; + return Server.query("settings.read", projectId === "" ? { file } : { projectId, file }, { reactivityKeys: keys }); +}); +const setAtom = Server.mutation("settings.set"); +const writeAtom = Server.mutation("settings.write"); + +const useFile = (projectId: string | undefined, file: File) => { + const result = useAtomValue(fileAtom(`${projectId ?? ""}:${file}`)); + return AsyncResult.isSuccess(result) ? result.value : undefined; +}; + +/** Sets one value in a project file; a refusal is a toast, and the page keeps showing the file. */ +const useSet = (projectId: string, file: File) => { + const set = useAtomSet(setAtom, { mode: "promise" }); + return (at: readonly [string | number, ...Array], value?: unknown) => + set({ + payload: { projectId, file, at, ...(value === undefined ? {} : { value }) }, + reactivityKeys: keys, + }).catch((error: unknown) => { + failed(error); + throw error; + }); +}; + +const record = (value: unknown): Readonly> => + Predicate.isObject(value) && !Array.isArray(value) ? (value as Record) : {}; + +/** A section heading as Linear sets one, a step quieter: medium weight, in line with its rows' text. */ +export function Heading({ children }: { readonly children: string }) { + return

{children}

; +} + +export function Section({ title, children }: { readonly title: string; readonly children: ReactNode }) { + return ( +
+ {title} +
{children}
+
+ ); +} + +/** + * One setting: its name in regular weight, so the section heading above stays the step up, and a + * muted line under it. The control sits at the end. + */ +export function Row(props: { + readonly title: ReactNode; + readonly description?: ReactNode; + /** The description is a path, cut from its start: the last parts tell folders apart. */ + readonly path?: boolean; + /** The id of the field this row sets: its name becomes that field's label. */ + readonly htmlFor?: string; + readonly children?: ReactNode; +}) { + const Title = props.htmlFor === undefined ? "span" : "label"; + return ( +
+
+ + {props.title} + + {props.description !== undefined && ( + + {props.description} + + )} +
+ {props.children} +
+ ); +} + +/** A category beside a row's name: where a server comes from, which checkout a folder is. */ +export function Tag({ children }: { readonly children: string }) { + return ( + + {children} + + ); +} + +const infoAtom = Server.query("host.info", undefined); + +/** `path` with the home folder as `~`, once the server has said where home is. */ +export const useTilde = () => { + const info = useAtomValue(infoAtom); + const home = AsyncResult.isSuccess(info) ? info.value.home : undefined; + return (path: string) => tilde(path, home); +}; + +/** The model new sessions in this project start on, and how often a failed request is tried again. */ +export function General({ projectId, hostDir }: { readonly projectId: string; readonly hostDir: string }) { + const settings = useFile(projectId, "settings"); + const set = useSet(projectId, "settings"); + const retry = record(record(settings?.value).retry); + const retries = retry.maxRetries; + const retriesId = useId(); + return ( +
+ +
+ + void set(["model", "provider"], model.provider).then(() => set(["model", "id"], model.id)) + } + /> + void set(["model", "thinkingLevel"], level)} + /> +
+
+ + + // Clearing the last retry key takes the empty `retry` block with it. + void ( + next === undefined && Object.keys(retry).every((key) => key === "maxRetries") + ? set(["retry"]) + : set(["retry", "maxRetries"], next) + ).catch(() => undefined) + } + /> + +
+ ); +} + +/** What a count setting accepts, as the settings schema checks it: a whole number, 0 or more. */ +const count = /^\d+$/; + +/** + * A count the project sets, saved on Enter or leaving it. Empty means the project sets none: the value + * it then inherits shows as the placeholder. A typo is held and flagged until it is fixed, not saved. + */ +function Count(props: { + readonly id: string; + readonly value: number | undefined; + readonly inherited: number | undefined; + readonly onCommit: (value: number | undefined) => void; +}) { + const saved = props.value === undefined ? "" : String(props.value); + const [draft, setDraft] = useState(saved); + const [invalid, setInvalid] = useState(false); + const valid = (text: string) => text === "" || count.test(text); + const commit = () => { + const trimmed = draft.trim(); + if (!valid(trimmed)) return setInvalid(true); + const next = trimmed === "" ? undefined : Number(trimmed); + if (next === props.value) return setDraft(saved); + props.onCommit(next); + }; + return ( +
+ {invalid && ( + + Whole number, 0 or more + + )} + { + setDraft(event.target.value); + // Once flagged, the flag clears the moment the value is fixed. + if (invalid && valid(event.target.value.trim())) setInvalid(false); + }} + onBlur={commit} + onKeyDown={(event) => { + if (event.key === "Enter") event.currentTarget.blur(); + if (event.key === "Escape") { + // Puts the saved value back; the settings stay open. + event.preventDefault(); + setDraft(saved); + setInvalid(false); + } + }} + className="h-7 w-20 rounded-md border border-edge/60 bg-transparent px-2 text-right text-xs tabular-nums outline-none transition-colors duration-150 ease-out placeholder:text-ink-muted/70 hover:bg-ink/4 focus:bg-ink/4 focus-visible:ring-2 focus-visible:ring-ring aria-invalid:border-destructive" + /> +
+ ); +} + +interface McpRow { + readonly name: string; + readonly from: "project" | "user"; + readonly detail: string; + readonly enabled: boolean; + /** The project entry only turns the user's server on or off. */ + readonly override: boolean; +} + +/** Where a server runs, as a line: its own description, else its command or URL. */ +const detailOf = (config: Readonly>) => { + if (typeof config.description === "string") return config.description; + if (typeof config.url === "string") return config.url; + const args = Array.isArray(config.args) ? config.args.filter(Predicate.isString) : []; + return typeof config.command === "string" ? [config.command, ...args].join(" ") : ""; +}; + +const isOverride = (config: Readonly>) => + config.command === undefined && config.url === undefined && config.type === undefined; + +/** The MCP servers sessions in this project connect to: the project's own, and the user's it can turn off. */ +export function Mcp({ projectId }: { readonly projectId: string }) { + const project = useFile(projectId, "mcp"); + const user = useFile(undefined, "mcp"); + const set = useSet(projectId, "mcp"); + if (project === undefined || user === undefined) return null; + const own = record(record(project.value).mcpServers); + const theirs = record(record(user.value).mcpServers); + const servers: Array = []; + for (const [name, raw] of Object.entries(theirs)) { + const config = record(raw); + const local = record(own[name]); + const override = name in own && isOverride(local); + if (name in own && !override) continue; + servers.push({ + name, + from: "user", + detail: detailOf(config), + enabled: (override ? local.enabled : config.enabled) !== false, + override, + }); + } + for (const [name, raw] of Object.entries(own)) { + const config = record(raw); + if (isOverride(config)) continue; + servers.push({ + name, + from: "project", + detail: detailOf(config), + enabled: config.enabled !== false, + override: false, + }); + } + servers.sort((a, b) => a.name.localeCompare(b.name)); + const toggle = (server: McpRow, enabled: boolean) => { + // Turning a user server back on drops the project's override rather than leaving `enabled: true`. + const keys = Object.keys(record(own[server.name])); + if (server.from === "user" && enabled && keys.every((key) => key === "enabled")) + return void set(["mcpServers", server.name]).catch(() => undefined); + void set(["mcpServers", server.name, "enabled"], enabled).catch(() => undefined); + }; + return ( +
+ {project.error !== undefined && ( + {project.error}} /> + )} + {servers.length === 0 ? ( + + ) : ( + servers.map((server) => ( + + {server.name} + {server.from === "user" ? "User" : "Project"} + + } + description={server.detail} + > + toggle(server, checked)} + /> + + )) + )} +
+ ); +} + +/** The project's files, each opened in place to edit as text: for whatever the rows above do not cover. */ +export function Files({ projectId, hostDir }: { readonly projectId: string; readonly hostDir: string }) { + return ( +
+ + +
+ ); +} + +const nameOf = (path: string) => path.split("/").at(-1) ?? path; + +/** What each file holds, as its row says it. */ +const purposes: Record = { settings: "Default model, plugins and retries", mcp: "MCP servers" }; + +function FileRow(props: { readonly projectId: string; readonly hostDir: string; readonly file: File }) { + const { projectId, file } = props; + const current = useFile(projectId, file); + const shorten = useTilde(); + const [open, setOpen] = useState(false); + if (current === undefined) return null; + // A file above the host directory belongs to an outer project, and that is worth seeing before editing. + const outside = !current.path.startsWith(`${props.hostDir}/`); + return ( +
+ {nameOf(current.path)}} + path={current.error === undefined && outside} + description={ + current.error !== undefined ? ( + {current.error} + ) : outside ? ( + {shorten(current.path)} + ) : ( + purposes[file] + ) + } + > + {!open && ( + + )} + + {open && setOpen(false)} />} +
+ ); +} + +/** The file as text. Saved only if nobody changed it meanwhile; a refusal keeps what was typed. */ +function Editor(props: { + readonly projectId: string; + readonly file: File; + readonly current: SettingsFile; + readonly onClose: () => void; +}) { + const write = useAtomSet(writeAtom, { mode: "promiseExit" }); + const refresh = useAtomRefresh(fileAtom(`${props.projectId}:${props.file}`)); + // The text and the version it was started from, so a reload can start over. + const [base, setBase] = useState(props.current); + const [draft, setDraft] = useState(props.current.source); + const [problem, setProblem] = useState<{ readonly message: string; readonly conflict: boolean }>(); + const [saving, setSaving] = useState(false); + // A reload waits for the file read again, then starts over from it. + const [reloading, setReloading] = useState(false); + if (reloading && props.current.version !== base.version) { + setReloading(false); + setBase(props.current); + setDraft(props.current.source); + setProblem(undefined); + } + const save = async () => { + setSaving(true); + const exit = await write({ + payload: { projectId: props.projectId, file: props.file, source: draft, version: base.version }, + reactivityKeys: keys, + }); + setSaving(false); + if (exit._tag === "Success") return props.onClose(); + const error = Option.getOrUndefined(Cause.findErrorOption(exit.cause)); + if (error?._tag === "Server.SettingsConflict") + return setProblem({ message: "Changed on disk since you opened it.", conflict: true }); + setProblem({ message: error !== undefined && "message" in error ? error.message : "Not saved", conflict: false }); + }; + return ( +
+