Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
a7d3db8
feat(relay): add relay API with Clerk sign-in and default workspace
sanchitrk Nov 17, 2026
f6d3342
feat: connect machines to workspaces through the relay
sanchitrk Nov 17, 2026
ae1399c
feat(desktop): sign in with Clerk and pick a workspace
sanchitrk Nov 17, 2026
9277255
feat(desktop): connect, list and rename machines from the app
sanchitrk Nov 17, 2026
2b92e16
feat(desktop): install codework from the app
sanchitrk Nov 17, 2026
b4cdd3a
fix(desktop): keep sign-up inside the app
sanchitrk Nov 17, 2026
0c8e497
feat(relay): create workspaces
sanchitrk Nov 17, 2026
9f4439c
feat(desktop): create workspaces and a Linear-style workspace menu
sanchitrk Nov 17, 2026
7d734dd
fix(desktop): no blank page while signing out
sanchitrk Nov 17, 2026
82d9c31
feat(desktop): profile settings and a Linear-style light theme
sanchitrk Nov 17, 2026
dfbc16d
fix
sanchitrk Nov 17, 2026
9acbfe0
tweaks
sanchitrk Nov 17, 2026
b334533
feat(relay): list pending connects, decline them and remove machines
sanchitrk Nov 17, 2026
acd267a
feat(desktop): machines page with requests, manual codes and disconnect
sanchitrk Nov 17, 2026
15cd915
fix: declined connects, typed codes and fresher machine state
sanchitrk Nov 17, 2026
e16f503
fix: confirmed machine links, recoverable sign-in and a connection st…
sanchitrk Nov 18, 2026
08fa096
fix: connect hints, custom-home commands and sign-in outage on first …
sanchitrk Nov 18, 2026
7813797
fix: handle session expiry, stale machine links and home switches
sanchitrk Nov 18, 2026
7114e82
fix(desktop): restore the metrics page width
sanchitrk Nov 18, 2026
65d81ac
feat(desktop): a Linear-style dark theme
sanchitrk Nov 18, 2026
14a1d17
fix(desktop): show setup step failures in red
sanchitrk Nov 18, 2026
bb9d23b
feat: bind every machine link to one identity key (#172)
sanchitrk Nov 19, 2026
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
1 change: 1 addition & 0 deletions apps/contract/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@codeworksh/schema": "workspace:*",
"@codeworksh/widget": "workspace:*",
"effect": "4.0.5"
},
Expand Down
31 changes: 31 additions & 0 deletions apps/contract/src/contract.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Machine } from "@codeworksh/schema";
import { Schema } from "effect";
import { Rpc, RpcGroup } from "effect/rpc";
import {
Expand Down Expand Up @@ -817,6 +818,30 @@ export const Api = RpcGroup.make(
success: ModelList,
error: Schema.Union([CodeworkUnavailable, ModelsError]),
}),
/** The default machine and the workspaces it is connected to. */
Rpc.make("machine.info", {
success: Machine.Status,
error: CodeworkUnavailable,
}),
/** Names the default machine for people; an empty name goes back to the OS's. */
Rpc.make("machine.rename", {
payload: { givenName: Schema.String },
success: Machine.Status,
error: CodeworkUnavailable,
}),
/** Disconnects the default machine from a workspace. */
Rpc.make("machine.disconnect", {
payload: Machine.Disconnect,
success: Machine.Disconnected,
error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]),
}),
/** Connects the default machine to a workspace: the code to approve, then the link. */
Rpc.make("machine.connect", {
payload: { workspaceId: Schema.String },
success: Machine.ConnectEvent,
error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]),
stream: true,
}),
/** The OS home directory, and the folder `host.create` makes projects in. */
Rpc.make("host.info", {
success: Schema.Struct({ home: Schema.String, projects: Schema.String }),
Expand Down Expand Up @@ -993,6 +1018,12 @@ export const Api = RpcGroup.make(
success: Schema.Void,
error: ServersError,
}),
/** Installs codework with the install script, into its default folder, then starts the local server `id`. */
Rpc.make("servers.install", {
payload: { id: Schema.String },
success: Schema.Void,
error: ServersError,
}),
/** Runs `codework service <action>` with a local server's executable, home, arguments and variables. */
Rpc.make("servers.service", {
payload: { id: Schema.String, action: CliAction },
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@
"package": "node scripts/package.mjs"
},
"devDependencies": {
"@clerk/electron": "0.1.10",
"@types/node": "catalog:",
"bumpp": "^12.3.0",
"electron": "44.4.2",
"electron-builder": "^26.15.3",
"electron-store": "8.2.0",
"typescript": "catalog:",
"vite-plus": "catalog:"
}
Expand Down
20 changes: 14 additions & 6 deletions apps/desktop/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { createClerkBridge } from "@clerk/electron";
import { storage } from "@clerk/electron/storage";
import { app, BrowserWindow, dialog, ipcMain, net, protocol, shell } from "electron";
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
Expand All @@ -14,7 +16,7 @@ app.setPath(
path.join(app.getPath("appData"), channel() === "latest" ? "codework" : `codework${channel()}`),
);

const SCHEME = app.isPackaged ? "codework" : "codework-dev";
const SCHEME = app.isPackaged ? "codework" : "codeworkdev";
const HOST = "app";
const APP_URL = `${SCHEME}://${HOST}/`;

Expand Down Expand Up @@ -50,10 +52,16 @@ const MIME_TYPES: Record<string, string> = {
".txt": "text/plain",
};

// Must run synchronously before Electron emits `ready`.
protocol.registerSchemesAsPrivileged([
{
// Must run synchronously before Electron emits `ready`. Clerk's bridge registers the renderer's scheme
// as privileged (one registration per process), keeps the signed-in session encrypted under userData,
// and carries OAuth back to the renderer on the same origin.
createClerkBridge({
storage: storage({ path: path.join(app.getPath("userData"), "clerk") }),
// The app takes the lock itself, below, before any window opens.
manageSingleInstanceLock: false,
renderer: {
scheme: SCHEME,
host: HOST,
privileges: {
standard: true,
secure: true,
Expand All @@ -63,7 +71,7 @@ protocol.registerSchemesAsPrivileged([
codeCache: true,
},
},
]);
});

async function serveAsset(request: Request): Promise<Response> {
const url = new URL(request.url);
Expand Down Expand Up @@ -105,7 +113,7 @@ function handleRequest(request: Request): Promise<Response> {
if (DEV_SERVER_URL) {
const url = new URL(request.url);
if (url.host !== HOST) return Promise.resolve(new Response(null, { status: 404 }));
// Module scripts carry `Origin: codework-dev://app`; forwarding it makes
// Module scripts carry `Origin: codeworkdev://app`; forwarding it makes
// net.fetch a CORS request the dev server never allows, failing every script.
const headers = new Headers(request.headers);
headers.delete("origin");
Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/src/preload.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { exposeClerkBridge } from "@clerk/electron/preload";
import { contextBridge, ipcRenderer } from "electron";
import { HOME_CHANNEL, PICK_FOLDER_CHANNEL, REVEAL_CHANNEL, SERVER_CHANNEL } from "./ipc.ts";

Expand All @@ -12,3 +13,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
reveal: (path: string) => ipcRenderer.invoke(REVEAL_CHANNEL, path) as Promise<void>,
}),
});

// The narrow bridge @clerk/electron/react uses for token storage and OAuth.
exposeClerkBridge();
5 changes: 4 additions & 1 deletion apps/desktop/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { defineConfig } from "vite-plus";

// The main process is bundled to CJS; only `electron` (and Node built-ins)
// stay external — everything else is inlined into the artifact.
const isExternal = (id: string) => id === "electron" || id.startsWith("electron/") || id.startsWith("node:");
// `@clerk/electron-passkeys` is an optional native module Clerk imports only when passkeys are on,
// which they are not.
const isExternal = (id: string) =>
id === "electron" || id.startsWith("electron/") || id.startsWith("node:") || id === "@clerk/electron-passkeys";

// One config per entry: a sandboxed preload cannot require sibling files, so
// modules shared with main must be inlined rather than split into a chunk.
Expand Down
49 changes: 45 additions & 4 deletions apps/server/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@ const run = (
return { output: output.trim(), code: Number(code) };
}).pipe(Effect.scoped, Effect.timeout(timeout));

// A Node crash prints the source line first; the error line says what went wrong.
// A Node crash prints the source line first; the error line says what went wrong, shown without its
// "Error:" label. The exit code only stands in when there is no output to show.
const reason = (output: string, code: number) => {
const lines = output.split("\n").map((line) => line.trim());
const line = lines.findLast((candidate) => /error/i.test(candidate)) ?? lines.findLast(Boolean);
return line === undefined ? `exited with code ${code}` : `exited with code ${code}: ${line.slice(0, 240)}`;
return line === undefined ? `exited with code ${code}` : line.replace(/^error:\s*/i, "").slice(0, 240);
};

// An app opened from the Dock does not inherit the terminal's PATH, so the login shell is asked.
Expand Down Expand Up @@ -201,9 +202,49 @@ export const service = Effect.fn("Cli.service")(function* (row: Servers.LocalRow
const { output, code } = yield* run(file, [...prefix, "service", action, ...args], "30 seconds", {
...env,
CODEWORK_HOME_DIR: servers.homeOf(row).path,
}).pipe(Effect.mapError((error) => new ServersError({ message: `codework service ${action}: ${error.message}` })));
if (code !== 0) return yield* new ServersError({ message: `codework service ${action} ${reason(output, code)}` });
}).pipe(
Effect.mapError((error) => new ServersError({ message: `Couldn't ${action} the server: ${error.message}` })),
);
if (code !== 0)
return yield* new ServersError({ message: `Couldn't ${action} the server: ${reason(output, code)}` });
if (row.isDefault && action !== "stop") yield* awaitConnection;
});

// The script `curl -fsSL https://codework.sh/install | sh` runs; overridable so a test serves its own.
const installScript = Config.String("CODEWORK_INSTALL_SCRIPT").pipe(
Config.withDefault("https://codework.sh/install"),
Effect.orDie,
);

/**
* Installs codework the way the install command does, into the install script's folder, then starts
* `row`. The shell's startup file is left alone: the app finds the binary in that folder by itself.
* A development or canary build of the app installs the newest development build.
*/
export const install = Effect.fn("Cli.install")(function* (row: Servers.LocalRow) {
const url = yield* installScript;
const channel = yield* Config.String("CODEWORK_CHANNEL").pipe(Config.withDefault("latest"), Effect.orDie);
const script = yield* Effect.tryPromise({
try: () =>
fetch(url).then((response) => {
if (!response.ok) throw new Error(`the download answered ${response.status}`);
return response.text();
}),
// fetch rejects with a TypeError when the network is down or the host unknown.
catch: (error) =>
new ServersError({
message:
error instanceof TypeError
? "Couldn't download the installer. Check your connection, then try again."
: `Couldn't download the installer: ${error instanceof Error ? error.message : String(error)}`,
}),
});
const flags = ["--no-modify-path", ...(channel === "dev" || channel === "canary" ? ["--dev"] : [])];
const { output, code } = yield* run("sh", ["-c", script, "install", ...flags], "300 seconds", {
CODEWORK_INSTALL_DIR: yield* installDir,
}).pipe(Effect.mapError((error) => new ServersError({ message: `Couldn't install codework: ${error.message}` })));
if (code !== 0) return yield* new ServersError({ message: `Couldn't install codework: ${reason(output, code)}` });
yield* service(row, "start");
});

export * as Cli from "./cli.ts";
30 changes: 30 additions & 0 deletions apps/server/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,33 @@ export const layer = Contract.Api.toLayer(
"metrics.usage": (input) => Metrics.usage(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)),
"metrics.hours": (input) => Metrics.hours(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)),

"machine.info": Effect.fn("machine.info")(function* () {
return yield* call((client) => client("machine.info", {}));
}),
"machine.rename": Effect.fn("machine.rename")(function* ({ givenName }) {
return yield* call((client) => client("machine.rename", { givenName }));
}),
// The CLI's own failure (not connected to that workspace) keeps its message.
"machine.disconnect": Effect.fn("machine.disconnect")(function* (input) {
const reply = yield* call((client) =>
client("machine.disconnect", input).pipe(
Effect.map((disconnected) => ({ disconnected })),
Effect.catchTag("Machine.ConnectError", (failed) => Effect.succeed({ failed })),
),
);
return yield* "failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.disconnected);
}),
// The CLI's own connect failure (the relay unreachable, the code expired) keeps its message; only
// a dropped server reads as unavailable.
"machine.connect": ({ workspaceId }) =>
Codework.stream((client) =>
client("machine.connect", { workspaceId }).pipe(
Stream.map((event) => ({ event })),
Stream.catchTag("Machine.ConnectError", (failed) => Stream.succeed({ failed })),
),
).pipe(
Stream.flatMap((item) => ("failed" in item ? Stream.fail(item.failed) : Stream.succeed(item.event))),
),
"host.info": Effect.fn("host.info")(function* () {
return yield* call((client) => client("host.info", {}));
}),
Expand Down Expand Up @@ -206,6 +233,9 @@ export const layer = Contract.Api.toLayer(
yield* changingDefault(servers.setDefault(id));
yield* health.check;
}),
"servers.install": Effect.fn("servers.install")(function* ({ id }: { readonly id: string }) {
yield* Cli.install(yield* servers.getLocal(id)).pipe(Effect.ensuring(health.check));
}),
"servers.service": Effect.fn("servers.service")(function* ({
id,
action,
Expand Down
6 changes: 5 additions & 1 deletion apps/server/src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,11 @@ export const layer = Layer.effect(
);
const client = Context.get(context, Client);
clients.set(row.id, client);
yield* Effect.addFinalizer(() => Effect.sync(() => clients.delete(row.id)));
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
if (clients.get(row.id) === client) clients.delete(row.id);
}),
);
yield* Effect.forkScoped(followUsage(row.id, client));
yield* connected(row.id, client).pipe(
Effect.catchCause((cause) =>
Expand Down
3 changes: 3 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@clerk/electron": "0.1.10",
"@codeworksh/contract": "workspace:*",
"@codeworksh/schema": "workspace:*",
"@codeworksh/widget": "workspace:*",
"@effect/atom-react": "4.0.5",
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/lilex": "5.3.0",
"@legendapp/list": "3.3.5",
"@phosphor-icons/react": "2.1.10",
"@pierre/diffs": "1.6.2",
Expand Down
94 changes: 94 additions & 0 deletions apps/web/src/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { ClerkProvider, SignIn, SignUp, useAuth, useClerk } from "@clerk/electron/react";
import { type ReactNode, useEffect, useState } from "react";

import { isElectron } from "./env";
import { setSession } from "./kernel/relay";
import { reveal } from "./splash";

const key: unknown = import.meta.env.CLERK_PUBLISHABLE_KEY;
const publishableKey = typeof key === "string" && key !== "" ? key : undefined;

/** Whether this app signs people in: the desktop app, built with a publishable key. */
export const isSignedInApp = isElectron && publishableKey !== undefined;

// Signing in and up live on these paths of the app's own origin. Clerk's default, its hosted Account
// Portal, cannot return to an Electron window. The app's router reads only the hash, so these paths
// never reach it; finishing returns to the root.
const SIGN_IN = "/sign-in";
const SIGN_UP = "/sign-up";
const HOME = "/#/";

/**
* The desktop app requires a signed-in account. A browser build of the web app, or a build without a
* publishable key, runs without one.
*/
export function Auth({ children }: { readonly children: ReactNode }) {
// Clerk moves between sign-in, sign-up and their steps through these, so the gate re-renders.
// The app opens at its root; Clerk's forms render only on their own paths, so it starts on sign-in.
// The hash, which is the app's route, is kept.
const [path, setPath] = useState(() => {
const { pathname, hash } = window.location;
if (isSignedInApp && !pathname.startsWith(SIGN_IN) && !pathname.startsWith(SIGN_UP)) {
window.history.replaceState(null, "", `${SIGN_IN}${hash}`);
}
return window.location.pathname;
});
if (!isSignedInApp || publishableKey === undefined) return children;
const navigate = (replace: boolean) => (to: string) => {
window.history[replace ? "replaceState" : "pushState"](null, "", to);
setPath(window.location.pathname);
};
return (
<ClerkProvider
publishableKey={publishableKey}
signInUrl={SIGN_IN}
signUpUrl={SIGN_UP}
afterSignOutUrl={SIGN_IN}
routerPush={navigate(false)}
routerReplace={navigate(true)}
>
<Gate signingUp={path.startsWith(SIGN_UP)}>{children}</Gate>
</ClerkProvider>
);
}

function Gate({ signingUp, children }: { readonly signingUp: boolean; readonly children: ReactNode }) {
const clerk = useClerk();
const { isLoaded, isSignedIn, getToken, userId } = useAuth();
// Before the app renders, so the relay client's first call already carries the session.
setSession(getToken, userId);
// 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 />;
return isSignedIn ? children : <SignInScreen signingUp={signingUp} />;
}

function Screen({ children }: { readonly children?: ReactNode }) {
return (
<div className="flex h-full flex-col bg-desktop">
<div className="h-titlebar shrink-0 [-webkit-app-region:drag]" />
<div className="flex flex-1 items-center justify-center overflow-auto pb-titlebar">{children}</div>
</div>
);
}

function SignInScreen({ signingUp }: { readonly signingUp: boolean }) {
useEffect(reveal, []);
return (
<Screen>
{signingUp ? (
<SignUp routing="path" path={SIGN_UP} signInUrl={SIGN_IN} forceRedirectUrl={HOME} />
) : (
<SignIn
routing="path"
path={SIGN_IN}
signUpUrl={SIGN_UP}
forceRedirectUrl={HOME}
signUpForceRedirectUrl={HOME}
/>
)}
</Screen>
);
}
Loading