Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions apps/web/src/auth.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ClerkProvider, SignIn, SignUp, useAuth, useClerk } from "@clerk/electron/react";
import { ClerkProvider, SignIn, SignUp, useAuth, useClerk, useUser } from "@clerk/electron/react";
import { type ReactNode, useEffect, useState } from "react";

import { setSession } from "./kernel/relay";
Expand Down Expand Up @@ -49,13 +49,15 @@ export function Auth({ children }: { readonly children: ReactNode }) {
function Gate({ signingUp, children }: { readonly signingUp: boolean; readonly children: ReactNode }) {
const clerk = useClerk();
const { isLoaded, isSignedIn, getToken, userId } = useAuth();
const { isLoaded: userLoaded, user } = useUser();
const personalWorkspaceName = user?.fullName?.trim().slice(0, 64) || undefined;
// Before the app renders, so the relay client's first call already carries the session.
setSession(getToken, userId);
setSession(getToken, userId, personalWorkspaceName);
// Clerk unreachable (offline): local work keeps running; only cloud features wait for it.
if (clerk.status === "error") return children;
// Clerk is briefly not loaded while it signs out too, after the splash is gone: the screen's backdrop
// holds the window instead of an empty page.
if (!isLoaded) return <Screen />;
if (!isLoaded || (isSignedIn && !userLoaded)) return <Screen />;
return isSignedIn ? children : <SignInScreen signingUp={signingUp} />;
}

Expand Down
16 changes: 12 additions & 4 deletions apps/web/src/kernel/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ type TokenSource = (options?: { readonly skipCache?: boolean }) => Promise<strin
let sessionToken: TokenSource = () => Promise.resolve(null);
/** Where the signed-in person's account is remembered on this device, so it shows while out of reach. */
let accountKey: string | undefined;
export const setSession = (source: TokenSource, userId: string | null | undefined) => {
/** Display name passed on first `/v1/me` so Relay names the personal workspace after the signed-in user. */
let personalWorkspaceName: string | undefined;
export const setSession = (source: TokenSource, userId: string | null | undefined, workspaceName?: string) => {
sessionToken = source;
accountKey = userId == null ? undefined : `codework.account.${userId}`;
personalWorkspaceName = workspaceName;
};

const remembered = (): Relay.Me | undefined => {
Expand Down Expand Up @@ -142,7 +145,9 @@ export const meAtom = runtime
// Without a session yet there is nothing to ask the relay with; wait for one.
const get = Effect.gen(function* () {
if ((yield* currentToken()) === null) return yield* pending();
return yield* client.me.get();
return yield* client.me.get({
query: personalWorkspaceName === undefined ? {} : { personalWorkspaceName },
});
});
return yield* get.pipe(
Effect.tap((me) => Effect.sync(() => remember(me))),
Expand Down Expand Up @@ -185,12 +190,15 @@ export const chooseWorkspaceAtom = Atom.writable(
(ctx, id: string) => ctx.set(chosenAtom, id),
);

/** The workspace the app works in: the one picked, while the account still belongs to it, else the first. */
/** The workspace the app works in: the one picked, while the account still belongs to it, else the personal one. */
export const workspaceAtom = Atom.make((get) => {
const chosen = get(chosenAtom);
return AsyncResult.map(
get(meAtom),
(me) => me.workspaces.find((workspace) => workspace.id === chosen) ?? me.workspaces[0],
(me) =>
me.workspaces.find((workspace) => workspace.id === chosen) ??
me.workspaces.find(Relay.isPersonalWorkspace) ??
me.workspaces[0],
);
});

Expand Down
8 changes: 6 additions & 2 deletions apps/web/src/setup.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { shellQuoted } from "@codeworksh/schema/shell";
import { useAtom, useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
import type { Relay } from "@codeworksh/schema/relay";
import { Relay } from "@codeworksh/schema/relay";
import type { LocalServerStatus } from "@codeworksh/contract";
import { CaretRightIcon, CheckIcon } from "@phosphor-icons/react";
import { useNavigate } from "@tanstack/react-router";
Expand Down Expand Up @@ -229,7 +229,11 @@ function Setup({ workspace }: { readonly workspace: Relay.Workspace | undefined
current={current}
title={`Link to ${workspaceName}`}
summary={`Linked to ${workspaceName}`}
line={`${name} shows up in ${workspaceName} for everyone in it.`}
line={
workspace !== undefined && Relay.isPersonalWorkspace(workspace)
? `${name} shows up in your personal ${workspaceName} workspace.`
: `${name} shows up in ${workspaceName} for everyone in it.`
}
problem={null}
command={`codework connect${workspaceId === undefined ? "" : ` --workspace ${workspaceId}`}${home}`}
error={null}
Expand Down
17 changes: 13 additions & 4 deletions apps/web/src/shell/workspace.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useClerk } from "@clerk/electron/react";
import { Relay } from "@codeworksh/schema/relay";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { CaretDownIcon, CheckIcon, PlusIcon } from "@phosphor-icons/react";
import { useNavigate } from "@tanstack/react-router";
Expand Down Expand Up @@ -27,8 +28,9 @@ export function WorkspaceSwitcher() {
const navigate = useNavigate();
const current = useAtomValue(workspaceAtom);
const workspace = AsyncResult.isSuccess(current) ? current.value : undefined;
const id = workspace?.id ?? "codework";
const name = workspace?.name ?? "CodeWork";
const id = workspace?.id ?? Relay.DEFAULT_PERSONAL_WORKSPACE_SLUG;
const name = workspace?.name ?? Relay.DEFAULT_PERSONAL_WORKSPACE_NAME;
const personal = workspace === undefined || Relay.isPersonalWorkspace(workspace);
return (
<DropdownMenu>
<DropdownMenuTrigger className="flex h-8 max-w-full items-center gap-2 self-start rounded-md px-1.5 text-left text-ui text-ink outline-none transition-colors duration-150 ease-out hover:bg-selection-subtle focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset data-[state=open]:bg-selection-subtle data-[state=open]:duration-0">
Expand All @@ -38,8 +40,12 @@ export function WorkspaceSwitcher() {
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56">
<DropdownMenuItem onSelect={() => void navigate({ to: "/settings" })}>Settings</DropdownMenuItem>
{/* Members come with invites; the row marks where they will live. */}
<DropdownMenuItem disabled>Invite & Manage Members</DropdownMenuItem>
{personal ? (
<DropdownMenuLabel className="text-xs font-normal text-ink-muted">Personal · Only you</DropdownMenuLabel>
) : (
/* Members come with invites; the row marks where they will live. */
<DropdownMenuItem disabled>Invite & Manage Members</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<SwitchWorkspace current={workspace?.id} />
<SignOut />
Expand All @@ -65,6 +71,9 @@ function SwitchWorkspace({ current }: { readonly current: string | undefined })
<DropdownMenuItem key={option.id} onSelect={() => choose(option.id)}>
<Monogram id={option.id} name={option.name} />
<span className="min-w-0 flex-1 truncate">{option.name}</span>
{Relay.isPersonalWorkspace(option) && (
<span className="shrink-0 text-2xs text-ink-muted">Personal</span>
)}
{option.id === current && <CheckIcon size={13} className="shrink-0" aria-hidden />}
</DropdownMenuItem>
))}
Expand Down
3 changes: 2 additions & 1 deletion docs/internals/00_glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ The domains and the processes that make up CodeWork.
| Sandbox driver | Code that provisions remote sandboxes. Its contract is in `packages/plugin`, but the embedder supplies it, not settings. |
| Paired | A device given access to a server with a one-time code (`codework service pair`), like an SSH key. It cannot manage devices. |
| Linked machine | A machine that joined a workspace through Relay (`codework connect`). Membership, not access. |
| Workspace | A group of people and machines in Relay. People are owners, admins or members. |
| Actor | Who is acting in the runtime (`ActorRef = { id, scope }`). Defaults to root (`local` / `local`), like Unix `uid 0` / `gid 0`. |
| Workspace | A virtual permission boundary in Relay: either an account's personal workspace (`slug = local`, named `Personal Workspace` by default) or a team workspace with owners, admins and members. |

## Technical Details

Expand Down
6 changes: 6 additions & 0 deletions docs/internals/04_runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ The `subagent` origin is modelled in the schema and its constraints, but nothing

Per-session overrides held by [runtime.ts](../../packages/harness/src/session/runtime.ts) are process memory and never reach the log. The model and thinking level are not among them; they are durable session config.

## Runtime Actor

Core sees only `ActorRef = { id, scope }` ([actor.ts](../../packages/schema/src/actor.ts)), never users, roles or workspaces. `Actor.Current` is an Effect `Context.Reference` defaulting to root (`{ id: "local", scope: "local" }`), so in-process CLI, ACP, SDK callers and background crash recovery (`resumeUnfinished`) all run as root without configuration.

No harness table stores actor or workspace columns. Permission checks belong at request admission (`open()`), not inside the durable drain (`read()`), so a resumed run works its queue as the host daemon without needing a stored actor credential.

## Storage and Control

[control.ts](../../packages/harness/src/control.ts) holds the commands that start, join and stop work. `Session.Service` and `Thread.Service` are repositories: they record what happened and never learn that a process manager exists. Control decides whether, when and for how long a session runs. Control depends on execution and storage, and neither depends back. Keep it that way: nothing below Control may reach up into fiber ownership.
Expand Down
2 changes: 1 addition & 1 deletion docs/internals/10_relay.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ The API is declared once in [packages/schema/src/relay.ts](../../packages/schema

People call with a Clerk session token as a bearer ([clerk.ts](../../infra/relay/src/clerk.ts)). Relay takes only the verified subject from it, and reads the person's email and name from Clerk once, on their first call. The `account` row is keyed by that subject, so a change of auth vendor migrates users and nothing else. Clerk being unreachable is `Unavailable` (try again), never `Unauthorized`. The desktop app shows the two differently. CORS admits only the desktop renderer's origins ([http.ts](../../infra/relay/src/http.ts)), so the renderer talks to Relay directly, not through the app server.

A person's first call to `/v1/me` creates their account and a default workspace in which they are the owner. Two concurrent first calls create exactly one account and workspace, because the unique subject makes the loser insert nothing ([accounts.ts](../../infra/relay/src/accounts.ts)).
A person's first call to `/v1/me` creates their account and a personal workspace (`slug = 'local'`, named from `personalWorkspaceName` when supplied by the client, else `Personal Workspace`) in which they are the sole `owner`. Two concurrent first calls create exactly one account and workspace, because the unique subject makes the loser insert nothing ([accounts.ts](../../infra/relay/src/accounts.ts)). A workspace keeps its global UUID `id` on the wire, with `slug` unique on `(account_id, slug)`: `local` is personal (no invites, permanent), while `POST /v1/workspaces` generates a unique slug (`slug.ts`, ending in the UUID's last 8 chars) for team workspaces and refuses `local`. On the machine side, single-user work says `local`; Relay calls and `machine.json` links use the workspace UUID, and the outer layer maps between them.

Machines never hold a session. Every machine request body is one compact JWS ([jws.ts](../../packages/schema/src/jws.ts), Ed25519 over WebCrypto so the same code signs in Node and verifies in any runtime). Its claims name the operation in `op`, so a signature made for one endpoint is refused by every other. Each request carries `iat` and is refused outside a short freshness window. A machine with a skewed clock therefore sees its heartbeats refused, and its server logs a warning rather than treating that as a revoke. `revoke` also carries a `jti`, kept in the database so a replay is refused across every Relay instance. Heartbeats are idempotent and carry none.

Expand Down
57 changes: 36 additions & 21 deletions infra/relay/src/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ import { Context, Effect, Layer } from "effect";
import { SqlClient } from "effect/sql";
import { Relay } from "@codeworksh/schema/relay";
import { Clerk } from "./clerk.ts";
import * as Slug from "./slug.ts";

/** People and the workspaces they belong to. */
export class Accounts extends Context.Service<
Accounts,
{
/** The person's account and workspaces, creating the account and its default workspace on first sight. */
readonly ensure: (authId: string) => Effect.Effect<Relay.Me, Relay.Unavailable>;
/** A new workspace the person owns. */
readonly createWorkspace: (authId: string, name: string) => Effect.Effect<Relay.Workspace, Relay.Unavailable>;
/** The person's account and workspaces, creating the account and its personal workspace on first sight. */
readonly ensure: (authId: string, personalWorkspaceName?: string) => Effect.Effect<Relay.Me, Relay.Unavailable>;
/** A new team workspace the person owns. */
readonly createWorkspace: (
authId: string,
name: string,
) => Effect.Effect<Relay.Workspace, Relay.BadRequest | Relay.Unavailable>;
}
>()("relay/Accounts") {
static readonly layer = Layer.effect(
Expand All @@ -25,10 +29,10 @@ export class Accounts extends Context.Service<
`.pipe(Effect.map((rows) => rows[0]));

// Concurrent first calls both reach the insert; the unique auth_id makes the loser wait for the
// winner's commit and insert nothing, so exactly one default workspace is created.
const create = Effect.fn("Accounts.create")(function* (authId: string) {
// winner's commit and insert nothing, so exactly one personal workspace (`local`) is created.
const create = Effect.fn("Accounts.create")(function* (authId: string, personalWorkspaceName?: string) {
const profile = yield* clerk.profile(authId);
const workspaceName = `${profile.firstName ?? profile.email.split("@")[0]}'s Workspace`;
const workspaceName = personalWorkspaceName ?? Relay.DEFAULT_PERSONAL_WORKSPACE_NAME;
yield* sql.withTransaction(
Effect.gen(function* () {
const created = yield* sql<{ readonly id: string; readonly accountId: string }>`
Expand All @@ -38,8 +42,8 @@ export class Accounts extends Context.Service<
ON CONFLICT (auth_id) DO NOTHING
RETURNING id
)
INSERT INTO workspace (name, account_id)
SELECT ${workspaceName}, id FROM inserted
INSERT INTO workspace (slug, name, account_id)
SELECT ${Relay.DEFAULT_PERSONAL_WORKSPACE_SLUG}, ${workspaceName}, id FROM inserted
RETURNING id, account_id
`;
for (const workspace of created) {
Expand All @@ -53,18 +57,21 @@ export class Accounts extends Context.Service<
});

const ensure = Effect.fn("Accounts.ensure")(
function* (authId: string) {
const account = (yield* find(authId)) ?? (yield* create(authId).pipe(Effect.andThen(find(authId))));
function* (authId: string, personalWorkspaceName?: string) {
const account =
(yield* find(authId)) ??
(yield* create(authId, personalWorkspaceName).pipe(Effect.andThen(find(authId))));
if (account === undefined) return yield* Effect.die(new Error(`No account for ${authId}`));
const workspaces = yield* sql<{
readonly id: string;
readonly slug: string;
readonly name: string;
readonly role: typeof Relay.Role.Type;
}>`
SELECT w.id, w.name, m.role
SELECT w.id, w.slug, w.name, m.role
FROM member m JOIN workspace w ON w.id = m.workspace_id
WHERE m.account_id = ${account.id}
ORDER BY w.created_at, w.id
ORDER BY (w.slug = ${Relay.DEFAULT_PERSONAL_WORKSPACE_SLUG}) DESC, w.created_at, w.id
`;
return new Relay.Me({
account: new Relay.Account(account),
Expand All @@ -78,18 +85,26 @@ export class Accounts extends Context.Service<
ensure,
createWorkspace: Effect.fn("Accounts.createWorkspace")(
function* (authId, name) {
if (name.trim().toLowerCase() === Relay.DEFAULT_PERSONAL_WORKSPACE_SLUG) {
return yield* new Relay.BadRequest({
message: 'The name "local" is reserved for your personal workspace',
});
}
const { account } = yield* ensure(authId);
return yield* sql.withTransaction(
Effect.gen(function* () {
const [workspace] = yield* sql<{ readonly id: string }>`
INSERT INTO workspace (name, account_id) VALUES (${name}, ${account.id}) RETURNING id
`;
if (workspace === undefined) return yield* Effect.die(new Error("No workspace inserted"));
const [generated] = yield* sql<{ readonly id: string }>`SELECT uuidv7()::text AS id`;
if (generated === undefined) return yield* Effect.die(new Error("No workspace id generated"));
const slug = yield* Slug.create(generated.id);
yield* sql`
INSERT INTO member (workspace_id, account_id, role)
VALUES (${workspace.id}, ${account.id}, 'owner')
`;
return new Relay.Workspace({ id: workspace.id, name, role: "owner" });
INSERT INTO workspace (id, slug, name, account_id)
VALUES (${generated.id}::uuid, ${slug}, ${name}, ${account.id})
`;
yield* sql`
INSERT INTO member (workspace_id, account_id, role)
VALUES (${generated.id}::uuid, ${account.id}, 'owner')
`;
return new Relay.Workspace({ id: generated.id, slug, name, role: "owner" });
}),
);
},
Expand Down
4 changes: 2 additions & 2 deletions infra/relay/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ const MeHandlers = HttpApiBuilder.group(
"me",
Effect.fn(function* (handlers) {
const accounts = yield* Accounts;
return handlers.handle("get", () =>
return handlers.handle("get", ({ query }) =>
Effect.gen(function* () {
return yield* accounts.ensure((yield* Relay.Person).authId);
return yield* accounts.ensure((yield* Relay.Person).authId, query.personalWorkspaceName);
}),
);
}),
Expand Down
30 changes: 30 additions & 0 deletions infra/relay/src/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,34 @@ export const migrations = {
)
`;
}),
"2026113001_workspace_slug": Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`ALTER TABLE workspace ADD COLUMN slug text`;
// Earliest workspace per account becomes its personal workspace (`local`);
// any additional workspaces get a unique derived slug that cannot collide with `local`.
yield* sql`
WITH ranked AS (
SELECT
id,
row_number() OVER (PARTITION BY account_id ORDER BY created_at, id) AS rn,
trim(both '-' FROM regexp_replace(lower(name), '[^a-z0-9]+', '-', 'g')) AS raw_slug
FROM workspace
)
UPDATE workspace w
SET
slug = CASE
WHEN r.rn = 1 THEN 'local'
WHEN r.raw_slug = '' OR r.raw_slug = 'local' THEN 'workspace-' || r.rn::text
ELSE left(r.raw_slug, 55) || '-' || r.rn::text
END,
name = CASE
WHEN r.rn = 1 AND btrim(w.name) = '' THEN 'Personal Workspace'
ELSE w.name
END
FROM ranked r
WHERE w.id = r.id
`;
yield* sql`ALTER TABLE workspace ALTER COLUMN slug SET NOT NULL`;
yield* sql`ALTER TABLE workspace ADD CONSTRAINT workspace_account_slug UNIQUE (account_id, slug)`;
}),
};
Loading