Skip to content
Closed
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
5 changes: 4 additions & 1 deletion apps/desktop/scripts/dev.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ while (!(await ready())) await sleep(100);

let electron;
function startElectron() {
electron = run("node", ["scripts/start-electron.mjs"], {
// pnpm inserts a lone `--` before arguments meant for the script.
const extra = process.argv.slice(2);
if (extra[0] === "--") extra.shift();
electron = run("node", ["scripts/start-electron.mjs", ...extra], {
cwd: desktopDir,
env: { ...process.env, CODEWORK_WEB_URL: WEB_URL },
});
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/scripts/start-electron.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ const electronPath = process.platform === "darwin" ? brandedElectron() : electro
const env = { ...process.env };
delete env.ELECTRON_RUN_AS_NODE;

const child = spawn(electronPath, ["."], {
// Extra arguments reach Electron, `--remote-debugging-port=9222` say.
const child = spawn(electronPath, [".", ...process.argv.slice(2)], {
stdio: "inherit",
cwd: desktopDir,
env,
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/kernel/servers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export interface Problem {
/** The default server's problem from its status; undefined while the app can work with it. */
export function problemOf(status: ServerStatus): Problem | undefined {
const { cli, server } = status;
// An already running, compatible server is usable even without a local CLI.
if (server._tag === "Running") return undefined;
if (cli === null)
return {
title: "CodeWork Isn't Installed",
Expand All @@ -43,8 +45,6 @@ export function problemOf(status: ServerStatus): Problem | undefined {
title: "Incompatible Server Version",
line: `${status.name} runs codework v${server.version}, which this app can't read.`,
};
case "Running":
return undefined;
}
}

Expand Down
11 changes: 9 additions & 2 deletions apps/web/src/widgets/session/address.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type { ThreadRef } from "./schema";

const prefix = "codework://session/";

/** A session's address: its main thread's. Another thread's is `<session address>/<thread id>`. */
export const sessionAddress = (id: string) => `${prefix}${id}`;

export const sessionId = (address: string | undefined) =>
address?.startsWith(prefix) ? address.slice(prefix.length) : undefined;
export const threadRef = (address: string | undefined): ThreadRef | undefined => {
if (!address?.startsWith(prefix)) return undefined;
const [sessionId, threadId, ...rest] = address.slice(prefix.length).split("/");
if (sessionId === undefined || sessionId === "" || threadId === "" || rest.length > 0) return undefined;
return threadId === undefined ? { sessionId } : { sessionId, threadId };
};
232 changes: 151 additions & 81 deletions apps/web/src/widgets/session/backend.ts

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions apps/web/src/widgets/session/composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useEffect, useRef, useState } from "react";
import { PromptComposer, ComposerHeader, ComposerSubmit, ComposerButton, type Submit } from "@/components/composer";
import { ModelPicker, type ModelRef, ThinkingPicker } from "@/components/model";
import type { Delivery, ThinkingLevel } from "@codeworksh/widget/codework";
import { type Info, Json, topics } from "./schema";
import { type Info, Json, type ThreadRef, topics } from "./schema";

const decodeReply = Schema.decodeUnknownOption(Json.Reply);
const encodePrompt = Schema.encodeSync(Json.Prompt);
Expand All @@ -25,18 +25,18 @@ const unreachable = "The CodeWork server is not reachable.";
* an id the view chooses for the user message it becomes; the message itself arrives as an update.
* The text stays until the backend accepts it, and the unsent draft survives a remount.
*
* The model and reasoning pickers show the session's own choice, which CodeWork keeps with the
* session; a pick shows at once and is sent as a configure request, applying from the next exchange.
* The model and reasoning pickers show the thread's own choice, which CodeWork keeps with the
* thread; a pick shows at once and is sent as a configure request, applying from the next exchange.
*/
export function SessionComposer({
sessionId,
thread,
instanceId,
running,
info,
onError,
restored,
}: {
readonly sessionId: string;
readonly thread: ThreadRef;
readonly instanceId: string;
readonly running: boolean;
readonly info: Info;
Expand Down Expand Up @@ -164,7 +164,7 @@ export function SessionComposer({
const sent = await ask(
topics.prompt,
encodePrompt({
sessionId,
...thread,
messageId: crypto.randomUUID(),
text: prompt,
...(delivery === undefined ? {} : { delivery }),
Expand All @@ -176,7 +176,7 @@ export function SessionComposer({

const configure = (change: { model?: ModelRef; thinkingLevel?: ThinkingLevel }) => {
setPicked((current) => ({ ...current, ...change }));
void ask(topics.configure, encodeConfigure({ sessionId, ...change }));
void ask(topics.configure, encodeConfigure({ ...thread, ...change }));
};

const empty = text.trim() === "";
Expand Down Expand Up @@ -230,7 +230,7 @@ export function SessionComposer({
actions={
<>
{running && (
<ComposerButton label="Stop" onClick={() => void ask(topics.interrupt, { sessionId })}>
<ComposerButton label="Stop" onClick={() => void ask(topics.interrupt, { ...thread })}>
<Square className="size-3" fill="currentColor" strokeWidth={0} aria-hidden />
</ComposerButton>
)}
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/widgets/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { MessageSquare } from "lucide-react";

import { Session } from "./view";

/** One session's conversation, opened by its `codework://session/<id>` address. */
/** One thread's conversation: `codework://session/<id>` for a session's main thread, `…/<id>/<thread>` for another. */
export const session = defineWidget({
kind: "codework:session",
title: "Session",
Expand All @@ -13,7 +13,7 @@ export const session = defineWidget({
minHeight: 200,
cardinality: "many",
priority: "builtin",
opens: ["codework://session/*"],
opens: ["codework://session/*", "codework://session/*/*"],
ownsTab: true,
replaceable: true,
props: Schema.Struct({}),
Expand Down
10 changes: 5 additions & 5 deletions apps/web/src/widgets/session/queue.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Option, Schema } from "effect";
import { CornerDownRight, ListEnd, type LucideIcon, Pencil, SendHorizontal, Trash2, Undo2 } from "lucide-react";
import { useRef, useState } from "react";

import { Json, topics } from "./schema";
import { Json, type ThreadRef, topics } from "./schema";

const decodeReply = Schema.decodeUnknownOption(Json.Reply);
const decodeCancelled = Schema.decodeUnknownOption(Json.Cancelled);
Expand All @@ -21,13 +21,13 @@ const unreachable = "The CodeWork server is not reachable.";
* the queue next updates.
*/
export function Queue({
sessionId,
thread,
queued,
running,
onError,
onRestore,
}: {
readonly sessionId: string;
readonly thread: ThreadRef;
readonly queued: readonly QueuedPrompt[];
readonly running: boolean;
readonly onError: (message: string | undefined) => void;
Expand Down Expand Up @@ -70,7 +70,7 @@ export function Queue({
act(prompt.id, async () => {
const answer = await bus.request({
topic: topics.change,
payload: { sessionId, messageId: prompt.id, ...patch },
payload: { ...thread, messageId: prompt.id, ...patch },
});
const reply = decodeReply(answer.payload);
if (Option.isSome(reply) && reply.value._tag === "Failed") onError(reply.value.message);
Expand All @@ -79,7 +79,7 @@ export function Queue({
// Undo restores only what it took back: a prompt the agent already took in stays in the conversation.
const cancel = (prompt: QueuedPrompt, restore: boolean) =>
act(prompt.id, async () => {
const answer = await bus.request({ topic: topics.cancel, payload: { sessionId, messageId: prompt.id } });
const answer = await bus.request({ topic: topics.cancel, payload: { ...thread, messageId: prompt.id } });
const reply = Option.getOrUndefined(decodeCancelled(answer.payload));
if (reply?._tag === "Failed") onError(reply.message);
else if (reply?._tag === "Cancelled" && restore) onRestore(prompt.text);
Expand Down
41 changes: 26 additions & 15 deletions apps/web/src/widgets/session/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,43 @@ import { Schema } from "effect";
* halves import this file, so it stays free of React and the DOM.
*/

/** A thread of a session: `threadId`, or the session's main thread when absent. */
export const ThreadRef = Schema.Struct({ sessionId: Schema.String, threadId: Schema.optionalKey(Schema.String) });
export type ThreadRef = typeof ThreadRef.Type;

/**
* What names a thread in addresses, topics and kv: its session's id for the main thread, else
* `<session>/<thread>`. The main thread is never named by its own id, so it has one key.
*/
export const threadKey = ({ sessionId, threadId }: ThreadRef) =>
threadId === undefined ? sessionId : `${sessionId}/${threadId}`;

export const topics = {
/** Requests: start following a session; answered once its snapshot is stored. */
/** Requests: start following a thread; answered once its snapshot is stored. */
follow: "codework/session.follow",
/** Requests: create a session and send its first prompt; answered with its id. */
create: "codework/session.create",
prompt: "codework/session.prompt",
/** Requests: choose a session's model or thinking level; they apply from its next turn. */
/** Requests: choose a thread's model or thinking level; they apply from its next turn. */
configure: "codework/session.configure",
interrupt: "codework/session.interrupt",
/** Requests: withdraw a queued prompt before the agent takes it in; answered with `Cancelled`. */
cancel: "codework/session.cancel",
/** Requests: move a queued prompt to the other lane, or rewrite it, in place. */
change: "codework/session.change",
/** Requests: a window of a followed session's conversation, newest first back from `before`. */
/** Requests: a window of a followed thread's conversation, newest first back from `before`. */
page: "codework/session.page",
/** Updates to one session's conversation. */
session: (id: string) => `codework/session/${id}`,
/** Updates to one thread's conversation, by its {@link threadKey}. */
thread: (key: string) => `codework/session/${key}`,
};

/** The kv key of a session's snapshot. */
export const snapshotKey = (id: string) => `session/${id}`;
/** The kv key of a thread's snapshot, by its {@link threadKey}. */
export const snapshotKey = (key: string) => `session/${key}`;

export const Follow = Schema.Struct({ sessionId: Schema.String });
export const Follow = ThreadRef;

export const Prompt = Schema.Struct({
sessionId: Schema.String,
...ThreadRef.fields,
/** Chosen by the view: the id of the user message this prompt becomes. */
messageId: Schema.String,
text: Schema.String,
Expand Down Expand Up @@ -65,9 +76,9 @@ export const Created = Schema.Union([
]);
export type Created = typeof Created.Type;

export const Interrupt = Schema.Struct({ sessionId: Schema.String });
export const Interrupt = ThreadRef;

export const Cancel = Schema.Struct({ sessionId: Schema.String, messageId: Schema.String });
export const Cancel = Schema.Struct({ ...ThreadRef.fields, messageId: Schema.String });

/** The answer to a cancel: withdrawn, already in the conversation, or why neither is known. */
export const Cancelled = Schema.Union([
Expand All @@ -79,22 +90,22 @@ export type Cancelled = typeof Cancelled.Type;

/** A queued prompt moved to `delivery`, or given new `text`; an absent key is left as it is. */
export const Change = Schema.Struct({
sessionId: Schema.String,
...ThreadRef.fields,
messageId: Schema.String,
delivery: Schema.optionalKey(Delivery),
text: Schema.optionalKey(Schema.String),
});

/** A model or thinking level chosen for a session; an absent key is left as it is. */
/** A model or thinking level chosen for a thread; an absent key is left as it is. */
export const Configure = Schema.Struct({
sessionId: Schema.String,
...ThreadRef.fields,
model: Schema.optionalKey(Schema.Struct({ provider: Schema.String, id: Schema.String })),
thinkingLevel: Schema.optionalKey(ThinkingLevel),
});
export type Configure = typeof Configure.Type;

export const Page = Schema.Struct({
sessionId: Schema.String,
...ThreadRef.fields,
/** The oldest message the view holds; omitted asks for the newest messages. */
before: Schema.optionalKey(Schema.String),
limit: Schema.Int,
Expand Down
36 changes: 18 additions & 18 deletions apps/web/src/widgets/session/view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import { memo, type ReactNode, useCallback, useEffect, useMemo, useRef, useState
import { ComposerNotice, type Notice } from "@/components/banner";
import { Monogram } from "@/components/monogram";
import { useModelsNotice } from "@/components/model";
import { sessionId } from "./address";
import { threadRef } from "./address";
import { SessionComposer } from "./composer";
import { Markdown } from "./markdown";
import { Message } from "./message";
import { Queue } from "./queue";
import { useListedSession } from "./projects";
import { type Info, Json, topics, type Update } from "./schema";
import { type Info, Json, type ThreadRef, threadKey, topics, type Update } from "./schema";

const decodeReply = Schema.decodeUnknownOption(Json.Reply);
const decodeWindow = Schema.decodeUnknownOption(Json.Window);
Expand All @@ -27,9 +27,9 @@ const PAGE = 60;
const contentWidth = "mx-auto w-full max-w-[62rem]";

export function Session({ address, instanceId }: WidgetProps<unknown>) {
const id = sessionId(address);
if (id === undefined) return <p className="p-3 text-ink-muted">Not a session: {address}</p>;
return <Conversation key={id} id={id} instanceId={instanceId} />;
const thread = useMemo(() => threadRef(address), [address]);
if (thread === undefined) return <p className="p-3 text-ink-muted">Not a session: {address}</p>;
return <Conversation key={threadKey(thread)} thread={thread} instanceId={instanceId} />;
}

type State =
Expand Down Expand Up @@ -106,11 +106,11 @@ const apply = (state: State, update: Update): State => {
};

/**
* Asks the session backend to follow the session, loads its newest page, then applies every update
* Asks the session backend to follow the thread, loads its newest page, then applies every update
* published after that page. Older pages load on demand. A dropped connection resumes where it
* left off.
*/
function useConversation(id: string) {
function useConversation(thread: ThreadRef) {
const bus = useBus();
const [state, setState] = useState<State>({ status: "loading" });
const paging = useRef(false);
Expand All @@ -121,13 +121,13 @@ function useConversation(id: string) {
(
await bus.request({
topic: topics.page,
payload: { sessionId: id, limit: PAGE, ...(before === undefined ? {} : { before }) },
payload: { ...thread, limit: PAGE, ...(before === undefined ? {} : { before }) },
})
).payload,
);
return Option.getOrUndefined(reply);
},
[bus, id],
[bus, thread],
);

useEffect(() => {
Expand All @@ -136,21 +136,21 @@ function useConversation(id: string) {
if (active) setState({ status: "failed", message });
};
void (async () => {
const reply = decodeReply((await bus.request({ topic: topics.follow, payload: { sessionId: id } })).payload);
const reply = decodeReply((await bus.request({ topic: topics.follow, payload: thread })).payload);
if (Option.isSome(reply) && reply.value._tag === "Failed") return fail(reply.value.message);
const window = await page(undefined);
if (window === undefined) return fail(`Could not load session ${id}.`);
if (window === undefined) return fail(`Could not load session ${threadKey(thread)}.`);
if (window._tag === "Failed") return fail(window.message);
const { info, messages, more, queued, seq } = window;
if (active) setState({ status: "ready", info, messages, more, queued, after: seq, running: undefined });
})().catch(() => fail("The CodeWork server is not reachable."));
return () => {
active = false;
};
}, [bus, id, page]);
}, [bus, thread, page]);

const after = state.status === "ready" ? state.after : undefined;
useEvents(after === undefined ? undefined : { topics: [topics.session(id)], after }, (item) => {
useEvents(after === undefined ? undefined : { topics: [topics.thread(threadKey(thread))], after }, (item) => {
if ("_tag" in item) return;
const update = decodeUpdate(item.payload);
if (Option.isSome(update)) setState((current) => apply(current, update.value));
Expand Down Expand Up @@ -178,11 +178,11 @@ function useConversation(id: string) {
return { state, loadOlder };
}

function Conversation({ id, instanceId }: { readonly id: string; readonly instanceId: string }) {
function Conversation({ thread, instanceId }: { readonly thread: ThreadRef; readonly instanceId: string }) {
const { setTitle, setIcon, setTab } = useFrame();
const { state, loadOlder } = useConversation(id);
const { state, loadOlder } = useConversation(thread);
// Named from the sessions list at once, so the frame never shows its default title while loading.
const listed = useListedSession(id);
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;
const projectId = project?.id;
Expand Down Expand Up @@ -253,15 +253,15 @@ function Conversation({ id, instanceId }: { readonly id: string; readonly instan
{/* Idle too: prompts left waiting by a stop or a failure run with the next message, so they stay in view. */}
{state.queued.length > 0 && (
<Queue
sessionId={id}
thread={thread}
queued={state.queued}
running={running}
onError={setSendError}
onRestore={(text) => setRestored((current) => ({ text, key: (current?.key ?? 0) + 1 }))}
/>
)}
<SessionComposer
sessionId={id}
thread={thread}
instanceId={instanceId}
running={running}
info={state.info}
Expand Down
Loading
Loading