-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathworkspace.ts
More file actions
209 lines (201 loc) · 6.41 KB
/
Copy pathworkspace.ts
File metadata and controls
209 lines (201 loc) · 6.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { existsSync } from "node:fs";
import { basename } from "node:path";
import { TRPCError } from "@trpc/server";
import { eq, isNull } from "drizzle-orm";
import { z } from "zod";
import { projects, workspaces } from "../../../db/schema";
import {
toCloudShape,
updateLocalWorkspace,
} from "../../../workspaces/local-workspace-store";
import {
repairMovedWorktree,
validateWorktreePathUpdate,
} from "../../../workspaces/moved-worktree";
import { protectedProcedure, router } from "../../index";
import { resolveWorktreePath } from "../git/utils/resolve-worktree";
import { destroyWorkspace } from "../workspace-cleanup";
export const workspaceRouter = router({
get: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const stored = ctx.db.query.workspaces
.findFirst({ where: eq(workspaces.id, input.id) })
.sync();
if (!stored) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Workspace not found",
});
}
const localWorkspace = await repairMovedWorktree(ctx, stored);
return {
...localWorkspace,
worktreeExists: existsSync(localWorkspace.worktreePath),
};
}),
/**
* Authoritative list of this host's workspaces, served entirely from
* host.db — works with zero cloud availability. Rows are shaped like
* cloud rows (plus local extras) so consumers of either read path agree.
* Archived (tombstoned) rows are excluded unless the caller opts in —
* only the workspaces board does, for its Merged/Deleted columns.
*/
list: protectedProcedure
.input(z.object({ includeArchived: z.boolean().default(false) }).optional())
.query(({ ctx, input }) => {
const rows = input?.includeArchived
? ctx.db.select().from(workspaces).all()
: ctx.db
.select()
.from(workspaces)
.where(isNull(workspaces.archivedAt))
.all();
const projectNameById = new Map(
ctx.db
.select({
id: projects.id,
name: projects.name,
repoPath: projects.repoPath,
})
.from(projects)
.all()
.map((project) => [
project.id,
project.name || basename(project.repoPath),
]),
);
return rows.map((row) => ({
...toCloudShape(row, ctx.organizationId),
worktreePath: row.worktreePath,
// Tombstones' worktrees are gone by definition; stat-checking an
// unbounded, forever-growing archive on every poll adds up.
worktreeExists:
row.archivedAt == null ? existsSync(row.worktreePath) : false,
projectName: row.projectId
? (projectNameById.get(row.projectId) ?? null)
: null,
archivedAt: row.archivedAt,
archiveReason: row.archiveReason,
}));
}),
/**
* Rename / branch-repoint / task-link update, local-first: the host.db
* row commits and broadcasts immediately; the cloud mirror push is
* best-effort (the reconciler retries when unreachable). `branch` only
* re-points the record — callers rename the git branch themselves.
* `worktreePath` re-points a workspace whose worktree was moved on disk;
* the path must be a worktree of the project on the workspace's branch.
*/
update: protectedProcedure
.input(
z.object({
id: z.string().uuid(),
name: z.string().min(1).optional(),
branch: z.string().min(1).optional(),
taskId: z.string().uuid().nullable().optional(),
worktreePath: z.string().min(1).optional(),
}),
)
.mutation(async ({ ctx, input }) => {
const current = ctx.db.query.workspaces
.findFirst({ where: eq(workspaces.id, input.id) })
.sync();
if (!current) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Workspace not found",
});
}
if (input.name !== undefined && current.type === "main") {
throw new TRPCError({
code: "BAD_REQUEST",
message:
'The local workspace cannot be renamed — it always displays as "local".',
});
}
const patch: {
name?: string;
branch?: string;
taskId?: string | null;
worktreePath?: string;
} = {};
if (input.name !== undefined) patch.name = input.name;
if (input.branch !== undefined) patch.branch = input.branch;
if (input.taskId !== undefined) patch.taskId = input.taskId;
if (input.worktreePath !== undefined) {
const validated = await validateWorktreePathUpdate(
ctx,
current,
input.worktreePath,
);
if (!validated.ok) {
throw new TRPCError({
code: "BAD_REQUEST",
message: validated.message,
});
}
patch.worktreePath = validated.worktreePath;
}
if (Object.keys(patch).length === 0) {
return toCloudShape(current, ctx.organizationId);
}
const updated = updateLocalWorkspace(
{ db: ctx.db, eventBus: ctx.eventBus },
input.id,
patch,
);
if (!updated) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Workspace not found",
});
}
// Linking a task to a workspace starts work on it — move it to
// In Progress. Best-effort cloud call; the update never blocks.
if (typeof input.taskId === "string") {
const taskId = input.taskId;
void ctx.api.task.start.mutate({ id: taskId }).catch((err) => {
console.warn(
`[workspace.update] failed to mark task ${taskId} as started:`,
err,
);
});
}
return toCloudShape(updated, ctx.organizationId);
}),
// Workspaces are host-owned now; the cloud list it proxied is gone. Kept as
// an empty read so released clients that still call it don't error.
gitStatus: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const worktreePath = resolveWorktreePath(ctx, input.id);
const git = await ctx.git(worktreePath);
const status = await git.status();
return {
workspaceId: input.id,
branch: status.current,
files: status.files.map((f) => ({
path: f.path,
index: f.index,
workingDir: f.working_dir,
})),
isClean: status.isClean(),
};
}),
delete: protectedProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
// Legacy external surface used by CLI/SDK/MCP. Preserve its
// non-interactive contract while reusing the v2 cleanup path:
// force covers the git semantics (no dirty-worktree prompt), but
// teardown still runs — a failure lands in `warnings` since there
// is nobody to prompt for a force-retry (#6174).
return destroyWorkspace(ctx, {
workspaceId: input.id,
deleteBranch: false,
force: true,
teardownMode: "best-effort",
});
}),
});