-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathrequest.ts
More file actions
441 lines (388 loc) · 12 KB
/
Copy pathrequest.ts
File metadata and controls
441 lines (388 loc) · 12 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
import { getApiUrl } from "./config";
import i18n from "../i18n";
const AUTH_TOKEN_KEY = "auth_token";
/** Response header used by the server for JWT sliding renewal. */
export const ACCESS_TOKEN_RESPONSE_HEADER = "X-Octop-Access-Token";
/** Save JWT token to localStorage */
export function setAuthToken(token: string) {
localStorage.setItem(AUTH_TOKEN_KEY, token);
}
/** Get JWT token from localStorage */
export function getAuthToken(): string {
return localStorage.getItem(AUTH_TOKEN_KEY) || "";
}
/** Remove JWT token from localStorage */
export function clearAuthToken() {
localStorage.removeItem(AUTH_TOKEN_KEY);
localStorage.removeItem("octop:active-agent");
setActiveAgentId(null);
}
/** Persist a sliding-renewed access token from an API response, if present. */
export function applyRenewedAccessToken(response: Response): void {
const renewed = response.headers.get(ACCESS_TOKEN_RESPONSE_HEADER);
if (renewed) {
setAuthToken(renewed);
}
}
let _redirectingToSetup = false;
/**
* Hard-redirect once when the backend reports the wizard isn't done.
* The flag prevents N parallel API calls from each issuing a navigate.
*/
function handleSetupRequired(): void {
if (_redirectingToSetup) return;
// Already on a public bootstrap route — a 503 from a background prefetch
// must not reload the page or we loop forever.
const path = window.location.pathname;
if (path.startsWith("/setup") || path.startsWith("/login")) {
return;
}
_redirectingToSetup = true;
// Full reload drops any in-flight React state.
window.location.replace("/setup");
}
/**
* Inspect a response for the lockdown signal (503 + body
* `{setup_required: true}`) and trigger a one-shot navigate to /setup.
*
* Returns ``true`` when the response matched and the caller should
* abort the normal success/error path. The wizard's own ``/setup/*``
* calls are exempt to avoid redirect loops.
*/
async function check503ForSetupRequired(
path: string,
response: Response,
): Promise<boolean> {
if (response.status !== 503) return false;
let body: unknown = null;
try {
body = await response.clone().json();
} catch {
/* not JSON — fall through to the standard error path. */
return false;
}
if (
body &&
typeof body === "object" &&
(body as Record<string, unknown>).setup_required === true
) {
if (!path.startsWith("/setup/")) {
handleSetupRequired();
}
return true;
}
return false;
}
/**
* Active agent id — populated by ``AgentProvider`` in ``context/AgentContext.tsx``
* whenever the user picks a new agent in the top-bar switcher. Stored at
* module scope so plain functions like ``request()`` can read it without
* threading a context through every call site.
*
* The value is ALSO mirrored to ``localStorage["octop:active-agent"]`` by
* the provider — but the source of truth at request time is this variable
* so reactions stay synchronous.
*/
let activeAgentId: string | null = null;
/** Setter used by AgentProvider; also clears when ``null``. */
export function setActiveAgentId(id: string | null) {
activeAgentId = id;
}
/** Read the active agent id (e.g. from non-React code). */
export function getActiveAgentId(): string | null {
return activeAgentId;
}
/**
* Decide whether a request path is "agent-scoped" — i.e. talking to a
* concrete agent's resource — and therefore should carry the
* ``X-Octop-Agent-Id`` header. Health, admin, auth, setup, providers, and
* personas don't need it.
*/
function isAgentScopedPath(path: string): boolean {
// Match `/agents/<id>/...` (one trailing segment after the id).
// The path passed to request() is stripped of the /api prefix.
if (/^\/agents\/[^/]+(\/|$)/.test(path)) return true;
// MBTI endpoints that read/write the active agent's persona config.
if (/^\/mbti\//.test(path)) return true;
return false;
}
function buildHeaders(path: string, extra?: HeadersInit): HeadersInit {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Accept-Language": i18n.language?.startsWith("zh") ? "zh" : "en",
};
// Apply the global JWT first; the caller's `extra` (including a
// wizard token) can still override it below.
const token = getAuthToken();
if (token) {
headers.Authorization = `Bearer ${token}`;
}
// Caller-supplied headers win — needed so the setup wizard can pass
// its short-TTL Bearer without being stomped by a stale localStorage
// JWT.
if (extra) {
const extraEntries =
extra instanceof Headers
? Array.from(extra.entries())
: Array.isArray(extra)
? extra
: Object.entries(extra);
for (const [k, v] of extraEntries) {
headers[k] = String(v);
}
}
if (
activeAgentId &&
isAgentScopedPath(path) &&
!headers["X-Octop-Agent-Id"]
) {
headers["X-Octop-Agent-Id"] = activeAgentId;
}
return headers;
}
/**
* Build auth-only headers (no Content-Type — let the browser set it for FormData).
*/
function buildAuthHeaders(path: string): Record<string, string> {
const headers: Record<string, string> = {
"Accept-Language": i18n.language?.startsWith("zh") ? "zh" : "en",
};
const token = getAuthToken();
if (token) {
headers.Authorization = `Bearer ${token}`;
}
if (
activeAgentId &&
isAgentScopedPath(path) &&
!headers["X-Octop-Agent-Id"]
) {
headers["X-Octop-Agent-Id"] = activeAgentId;
}
return headers;
}
/**
* Handle 401 responses: clear token, redirect to login, and throw.
* Shared by request(), requestBlob(), and requestUpload().
*/
async function throwIfUnauthorized(
path: string,
response: Response,
): Promise<void> {
if (response.status !== 401 || path.startsWith("/auth/")) {
return;
}
clearAuthToken();
if (
!window.location.pathname.startsWith("/setup") &&
!window.location.pathname.startsWith("/login")
) {
window.location.href = "/login";
}
let message = "Unauthorized";
if (path.startsWith("/setup/")) {
try {
const body = (await response.clone().json()) as {
error?: { message?: string };
};
if (body?.error?.message) {
message = body.error.message;
}
} catch {
/* keep generic message */
}
}
throw new Error(message);
}
export async function request<T = unknown>(
path: string,
options: RequestInit = {},
): Promise<T> {
const url = getApiUrl(path);
const headers = buildHeaders(path, options.headers);
const response = await fetch(url, {
...options,
headers,
});
if (await check503ForSetupRequired(path, response)) {
throw new Error("Setup required — redirecting to /setup");
}
await throwIfUnauthorized(path, response);
applyRenewedAccessToken(response);
if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(
`Request failed: ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`,
);
}
if (response.status === 204) {
return undefined as T;
}
const contentType = response.headers.get("content-type") || "";
if (!contentType.includes("application/json")) {
return (await response.text()) as unknown as T;
}
return (await response.json()) as T;
}
/**
* Download a binary resource as a Blob.
*/
export async function requestBlob(
path: string,
options: RequestInit = {},
): Promise<Blob> {
const url = getApiUrl(path);
const headers = buildAuthHeaders(path);
const response = await fetch(url, {
...options,
headers: { ...headers, ...(options.headers as Record<string, string>) },
});
if (await check503ForSetupRequired(path, response)) {
throw new Error("Setup required — redirecting to /setup");
}
await throwIfUnauthorized(path, response);
applyRenewedAccessToken(response);
if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(
`Request failed: ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`,
);
}
return response.blob();
}
/**
* Authenticated GET that only checks success — cancels the body without
* buffering it (existence probes for large workspace files).
*/
export async function probeAuthResource(
path: string,
options: RequestInit = {},
): Promise<void> {
const url = getApiUrl(path);
const headers = buildAuthHeaders(path);
const response = await fetch(url, {
...options,
headers: { ...headers, ...(options.headers as Record<string, string>) },
});
if (await check503ForSetupRequired(path, response)) {
throw new Error("Setup required — redirecting to /setup");
}
await throwIfUnauthorized(path, response);
applyRenewedAccessToken(response);
if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(
`Request failed: ${response.status} ${response.statusText}${
text ? ` - ${text}` : ""
}`,
);
}
try {
await response.body?.cancel();
} catch {
/* ignore cancel failures */
}
}
export type UploadProgressHandler = (percent: number) => void;
/**
* Upload a FormData payload (no explicit Content-Type — browser handles boundary).
* Uses XMLHttpRequest so callers can report upload progress.
*/
export async function requestUpload<T = unknown>(
path: string,
body: FormData,
options: RequestInit = {},
onProgress?: UploadProgressHandler,
): Promise<T> {
const url = getApiUrl(path);
const headers = buildAuthHeaders(path);
const method = options.method ?? "POST";
return new Promise<T>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
for (const [key, value] of Object.entries(headers)) {
xhr.setRequestHeader(key, value);
}
if (options.headers) {
const extraEntries =
options.headers instanceof Headers
? Array.from(options.headers.entries())
: Array.isArray(options.headers)
? options.headers
: Object.entries(options.headers);
for (const [k, v] of extraEntries) {
xhr.setRequestHeader(k, String(v));
}
}
if (onProgress) {
xhr.upload.onprogress = (event) => {
if (event.lengthComputable && event.total > 0) {
onProgress(Math.round((event.loaded / event.total) * 100));
}
};
}
if (options.signal) {
if (options.signal.aborted) {
reject(new DOMException("The operation was aborted.", "AbortError"));
return;
}
options.signal.addEventListener(
"abort",
() => {
xhr.abort();
},
{ once: true },
);
}
xhr.onload = () => {
void (async () => {
const status = xhr.status;
const responseText = xhr.responseText;
const responseHeaders = new Headers();
const renewed = xhr.getResponseHeader(ACCESS_TOKEN_RESPONSE_HEADER);
if (renewed) {
responseHeaders.set(ACCESS_TOKEN_RESPONSE_HEADER, renewed);
}
const response = new Response(responseText, {
status,
headers: responseHeaders,
});
if (await check503ForSetupRequired(path, response)) {
reject(new Error("Setup required — redirecting to /setup"));
return;
}
try {
await throwIfUnauthorized(path, response);
} catch (err) {
reject(err);
return;
}
applyRenewedAccessToken(response);
if (!response.ok) {
const text = responseText;
let detail = `Upload failed: ${status}`;
try {
const json = JSON.parse(text) as { detail?: string };
if (json.detail) detail = json.detail;
} catch {
if (text) detail = text;
}
reject(new Error(detail));
return;
}
try {
resolve((await response.json()) as T);
} catch {
reject(new Error("Upload failed: invalid JSON response"));
}
})();
};
xhr.onerror = () => reject(new Error("Network error"));
xhr.onabort = () =>
reject(new DOMException("The operation was aborted.", "AbortError"));
xhr.send(body);
});
}