Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67e3f2c7d5 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d |
No files matched your search
@@ -2,18 +2,42 @@
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## How to use
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
> T3 Code currently supports Codex and Claude.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||
> - Claude: install Claude Code and run `claude auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
```
|
||||
|
||||
You can also just install the desktop app. It's cooler.
|
||||
### Desktop app
|
||||
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
|
||||
#### Windows (`winget`)
|
||||
|
||||
```bash
|
||||
winget install T3Tools.T3Code
|
||||
```
|
||||
|
||||
#### macOS (Homebrew)
|
||||
|
||||
```bash
|
||||
brew install --cask t3-code
|
||||
```
|
||||
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
|
||||
## Some notes
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -14,47 +14,81 @@ import {
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalSessionStatus,
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { PtyProcess } from "./PTY";
|
||||
import { Effect, Schema, ServiceMap } from "effect";
|
||||
|
||||
export class TerminalError extends Schema.TaggedErrorClass<TerminalError>()("TerminalError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
export interface TerminalSessionState {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
process: PtyProcess | null;
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
|
||||
"TerminalCwdError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
if (this.reason === "notDirectory") {
|
||||
return `Terminal cwd is not a directory: ${this.cwd}`;
|
||||
}
|
||||
if (this.reason === "notFound") {
|
||||
return `Terminal cwd does not exist: ${this.cwd}`;
|
||||
}
|
||||
const causeMessage =
|
||||
this.cause && typeof this.cause === "object" && "message" in this.cause
|
||||
? this.cause.message
|
||||
: undefined;
|
||||
return causeMessage
|
||||
? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
|
||||
: `Failed to access terminal cwd: ${this.cwd}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ShellCandidate {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
export class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(
|
||||
"TerminalHistoryError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "truncate", "migrate"]),
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TerminalStartInput extends TerminalOpenInput {
|
||||
cols: number;
|
||||
rows: number;
|
||||
export class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(
|
||||
"TerminalSessionLookupError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(
|
||||
"TerminalNotRunningError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const TerminalError = Schema.Union([
|
||||
TerminalCwdError,
|
||||
TerminalHistoryError,
|
||||
TerminalSessionLookupError,
|
||||
TerminalNotRunningError,
|
||||
]);
|
||||
export type TerminalError = typeof TerminalError.Type;
|
||||
|
||||
/**
|
||||
* TerminalManagerShape - Service API for terminal session lifecycle operations.
|
||||
*/
|
||||
@@ -101,14 +135,13 @@ export interface TerminalManagerShape {
|
||||
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
|
||||
|
||||
/**
|
||||
* Subscribe to terminal runtime events.
|
||||
* Subscribe to terminal runtime events with a direct callback.
|
||||
*
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
|
||||
|
||||
/**
|
||||
* Dispose all managed terminal resources.
|
||||
*/
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
readonly subscribe: (
|
||||
listener: (event: TerminalEvent) => Effect.Effect<void>,
|
||||
) => Effect.Effect<() => void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
@@ -90,20 +90,19 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
|
||||
private activeSubscriptions = 0;
|
||||
|
||||
private key(threadId: string, terminalId: string): string {
|
||||
return `${threadId}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
emitEvent(event: TerminalEvent): void {
|
||||
for (const listener of this.listeners) {
|
||||
listener(event);
|
||||
}
|
||||
Effect.runSync(PubSub.publish(this.eventPubSub, event));
|
||||
}
|
||||
|
||||
subscriptionCount(): number {
|
||||
return this.listeners.size;
|
||||
return this.activeSubscriptions;
|
||||
}
|
||||
|
||||
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
|
||||
@@ -210,13 +209,15 @@ class MockTerminalManager implements TerminalManagerShape {
|
||||
|
||||
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
|
||||
Effect.sync(() => {
|
||||
this.listeners.add(listener);
|
||||
this.activeSubscriptions += 1;
|
||||
const fiber = Effect.runFork(
|
||||
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
|
||||
);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
this.activeSubscriptions -= 1;
|
||||
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
|
||||
};
|
||||
});
|
||||
|
||||
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1454,19 +1455,25 @@ describe("WebSocket Server", () => {
|
||||
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
|
||||
});
|
||||
|
||||
it("detaches terminal event listener on stop for injected manager", async () => {
|
||||
it("shuts down cleanly for injected terminal managers", async () => {
|
||||
const terminalManager = new MockTerminalManager();
|
||||
server = await createTestServer({
|
||||
cwd: "/test",
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
expect(terminalManager.subscriptionCount()).toBe(1);
|
||||
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
|
||||
expect(terminalManager.subscriptionCount()).toBe(0);
|
||||
expect(() =>
|
||||
terminalManager.emitEvent({
|
||||
type: "output",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: "after shutdown\n",
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("returns validation errors for invalid terminal open params", async () => {
|
||||
|
||||
@@ -719,9 +719,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
}
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
|
||||
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
|
||||
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
|
||||
yield* readiness.markTerminalSubscriptionsReady;
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
|
||||
@@ -553,6 +553,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
...defaultModelSelection,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
scripts: [],
|
||||
@@ -884,8 +885,8 @@ describe("sortProjectsForSidebar", () => {
|
||||
|
||||
it("preserves manual project ordering", () => {
|
||||
const projects = [
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First" }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second", pinned: true }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First", pinned: false }),
|
||||
];
|
||||
|
||||
const sorted = sortProjectsForSidebar(projects, [], "manual");
|
||||
@@ -896,6 +897,58 @@ describe("sortProjectsForSidebar", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps pinned projects ahead of unpinned projects in auto sort modes", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Unpinned newer",
|
||||
pinned: false,
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-2"),
|
||||
name: "Pinned older",
|
||||
pinned: true,
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
],
|
||||
[],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("still sorts pinned projects relative to each other by the active auto sort", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Pinned older",
|
||||
pinned: true,
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-2"),
|
||||
name: "Pinned newer",
|
||||
pinned: true,
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
],
|
||||
[],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores archived threads when sorting projects", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
|
||||
@@ -14,6 +14,7 @@ export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
name: string;
|
||||
pinned: boolean;
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
@@ -486,6 +487,8 @@ export function sortProjectsForSidebar<TProject extends SidebarProject, TThread
|
||||
}
|
||||
|
||||
return [...projects].toSorted((left, right) => {
|
||||
const byPinned = Number(right.pinned) - Number(left.pinned);
|
||||
if (byPinned !== 0) return byPinned;
|
||||
const rightTimestamp = getProjectSortTimestamp(
|
||||
right,
|
||||
threadsByProjectId.get(right.id) ?? [],
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
PinIcon,
|
||||
PlusIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
@@ -364,6 +365,7 @@ export default function Sidebar() {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const toggleProjectPinned = useStore((store) => store.toggleProjectPinned);
|
||||
const reorderProjects = useStore((store) => store.reorderProjects);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
@@ -909,11 +911,16 @@ export default function Sidebar() {
|
||||
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "toggle-pin", label: project.pinned ? "Unpin project" : "Pin project" },
|
||||
{ id: "copy-path", label: "Copy Project Path" },
|
||||
{ id: "delete", label: "Remove project", destructive: true },
|
||||
],
|
||||
position,
|
||||
);
|
||||
if (clicked === "toggle-pin") {
|
||||
toggleProjectPinned(projectId);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
copyPathToClipboard(project.cwd, { path: project.cwd });
|
||||
return;
|
||||
@@ -961,6 +968,7 @@ export default function Sidebar() {
|
||||
getDraftThreadByProjectId,
|
||||
projects,
|
||||
threads,
|
||||
toggleProjectPinned,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1559,6 +1567,12 @@ export default function Sidebar() {
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
{project.pinned ? (
|
||||
<PinIcon
|
||||
aria-hidden="true"
|
||||
className="size-3 shrink-0 rotate-45 text-muted-foreground/55"
|
||||
/>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
|
||||
@@ -7,7 +7,13 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
|
||||
import {
|
||||
markThreadUnread,
|
||||
reorderProjects,
|
||||
syncServerReadModel,
|
||||
toggleProjectPinned,
|
||||
type AppState,
|
||||
} from "./store";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
@@ -49,6 +55,7 @@ function makeState(thread: Thread): AppState {
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
@@ -181,6 +188,7 @@ describe("store pure functions", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
@@ -192,6 +200,7 @@ describe("store pure functions", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
@@ -203,6 +212,7 @@ describe("store pure functions", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
@@ -214,6 +224,16 @@ describe("store pure functions", () => {
|
||||
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]);
|
||||
});
|
||||
|
||||
it("toggleProjectPinned flips the pinned flag for the selected project", () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const initialState = makeState(makeThread());
|
||||
|
||||
const next = toggleProjectPinned(initialState, projectId);
|
||||
|
||||
expect(next.projects[0]?.pinned).toBe(true);
|
||||
expect(initialState.projects[0]?.pinned).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store read model sync", () => {
|
||||
@@ -302,6 +322,7 @@ describe("store read model sync", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: true,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
@@ -313,6 +334,7 @@ describe("store read model sync", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
@@ -345,5 +367,6 @@ describe("store read model sync", () => {
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
|
||||
expect(next.projects.map((project) => project.pinned)).toEqual([true, false, false]);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ const initialState: AppState = {
|
||||
threadsHydrated: false,
|
||||
};
|
||||
const persistedExpandedProjectCwds = new Set<string>();
|
||||
const persistedPinnedProjectCwds = new Set<string>();
|
||||
const persistedProjectOrderCwds: string[] = [];
|
||||
|
||||
// ── Persist helpers ──────────────────────────────────────────────────
|
||||
@@ -48,15 +49,22 @@ function readPersistedState(): AppState {
|
||||
if (!raw) return initialState;
|
||||
const parsed = JSON.parse(raw) as {
|
||||
expandedProjectCwds?: string[];
|
||||
pinnedProjectCwds?: string[];
|
||||
projectOrderCwds?: string[];
|
||||
};
|
||||
persistedExpandedProjectCwds.clear();
|
||||
persistedPinnedProjectCwds.clear();
|
||||
persistedProjectOrderCwds.length = 0;
|
||||
for (const cwd of parsed.expandedProjectCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0) {
|
||||
persistedExpandedProjectCwds.add(cwd);
|
||||
}
|
||||
}
|
||||
for (const cwd of parsed.pinnedProjectCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0) {
|
||||
persistedPinnedProjectCwds.add(cwd);
|
||||
}
|
||||
}
|
||||
for (const cwd of parsed.projectOrderCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
|
||||
persistedProjectOrderCwds.push(cwd);
|
||||
@@ -79,6 +87,9 @@ function persistState(state: AppState): void {
|
||||
expandedProjectCwds: state.projects
|
||||
.filter((project) => project.expanded)
|
||||
.map((project) => project.cwd),
|
||||
pinnedProjectCwds: state.projects
|
||||
.filter((project) => project.pinned)
|
||||
.map((project) => project.cwd),
|
||||
projectOrderCwds: state.projects.map((project) => project.cwd),
|
||||
}),
|
||||
);
|
||||
@@ -148,6 +159,7 @@ function mapProjectsFromReadModel(
|
||||
(persistedExpandedProjectCwds.size > 0
|
||||
? persistedExpandedProjectCwds.has(project.workspaceRoot)
|
||||
: true),
|
||||
pinned: existing?.pinned ?? persistedPinnedProjectCwds.has(project.workspaceRoot),
|
||||
createdAt: project.createdAt,
|
||||
updatedAt: project.updatedAt,
|
||||
scripts: project.scripts.map((script) => ({ ...script })),
|
||||
@@ -379,6 +391,16 @@ export function setProjectExpanded(
|
||||
return changed ? { ...state, projects } : state;
|
||||
}
|
||||
|
||||
export function toggleProjectPinned(state: AppState, projectId: Project["id"]): AppState {
|
||||
let changed = false;
|
||||
const projects = state.projects.map((project) => {
|
||||
if (project.id !== projectId) return project;
|
||||
changed = true;
|
||||
return { ...project, pinned: !project.pinned };
|
||||
});
|
||||
return changed ? { ...state, projects } : state;
|
||||
}
|
||||
|
||||
export function reorderProjects(
|
||||
state: AppState,
|
||||
draggedProjectId: Project["id"],
|
||||
@@ -429,6 +451,7 @@ interface AppStore extends AppState {
|
||||
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
|
||||
markThreadUnread: (threadId: ThreadId) => void;
|
||||
toggleProject: (projectId: Project["id"]) => void;
|
||||
toggleProjectPinned: (projectId: Project["id"]) => void;
|
||||
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
|
||||
reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void;
|
||||
setError: (threadId: ThreadId, error: string | null) => void;
|
||||
@@ -442,6 +465,7 @@ export const useStore = create<AppStore>((set) => ({
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)),
|
||||
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
|
||||
toggleProjectPinned: (projectId) => set((state) => toggleProjectPinned(state, projectId)),
|
||||
setProjectExpanded: (projectId, expanded) =>
|
||||
set((state) => setProjectExpanded(state, projectId, expanded)),
|
||||
reorderProjects: (draggedProjectId, targetProjectId) =>
|
||||
|
||||
@@ -83,6 +83,7 @@ export interface Project {
|
||||
cwd: string;
|
||||
defaultModelSelection: ModelSelection | null;
|
||||
expanded: boolean;
|
||||
pinned: boolean;
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
scripts: ProjectScript[];
|
||||
|
||||
@@ -130,12 +130,12 @@ export interface NativeApi {
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
};
|
||||
terminal: {
|
||||
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
|
||||
write: (input: TerminalWriteInput) => Promise<void>;
|
||||
resize: (input: TerminalResizeInput) => Promise<void>;
|
||||
clear: (input: TerminalClearInput) => Promise<void>;
|
||||
restart: (input: TerminalRestartInput) => Promise<TerminalSessionSnapshot>;
|
||||
close: (input: TerminalCloseInput) => Promise<void>;
|
||||
open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;
|
||||
write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;
|
||||
resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;
|
||||
clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;
|
||||
restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;
|
||||
close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;
|
||||
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
|
||||
};
|
||||
projects: {
|
||||
|
||||
@@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
|
||||
export const TerminalThreadInput = Schema.Struct({
|
||||
threadId: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type TerminalThreadInput = Schema.Codec.Encoded<typeof TerminalThreadInput>;
|
||||
export type TerminalThreadInput = typeof TerminalThreadInput.Type;
|
||||
|
||||
const TerminalSessionInput = Schema.Struct({
|
||||
...TerminalThreadInput.fields,
|
||||
@@ -73,7 +73,7 @@ export const TerminalCloseInput = Schema.Struct({
|
||||
terminalId: Schema.optional(TerminalIdSchema),
|
||||
deleteHistory: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type TerminalCloseInput = Schema.Codec.Encoded<typeof TerminalCloseInput>;
|
||||
export type TerminalCloseInput = typeof TerminalCloseInput.Type;
|
||||
|
||||
export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
|
||||
export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
|
||||
|
||||
@@ -28,6 +28,10 @@
|
||||
"types": "./src/DrainableWorker.ts",
|
||||
"import": "./src/DrainableWorker.ts"
|
||||
},
|
||||
"./KeyedCoalescingWorker": {
|
||||
"types": "./src/KeyedCoalescingWorker.ts",
|
||||
"import": "./src/KeyedCoalescingWorker.ts"
|
||||
},
|
||||
"./schemaJson": {
|
||||
"types": "./src/schemaJson.ts",
|
||||
"import": "./src/schemaJson.ts"
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { it } from "@effect/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
import { Deferred, Effect } from "effect";
|
||||
|
||||
import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker";
|
||||
|
||||
describe("makeKeyedCoalescingWorker", () => {
|
||||
it.live("waits for latest work enqueued during active processing before draining the key", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const processed: string[] = [];
|
||||
const firstStarted = yield* Deferred.make<void>();
|
||||
const releaseFirst = yield* Deferred.make<void>();
|
||||
const secondStarted = yield* Deferred.make<void>();
|
||||
const releaseSecond = yield* Deferred.make<void>();
|
||||
|
||||
const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
|
||||
merge: (_current, next) => next,
|
||||
process: (key, value) =>
|
||||
Effect.gen(function* () {
|
||||
processed.push(`${key}:${value}`);
|
||||
|
||||
if (value === "first") {
|
||||
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
|
||||
yield* Deferred.await(releaseFirst);
|
||||
}
|
||||
|
||||
if (value === "second") {
|
||||
yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
|
||||
yield* Deferred.await(releaseSecond);
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
yield* worker.enqueue("terminal-1", "first");
|
||||
yield* Deferred.await(firstStarted);
|
||||
|
||||
const drained = yield* Deferred.make<void>();
|
||||
yield* Effect.forkChild(
|
||||
worker
|
||||
.drainKey("terminal-1")
|
||||
.pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))),
|
||||
);
|
||||
|
||||
yield* worker.enqueue("terminal-1", "second");
|
||||
yield* Deferred.succeed(releaseFirst, undefined);
|
||||
yield* Deferred.await(secondStarted);
|
||||
|
||||
expect(yield* Deferred.isDone(drained)).toBe(false);
|
||||
|
||||
yield* Deferred.succeed(releaseSecond, undefined);
|
||||
yield* Deferred.await(drained);
|
||||
|
||||
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("requeues pending work for a key after a processor failure and keeps draining", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const processed: string[] = [];
|
||||
const firstStarted = yield* Deferred.make<void>();
|
||||
const releaseFailure = yield* Deferred.make<void>();
|
||||
const secondProcessed = yield* Deferred.make<void>();
|
||||
|
||||
const worker = yield* makeKeyedCoalescingWorker<string, string, string, never>({
|
||||
merge: (_current, next) => next,
|
||||
process: (key, value) =>
|
||||
Effect.gen(function* () {
|
||||
processed.push(`${key}:${value}`);
|
||||
|
||||
if (value === "first") {
|
||||
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
|
||||
yield* Deferred.await(releaseFailure);
|
||||
yield* Effect.fail("boom");
|
||||
}
|
||||
|
||||
if (value === "second") {
|
||||
yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
yield* worker.enqueue("terminal-1", "first");
|
||||
yield* Deferred.await(firstStarted);
|
||||
yield* worker.enqueue("terminal-1", "second");
|
||||
yield* Deferred.succeed(releaseFailure, undefined);
|
||||
yield* Deferred.await(secondProcessed);
|
||||
yield* worker.drainKey("terminal-1");
|
||||
|
||||
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key.
|
||||
*
|
||||
* Enqueues for an active or already-queued key are merged atomically instead of
|
||||
* creating duplicate queued items. `drainKey()` resolves only when that key has
|
||||
* no queued, pending, or active work left.
|
||||
*
|
||||
* @module KeyedCoalescingWorker
|
||||
*/
|
||||
import type { Scope } from "effect";
|
||||
import { Effect, TxQueue, TxRef } from "effect";
|
||||
|
||||
export interface KeyedCoalescingWorker<K, V> {
|
||||
readonly enqueue: (key: K, value: V) => Effect.Effect<void>;
|
||||
readonly drainKey: (key: K) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
interface KeyedCoalescingWorkerState<K, V> {
|
||||
readonly latestByKey: Map<K, V>;
|
||||
readonly queuedKeys: Set<K>;
|
||||
readonly activeKeys: Set<K>;
|
||||
}
|
||||
|
||||
export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
|
||||
readonly merge: (current: V, next: V) => V;
|
||||
readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
|
||||
}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
|
||||
const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
|
||||
latestByKey: new Map(),
|
||||
queuedKeys: new Set(),
|
||||
activeKeys: new Set(),
|
||||
});
|
||||
|
||||
const processKey = (key: K, value: V): Effect.Effect<void, E, R> =>
|
||||
options.process(key, value).pipe(
|
||||
Effect.flatMap(() =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const nextValue = state.latestByKey.get(key);
|
||||
if (nextValue === undefined) {
|
||||
const activeKeys = new Set(state.activeKeys);
|
||||
activeKeys.delete(key);
|
||||
return [null, { ...state, activeKeys }] as const;
|
||||
}
|
||||
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
latestByKey.delete(key);
|
||||
return [nextValue, { ...state, latestByKey }] as const;
|
||||
}).pipe(Effect.tx),
|
||||
),
|
||||
Effect.flatMap((nextValue) =>
|
||||
nextValue === null ? Effect.void : processKey(key, nextValue),
|
||||
),
|
||||
);
|
||||
|
||||
const cleanupFailedKey = (key: K): Effect.Effect<void> =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const activeKeys = new Set(state.activeKeys);
|
||||
activeKeys.delete(key);
|
||||
|
||||
if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
|
||||
const queuedKeys = new Set(state.queuedKeys);
|
||||
queuedKeys.add(key);
|
||||
return [true, { ...state, activeKeys, queuedKeys }] as const;
|
||||
}
|
||||
|
||||
return [false, { ...state, activeKeys }] as const;
|
||||
}).pipe(
|
||||
Effect.tx,
|
||||
Effect.flatMap((shouldRequeue) =>
|
||||
shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,
|
||||
),
|
||||
);
|
||||
|
||||
yield* TxQueue.take(queue).pipe(
|
||||
Effect.flatMap((key) =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const queuedKeys = new Set(state.queuedKeys);
|
||||
queuedKeys.delete(key);
|
||||
|
||||
const value = state.latestByKey.get(key);
|
||||
if (value === undefined) {
|
||||
return [null, { ...state, queuedKeys }] as const;
|
||||
}
|
||||
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
latestByKey.delete(key);
|
||||
const activeKeys = new Set(state.activeKeys);
|
||||
activeKeys.add(key);
|
||||
|
||||
return [
|
||||
{ key, value } as const,
|
||||
{ ...state, latestByKey, queuedKeys, activeKeys },
|
||||
] as const;
|
||||
}).pipe(Effect.tx),
|
||||
),
|
||||
Effect.flatMap((item) =>
|
||||
item === null
|
||||
? Effect.void
|
||||
: processKey(item.key, item.value).pipe(
|
||||
Effect.catchCause(() => cleanupFailedKey(item.key)),
|
||||
),
|
||||
),
|
||||
Effect.forever,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
const existing = latestByKey.get(key);
|
||||
latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
|
||||
|
||||
if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
|
||||
return [false, { ...state, latestByKey }] as const;
|
||||
}
|
||||
|
||||
const queuedKeys = new Set(state.queuedKeys);
|
||||
queuedKeys.add(key);
|
||||
return [true, { ...state, latestByKey, queuedKeys }] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
|
||||
Effect.tx,
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>
|
||||
TxRef.get(stateRef).pipe(
|
||||
Effect.tap((state) =>
|
||||
state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
|
||||
? Effect.txRetry
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.asVoid,
|
||||
Effect.tx,
|
||||
);
|
||||
|
||||
return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;
|
||||
});
|
||||
Reference in new issue
Block a user