-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathannotate.ts
More file actions
232 lines (201 loc) · 6.83 KB
/
annotate.ts
File metadata and controls
232 lines (201 loc) · 6.83 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/**
* Annotate Server
*
* Provides a server for annotating arbitrary markdown files.
* Follows the same patterns as the review server but serves
* markdown content via /api/plan so the plan editor UI can
* render it without modifications.
*
* Environment variables:
* PLANNOTATOR_REMOTE - Set to "1" or "true" for remote/devcontainer mode
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
*/
import { isRemoteSession, getServerPort, getServerHostname } from "./remote";
import { getRepoInfo } from "./repo";
import { handleImage, handleUpload, handleServerReady, handleDraftSave, handleDraftLoad, handleDraftDelete } from "./shared-handlers";
import { handleDoc } from "./reference-handlers";
import { contentHash, deleteDraft } from "./draft";
import { dirname } from "path";
// Re-export utilities
export { isRemoteSession, getServerPort } from "./remote";
export { openBrowser } from "./browser";
export { handleServerReady as handleAnnotateServerReady } from "./shared-handlers";
// --- Types ---
export interface AnnotateServerOptions {
/** Markdown content of the file to annotate */
markdown: string;
/** Original file path (for display purposes) */
filePath: string;
/** HTML content to serve for the UI */
htmlContent: string;
/** Origin identifier for UI customization */
origin?: "opencode" | "claude-code" | "pi";
/** Whether URL sharing is enabled (default: true) */
sharingEnabled?: boolean;
/** Custom base URL for share links */
shareBaseUrl?: string;
/** Called when server starts with the URL, remote status, and port */
onReady?: (url: string, isRemote: boolean, port: number) => void;
}
export interface AnnotateServerResult {
/** The port the server is running on */
port: number;
/** The full URL to access the server */
url: string;
/** Whether running in remote mode */
isRemote: boolean;
/** Wait for user feedback submission */
waitForDecision: () => Promise<{
feedback: string;
annotations: unknown[];
}>;
/** Stop the server */
stop: () => void;
}
// --- Server Implementation ---
const MAX_RETRIES = 5;
const RETRY_DELAY_MS = 500;
/**
* Start the Annotate server
*
* Handles:
* - Remote detection and port configuration
* - API routes (/api/plan with mode:"annotate", /api/feedback)
* - Port conflict retries
*/
export async function startAnnotateServer(
options: AnnotateServerOptions
): Promise<AnnotateServerResult> {
const {
markdown,
filePath,
htmlContent,
origin,
sharingEnabled = true,
shareBaseUrl,
onReady,
} = options;
const isRemote = isRemoteSession();
const configuredPort = getServerPort();
const hostname = await getServerHostname();
const draftKey = contentHash(markdown);
// Detect repo info (cached for this session)
const repoInfo = await getRepoInfo();
// Decision promise
let resolveDecision: (result: {
feedback: string;
annotations: unknown[];
}) => void;
const decisionPromise = new Promise<{
feedback: string;
annotations: unknown[];
}>((resolve) => {
resolveDecision = resolve;
});
// Start server with retry logic
let server: ReturnType<typeof Bun.serve> | null = null;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
server = Bun.serve({
port: configuredPort,
hostname: hostname !== "localhost" ? "0.0.0.0" : undefined,
async fetch(req) {
const url = new URL(req.url);
// API: Get plan content (reuse /api/plan so the plan editor UI works)
if (url.pathname === "/api/plan" && req.method === "GET") {
return Response.json({
plan: markdown,
origin,
mode: "annotate",
filePath,
sharingEnabled,
shareBaseUrl,
repoInfo,
});
}
// API: Serve images (local paths or temp uploads)
if (url.pathname === "/api/image") {
return handleImage(req);
}
// API: Serve a linked markdown document
// Inject source file's directory as base for relative path resolution
if (url.pathname === "/api/doc" && req.method === "GET") {
if (!url.searchParams.has("base")) {
const docUrl = new URL(req.url);
docUrl.searchParams.set("base", dirname(filePath));
return handleDoc(new Request(docUrl.toString()));
}
return handleDoc(req);
}
// API: Upload image -> save to temp -> return path
if (url.pathname === "/api/upload" && req.method === "POST") {
return handleUpload(req);
}
// API: Annotation draft persistence
if (url.pathname === "/api/draft") {
if (req.method === "POST") return handleDraftSave(req, draftKey);
if (req.method === "DELETE") return handleDraftDelete(draftKey);
return handleDraftLoad(draftKey);
}
// API: Submit annotation feedback
if (url.pathname === "/api/feedback" && req.method === "POST") {
try {
const body = (await req.json()) as {
feedback: string;
annotations: unknown[];
};
deleteDraft(draftKey);
resolveDecision({
feedback: body.feedback || "",
annotations: body.annotations || [],
});
return Response.json({ ok: true });
} catch (err) {
const message =
err instanceof Error
? err.message
: "Failed to process feedback";
return Response.json({ error: message }, { status: 500 });
}
}
// Serve embedded HTML for all other routes (SPA)
return new Response(htmlContent, {
headers: { "Content-Type": "text/html" },
});
},
});
break; // Success, exit retry loop
} catch (err: unknown) {
const isAddressInUse =
err instanceof Error && err.message.includes("EADDRINUSE");
if (isAddressInUse && attempt < MAX_RETRIES) {
await Bun.sleep(RETRY_DELAY_MS);
continue;
}
if (isAddressInUse) {
const hint = isRemote
? " (set PLANNOTATOR_PORT to use different port)"
: "";
throw new Error(
`Port ${configuredPort} in use after ${MAX_RETRIES} retries${hint}`
);
}
throw err;
}
}
if (!server) {
throw new Error("Failed to start server");
}
const serverUrl = `http://${hostname}:${server.port}`;
// Notify caller that server is ready
if (onReady) {
onReady(serverUrl, isRemote, server.port);
}
return {
port: server.port,
url: serverUrl,
isRemote,
waitForDecision: () => decisionPromise,
stop: () => server.stop(),
};
}