diff --git a/CHANGELOG.md b/CHANGELOG.md index c1d6da2c..b3a836dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ This file is the canonical source for unreleased changes and published release n ## [Unreleased] +### Changed + +- `vp run knip:check` reports unused exports in `packages/aikit`, `packages/codework`, `packages/harness` and `packages/plugin` as well as the apps. Modules other than a package's entry points no longer re-export themselves as a namespace (`export * as X from "./x.ts"`); their importers use `import * as X`, so knip sees which members are used. + +### Removed + +- Internal exports nothing imported, across aikit, codework, harness and plugin. Those also unused inside their own module are deleted, among them harness's `PluginStore.remove` and `PluginStore.all`, the `ToolRegistry` service and its layer, `Space.layerWith`, `Worktree.layerWith` and `Worktree.defaultLayer`. Package entry points are unchanged except as below. +- `@codeworksh/harness/effect`: `Global.defaultLayer`, a duplicate of `Global.layer`. + ## [@codeworksh/desktop@0.4.0] - 2026-11-06 ### Added diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index d68560ef..3e81fa0e 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, @@ -77,11 +77,27 @@ 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, }) {} +/** 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. */ @@ -91,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; @@ -439,6 +493,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), @@ -477,6 +536,40 @@ 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]), + }), + /** 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()) }, + 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..ec1f0c60 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -1,8 +1,18 @@ -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"; -import { type CliAction, Contract, ModelsError, type ServerAdd, type ServerUpdate } from "@codeworksh/contract"; +import { + type CliAction, + Contract, + ModelsError, + ProjectError, + type ServerAdd, + SettingsConflict, + SettingsError, + type ServerUpdate, +} from "@codeworksh/contract"; import { Desk } from "./desk.ts"; import { Event } from "./event.ts"; import { Health } from "./health.ts"; @@ -13,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; @@ -31,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* () { @@ -45,6 +95,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)), @@ -58,6 +109,27 @@ 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." })), + ), + ), + ); + }), + "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( + 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/server/src/reads.ts b/apps/server/src/reads.ts index e8043823..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, @@ -80,7 +81,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 @@ -427,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/server/test/fixtures/apps.ts b/apps/server/test/fixtures/apps.ts index 4a456e5a..8131213d 100644 --- a/apps/server/test/fixtures/apps.ts +++ b/apps/server/test/fixtures/apps.ts @@ -12,7 +12,7 @@ import { DatabaseSync } from "node:sqlite"; import { fileURLToPath } from "node:url"; import { expect } from "vite-plus/test"; import { Contract } from "@codeworksh/contract"; -import { Client } from "../../../../packages/codework/src/server/client.ts"; +import * as Client from "../../../../packages/codework/src/server/client.ts"; const appEntry = fileURLToPath(new URL("../../src/index.ts", import.meta.url)); const fixture = fileURLToPath(new URL("./codework.ts", import.meta.url)); diff --git a/apps/server/test/fixtures/codework.ts b/apps/server/test/fixtures/codework.ts index 6c930fd1..1390a950 100644 --- a/apps/server/test/fixtures/codework.ts +++ b/apps/server/test/fixtures/codework.ts @@ -4,8 +4,8 @@ import { NodeRuntime } from "@effect/platform-node"; import { Effect, Layer } from "effect"; import { createInterface } from "node:readline"; import { assistant } from "../../../../packages/harness/test/fixtures/llm.ts"; -import type { LLM } from "../../../../packages/harness/src/runner/llm.ts"; -import { Server } from "../../../../packages/codework/src/server/server.ts"; +import type * as LLM from "../../../../packages/harness/src/runner/llm.ts"; +import * as Server from "../../../../packages/codework/src/server/server.ts"; import { Control, Harness } from "../../../../packages/harness/src/effect.ts"; /* diff --git a/apps/server/test/machines/drive.ts b/apps/server/test/machines/drive.ts index 339f357c..5103e744 100644 --- a/apps/server/test/machines/drive.ts +++ b/apps/server/test/machines/drive.ts @@ -2,7 +2,7 @@ import { NodeRuntime } from "@effect/platform-node"; import { Effect } from "effect"; import { readFileSync } from "node:fs"; -import { Client } from "../../../../packages/codework/src/server/client.ts"; +import * as Client from "../../../../packages/codework/src/server/client.ts"; /* * `node --conditions=development drive.ts < calls.json`: runs `[[method, payload], ...]` in order diff --git a/apps/server/test/machines/orb.ts b/apps/server/test/machines/orb.ts index a32e5f48..da5e0490 100644 --- a/apps/server/test/machines/orb.ts +++ b/apps/server/test/machines/orb.ts @@ -4,7 +4,7 @@ import { spawn, spawnSync } from "node:child_process"; import { userInfo } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; -import { Client } from "../../../../packages/codework/src/server/client.ts"; +import * as Client from "../../../../packages/codework/src/server/client.ts"; const scripts = fileURLToPath(new URL(".", import.meta.url)); /** The checkout under test: each machine overlays its sources from here through the Mac mount. */ diff --git a/apps/server/test/sync.machines.live.test.ts b/apps/server/test/sync.machines.live.test.ts index d32ec9a0..685a15a7 100644 --- a/apps/server/test/sync.machines.live.test.ts +++ b/apps/server/test/sync.machines.live.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { userInfo } from "node:os"; import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test"; import { Contract, LOCAL_SERVER } from "@codeworksh/contract"; -import type { Client } from "../../../packages/codework/src/server/client.ts"; +import type * as Client from "../../../packages/codework/src/server/client.ts"; import { app, cleanup, 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..813dd564 100644 --- a/apps/web/src/components/ui/dropdown-menu.tsx +++ b/apps/web/src/components/ui/dropdown-menu.tsx @@ -15,6 +15,11 @@ 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. Popovers that act as menus share the surface and motion. +export const menuSurface = + "rounded-[12px] border bg-popover 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"; + function DropdownMenuContent({ className, sideOffset = 4, @@ -26,7 +31,8 @@ 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 p-1", + menuSurface, className, )} {...props} @@ -179,7 +185,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 +195,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({ + + + + {/* Dense, as the other menus: a plain 32px search row and a short empty line. */} + + + + + No Connectors Found + {/* Where connectors come from: your user settings, where they are added and signed in to. */} +
+ setOpen(false)} + // The list takes Enter for its own rows; on the link it follows the link. + onKeyDown={(event) => { + if (event.key === "Enter") event.stopPropagation(); + }} + className="flex h-7 items-center gap-1.5 rounded-[8px] px-1.5 text-[13px] outline-none transition-colors duration-150 ease-out hover:bg-accent focus-visible:bg-accent" + > + Manage + + +
+
+
+
+
+
+ + + ); +} + +/** + * Rows from one source inside a section, under a quiet label: where they come from is said once for the + * group instead of on every row. + */ +function Group(props: { readonly label: string; readonly count: number; readonly children: ReactNode }) { + const id = useId(); + return ( +
+
+ {props.label} + {props.count > 0 && {props.count}} +
+ {props.children} +
+ ); +} + +/** 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 ( +
+