Repository navigation
Expand file tree
/
Copy pathfiles.test.ts
More file actions
775 lines (734 loc) · 28.5 KB
/
Copy pathfiles.test.ts
File metadata and controls
775 lines (734 loc) · 28.5 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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
import { storageRuntime } from "@server/adapters/storage.js";
import { beforeEach, afterEach, expect, it, vi } from "vitest";
import { mkdtemp, rm, rename } from "node:fs/promises";
import { join } from "node:path";
import { openTestDatabase } from "./database.js";
import { createApp } from "../apps/server/src/app/create-app.js";
import { createUser, type Actor } from "@core/modules/identity/passwords.js";
import type { DB } from "@db/index.js";
import sharp from "sharp";
import { createFileProcessingWorker } from "../apps/server/src/jobs/file-processing-worker.js";
import { enqueueProjection } from "@core/modules/automation/jobs.js";
import { pluginServices } from "@core/shared/plugin-services.js";
import { fail } from "@core/shared/errors.js";
const origin = "http://localhost:39130";
const password = "test-only-password-2026";
let db: DB;
let app: Awaited<ReturnType<typeof createApp>>;
let directory = "";
let cookie = "";
async function request(
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
path: string,
payload?: any,
contentType = "application/json",
) {
return (app.inject as any)({
method,
url: "/api/v1" + path,
headers: {
host: "localhost:39130",
origin,
cookie,
...(payload === undefined ? {} : { "content-type": contentType }),
},
...(payload === undefined ? {} : { payload }),
}) as Promise<any>;
}
beforeEach(async () => {
directory = await mkdtemp(
join(process.env.TMPDIR ?? "/tmp", "doca-files-test-"),
);
db = await openTestDatabase({
driver: "sqlite",
path: join(directory, "test.db"),
});
const admin = await createUser(
db,
{ login: "admin", displayName: "管理员", password },
{ bootstrap: true },
);
await createUser(
db,
{ login: "alice", displayName: "Alice", password },
{ actor: { ...admin, admin: 1 } as Actor },
);
app = await createApp(db, {
origin,
storage: {
configuration: storageRuntime().configuration,
root: join(directory, "uploads"),
credentials: {},
endpointHosts: [],
cdnKeyPairId: undefined,
cdnPrivateKey: undefined,
},
});
const login = await app.inject({
method: "POST",
url: "/api/v1/auth/login",
headers: { host: "localhost:39130", origin },
payload: { login: "alice", password },
});
expect(login.statusCode, login.body).toBe(200);
cookie = String(login.headers["set-cookie"]).split(";")[0]!;
});
afterEach(async () => {
await app?.close();
await db?.destroy();
if (directory) await rm(directory, { recursive: true, force: true });
});
it("removes the old knowledge overview dashboard", async () => {
const overview = await request("GET", "/knowledge/overview");
expect(overview.statusCode).toBe(404);
});
it("detects real file types, preserves originals, generates reusable thumbnails, and authorizes derived downloads", async () => {
const png = await sharp({
create: { width: 640, height: 320, channels: 3, background: "#8752cc" },
})
.png()
.toBuffer();
const upload = await request(
"POST",
"/files/items?filename=pretend-video.mp4",
png,
"application/octet-stream",
);
expect(upload.statusCode, upload.body).toBe(200);
const item = upload.json();
expect(item.mime).toBe("image/png");
const object = await db
.selectFrom("file_storage_objects")
.selectAll()
.where("id", "=", item.storage_object_id)
.executeTakeFirstOrThrow();
expect(object.category).toBe("image");
expect(object.object_key).toMatch(
/^host\/objects\/image\/[a-f0-9]{2}\/[a-f0-9]{2}\/[^/]+\/original$/,
);
expect(
(await request("GET", `/files/items/${item.id}/content`)).rawPayload,
).toEqual(png);
const duplicate = await request(
"POST",
"/files/items?filename=same.png",
png,
"application/octet-stream",
);
expect(duplicate.json().storage_object_id).toBe(item.storage_object_id);
const worker = createFileProcessingWorker(db, {
configuration: storageRuntime().configuration,
root: join(directory, "uploads"),
credentials: {},
endpointHosts: [],
cdnKeyPairId: undefined,
cdnPrivateKey: undefined,
});
await worker.pump();
// The app worker can hold the lease before this explicit pump claims it.
// Wait for the observable result from whichever worker wins the lease.
const preview = await vi.waitFor(
async () => {
const result = await request(
"GET",
`/files/items/${item.id}/content?variant=thumbnail`,
);
expect(result.statusCode, result.body).toBe(200);
return result;
},
{ timeout: 5000, interval: 50 },
);
expect(await sharp(preview.rawPayload).metadata()).toMatchObject({
format: "webp",
width: 480,
height: 240,
});
await enqueueProjection(db, "file-thumbnail", object.id, {
objectId: object.id,
});
await worker.pump();
expect(
await db
.selectFrom("file_derivatives")
.selectAll()
.where("source_id", "=", object.id)
.execute(),
).toHaveLength(1);
const otherLogin = await app.inject({
method: "POST",
url: "/api/v1/auth/login",
headers: { host: "localhost:39130", origin },
payload: { login: "admin", password },
});
const outsider = await app.inject({
url: `/api/v1/files/items/${item.id}/content?variant=thumbnail`,
headers: {
host: "localhost:39130",
cookie: String(otherLogin.headers["set-cookie"]).split(";")[0]!,
},
});
expect(outsider.statusCode).toBe(404);
});
it("serves authenticated byte ranges and rejects unsatisfiable ranges", async () => {
const upload = await request(
"POST",
"/files/items?filename=range.txt",
Buffer.from("0123456789"),
"application/octet-stream",
);
const url = `/api/v1/files/items/${upload.json().id}/content`;
const get = (range: string) =>
app.inject({ url, headers: { host: "localhost:39130", cookie, range } });
const partial = await get("bytes=2-5");
expect(partial.statusCode).toBe(206);
expect(partial.body).toBe("2345");
expect(partial.headers["content-range"]).toBe("bytes 2-5/10");
expect(partial.headers["content-length"]).toBe("4");
expect((await get("bytes=-3")).body).toBe("789");
expect((await get("bytes=7-")).body).toBe("789");
const invalid = await get("bytes=10-20");
expect(invalid.statusCode).toBe(416);
expect(invalid.headers["content-range"]).toBe("bytes */10");
const denied = await app.inject({
url,
headers: { host: "localhost:39130", range: "bytes=0-1" },
});
expect(denied.statusCode).toBe(401);
});
it("retries a persisted thumbnail job after storage becomes available again", async () => {
const png = await sharp({
create: { width: 12, height: 12, channels: 3, background: "red" },
})
.png()
.toBuffer();
const upload = await request(
"POST",
"/files/items?filename=retry.png",
png,
"application/octet-stream",
);
expect(upload.statusCode, upload.body).toBe(200);
const object = await db
.selectFrom("file_storage_objects")
.selectAll()
.where("id", "=", upload.json().storage_object_id)
.executeTakeFirstOrThrow();
const source = join(directory, "uploads", object.object_key);
await rename(source, source + ".offline");
const runtime = {
configuration: storageRuntime().configuration,
root: join(directory, "uploads"),
credentials: {},
endpointHosts: [],
cdnKeyPairId: undefined,
cdnPrivateKey: undefined,
};
await createFileProcessingWorker(db, runtime).pump();
const jobId = `file-thumbnail:${object.id}`;
const job = await db
.selectFrom("projection_jobs")
.selectAll()
.where("id", "=", jobId)
.executeTakeFirstOrThrow();
expect(job.attempts).toBe(1);
expect(job.last_error).toBeTruthy();
await rename(source + ".offline", source);
await db
.updateTable("projection_jobs")
.set({ available_at: "2000-01-01T00:00:00.000Z" })
.where("id", "=", jobId)
.execute();
await createFileProcessingWorker(db, runtime).pump();
expect(
await db
.selectFrom("projection_jobs")
.selectAll()
.where("id", "=", jobId)
.executeTakeFirst(),
).toBeUndefined();
expect(
(
await request(
"GET",
`/files/items/${upload.json().id}/content?variant=thumbnail`,
)
).statusCode,
).toBe(200);
});
it("rolls back object registration when a plugin rejects storage allocation", async () => {
pluginServices(db).policies.set("test.storage", {
id: "test.storage",
async check(input) {
if (
input.action === "storage.allocate" &&
Number(input.facts.additional) === 2
)
fail(413, "Storage denied by plugin");
},
});
expect(
(
await request(
"POST",
"/files/items?filename=first.txt",
Buffer.from("1234"),
"application/octet-stream",
)
).statusCode,
).toBe(200);
const rejected = await request(
"POST",
"/files/items?filename=second.txt",
Buffer.from("56"),
"application/octet-stream",
);
expect(rejected.statusCode, rejected.body).toBe(413);
expect(
await db.selectFrom("file_storage_objects").selectAll().execute(),
).toHaveLength(1);
expect(await db.selectFrom("file_items").selectAll().execute()).toHaveLength(
1,
);
});
it("supports the personal file lifecycle and keeps copies on the same object", async () => {
const initial = await request(
"GET",
"/files?parentType=system&parentId=root",
);
expect(initial.statusCode, initial.body).toBe(200);
expect(
initial.json().folders.filter((x: { type: string }) => x.type === "system"),
).toHaveLength(0);
const folder = await request("POST", "/files/folders", {
name: "项目资料",
parentId: null,
});
expect(folder.statusCode, folder.body).toBe(200);
const folderId = folder.json().id;
const aliased = await request("POST", "/files/folders", {
name: "猫猫相册",
parentId: "root",
});
expect(aliased.statusCode, aliased.body).toBe(200);
expect(aliased.json().parent_id).toBeNull();
const rootPage = await request(
"GET",
"/files?parentType=system&parentId=root",
);
expect(rootPage.json().folders.map((x: { name: string }) => x.name)).toEqual(
expect.arrayContaining(["项目资料", "猫猫相册"]),
);
const upload = await request(
"POST",
`/files/items?parentType=folder&parentId=${folderId}&filename=说明.txt`,
Buffer.from("文件预览内容"),
"application/octet-stream",
);
expect(upload.statusCode, upload.body).toBe(200);
const item = upload.json();
expect(
(await request("GET", "/files?parentType=system&parentId=root"))
.json()
.files.map((x: { name: string }) => x.name),
).not.toContain("说明.txt");
const content = await request("GET", `/files/items/${item.id}/content`);
expect(content.statusCode, content.body).toBe(200);
expect(content.body).toBe("文件预览内容");
const aiAttachment = await request("POST", `/files/items/${item.id}/attach`, {
purpose: "ai_attachment",
});
expect(aiAttachment.statusCode, aiAttachment.body).toBe(200);
const attachedFile = await db.selectFrom("file_items").selectAll().where("id", "=", aiAttachment.json().fileId).executeTakeFirstOrThrow();
expect(JSON.parse(attachedFile.metadata).assetId).toBe(aiAttachment.json().id);
expect(attachedFile.storage_object_id).toBe(item.storage_object_id);
expect(aiAttachment.json()).toEqual(
expect.objectContaining({ filename: "说明.txt", mime: "text/plain" }),
);
const copy = await request("POST", `/files/items/${item.id}/copy`, {
parentType: "folder",
parentId: folderId,
});
expect(copy.statusCode, copy.body).toBe(200);
expect(copy.json().storage_object_id).toBe(item.storage_object_id);
expect(copy.json().id).not.toBe(item.id);
const renamed = await request("PATCH", `/files/items/${copy.json().id}`, {
name: "副本.txt",
version: 1,
});
expect(renamed.statusCode, renamed.body).toBe(200);
const removed = await request("DELETE", `/files/items/${item.id}`, {
version: 1,
});
expect(removed.statusCode, removed.body).toBe(200);
const folderPage = await request(
"GET",
`/files?parentType=folder&parentId=${folderId}`,
);
expect(folderPage.json().files.map((x: { name: string }) => x.name)).toEqual([
"副本.txt",
]);
});
it("lists shared folders separately and manages their share link", async () => {
const created = await request("POST", "/files/folders", {
name: "团队资料",
parentId: "shared",
});
expect(created.statusCode, created.body).toBe(200);
const folderId = created.json().id;
const root = await request("GET", "/files?parentType=system&parentId=root");
expect(
root.json().folders.map((folder: { name: string }) => folder.name),
).not.toContain("共享文件夹");
const shared = await request("GET", "/files/shared-folders");
expect(shared.statusCode, shared.body).toBe(200);
expect(shared.json().items).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: folderId,
name: "团队资料",
role: "owner",
}),
]),
);
const link = await request("PUT", `/files/folders/${folderId}/share-link`, {
enabled: true,
role: "reader",
});
expect(link.statusCode, link.body).toBe(200);
expect(link.json()).toEqual(
expect.objectContaining({ enabled: true, role: "reader" }),
);
expect(link.json().url).toContain("#/shared-files/join?token=");
const readBack = await request(
"GET",
`/files/folders/${folderId}/share-link`,
);
expect(readBack.statusCode, readBack.body).toBe(200);
expect(readBack.json().token).toBe(link.json().token);
});
async function fileTestUser(login: string) {
const admin = await db.selectFrom("users").selectAll().where("login", "=", "admin").executeTakeFirstOrThrow();
return createUser(db, { login, displayName: login, password }, { actor: { id: admin.id, display_name: admin.display_name, admin: 1 } });
}
async function signInFileUser(login: string) {
const response = await app.inject({ method: "POST", url: "/api/v1/auth/login", headers: { host: "localhost:39130", origin }, payload: { login, password } });
expect(response.statusCode, response.body).toBe(200);
cookie = String(response.headers["set-cookie"]).split(";")[0]!;
}
it("enforces folder link limits, supports custom and unlimited values, and does not count direct members", async () => {
const bob = await fileTestUser("bob"), charlie = await fileTestUser("charlie"), ownerCookie = cookie;
const folder = (await request("POST", "/files/folders", { name: "限额资料", parentId: "shared" })).json();
const link = (await request("PUT", `/files/folders/${folder.id}/share-link`, { enabled: true, role: "reader" })).json();
expect(link).toMatchObject({ maxMembers: 1, memberCount: 0 });
expect((await request("PUT", `/files/folders/${folder.id}/share-link`, { enabled: true, role: "reader", maxMembers: 0 })).statusCode).toBe(400);
await signInFileUser("bob");
expect((await request("POST", "/files/share/redeem", { token: link.token })).statusCode).toBe(200);
expect((await request("POST", "/files/share/redeem", { token: link.token })).statusCode).toBe(200);
await signInFileUser("charlie");
expect((await request("POST", "/files/share/redeem", { token: link.token })).statusCode).toBe(403);
cookie = ownerCookie;
expect((await request("GET", `/files/folders/${folder.id}/share-link`)).json().memberCount).toBe(1);
expect((await request("PUT", `/files/folders/${folder.id}/shares`, { userId: charlie.id, role: "reader" })).statusCode).toBe(200);
await signInFileUser("charlie");
expect((await request("POST", "/files/share/redeem", { token: link.token })).statusCode).toBe(200);
cookie = ownerCookie;
expect((await request("GET", `/files/folders/${folder.id}/share-link`)).json().memberCount).toBe(1);
expect((await request("PUT", `/files/folders/${folder.id}/share-link`, { enabled: true, role: "reader", maxMembers: 17 })).json().maxMembers).toBe(17);
const rotated = (await request("PUT", `/files/folders/${folder.id}/share-link`, { enabled: true, role: "reader", rotate: true, maxMembers: null })).json();
expect(rotated).toMatchObject({ maxMembers: null, memberCount: 0 });
expect(rotated.token).not.toBe(link.token);
expect(await db.selectFrom("file_folder_shares").select("user_id").where("folder_id", "=", folder.id).execute()).toEqual(expect.arrayContaining([{ user_id: bob.id }, { user_id: charlie.id }]));
await signInFileUser("bob");
expect((await request("POST", "/files/share/redeem", { token: link.token })).statusCode).toBe(404);
});
it("creates visible folder invitation tickets and notifications and grants access only after consent", async () => {
const bob = await fileTestUser("bob"), ownerCookie = cookie;
await db.updateTable("distribution_settings").set({ config: JSON.stringify({ grantMode: "invite", ticketReviewers: { invitation: true } }) }).execute();
const folder = (await request("POST", "/files/folders", { name: "受邀资料", parentId: "shared" })).json();
const invited = await request("PUT", `/files/folders/${folder.id}/shares`, { userId: bob.id, role: "reader", message: "请查收" });
expect(invited.statusCode, invited.body).toBe(200);
expect(invited.json()).toMatchObject({ pending: true });
expect(await db.selectFrom("file_folder_shares").selectAll().where("folder_id", "=", folder.id).execute()).toEqual([]);
await signInFileUser("bob");
const notifications = await request("GET", "/notifications");
expect(notifications.statusCode, notifications.body).toBe(200);
expect(notifications.json().items).toEqual(expect.arrayContaining([expect.objectContaining({ type: "resource.invited", ticket_id: invited.json().ticketId })]));
const mine = await request("GET", "/tickets?onlyMine=true&resourceKind=folder");
expect(mine.statusCode, mine.body).toBe(200);
expect(mine.json().items).toEqual(expect.arrayContaining([expect.objectContaining({ id: invited.json().ticketId, status: "pending", actions: expect.arrayContaining(["accept", "reject"]) })]));
const accepted = await request("POST", `/tickets/${invited.json().ticketId}/actions`, { action: "accept" });
expect(accepted.statusCode, accepted.body).toBe(200);
expect(accepted.json()).toMatchObject({ status: "completed", resource: { title: folder.name, kind: "folder", url: `#/shared-files/${folder.id}` } });
expect((await request("GET", "/files/shared-folders")).json().items).toEqual(expect.arrayContaining([expect.objectContaining({ id: folder.id, role: "reader" })]));
cookie = ownerCookie;
expect((await request("GET", "/notifications")).json().items).toEqual(expect.arrayContaining([expect.objectContaining({ type: "invitation.accepted", ticket_id: invited.json().ticketId })]));
});
it("records direct folder grants as completed invitation tickets and notifies the recipient", async () => {
const bob = await fileTestUser("bob");
const folder = (await request("POST", "/files/folders", { name: "直接资料", parentId: "shared" })).json();
const invitation = await request("PUT", `/files/folders/${folder.id}/shares`, { userId: bob.id, role: "reader" });
expect(invitation.statusCode, invitation.body).toBe(200);
expect(invitation.json()).toMatchObject({ pending: false });
await signInFileUser("bob");
expect((await request("GET", `/tickets/${invitation.json().ticketId}`)).json()).toMatchObject({ status: "completed", resourceKind: "folder", resource: { title: folder.name } });
const notice = (await request("GET", "/notifications")).json();
expect(notice.unread).toBe(1);
expect(notice.items).toEqual(expect.arrayContaining([expect.objectContaining({ ticket_id: invitation.json().ticketId, type: "resource.permissions_changed", title: folder.name })]));
});
it("recursively copies folders into a shared destination without duplicating storage", async () => {
const source = await request("POST", "/files/folders", {
name: "待共享资料",
parentId: null,
});
const child = await request("POST", "/files/folders", {
name: "子目录",
parentId: source.json().id,
});
const upload = await request(
"POST",
`/files/items?parentType=folder&parentId=${child.json().id}&filename=说明.txt`,
Buffer.from("shared copy"),
"application/octet-stream",
);
const shared = await request("POST", "/files/folders", {
name: "共享目标",
parentId: "shared",
});
const copied = await request(
"POST",
`/files/folders/${source.json().id}/copy`,
{ parentId: shared.json().id },
);
expect(copied.statusCode, copied.body).toBe(200);
const copiedRoot = await request(
"GET",
`/files?parentType=folder&parentId=${copied.json().id}`,
);
expect(copiedRoot.json().folders).toHaveLength(1);
const copiedChild = await request(
"GET",
`/files?parentType=folder&parentId=${copiedRoot.json().folders[0].id}`,
);
expect(copiedChild.json().files[0]).toEqual(
expect.objectContaining({ name: "说明.txt" }),
);
const copiedInfo = await request(
"GET",
`/files/items/${copiedChild.json().files[0].id}/info`,
);
expect(copiedInfo.json().storage_object_id).toBe(
upload.json().storage_object_id,
);
});
it("copies a folder under a new name when the destination already has the original", async () => {
const source = await request("POST", "/files/folders", {
name: "新建文件夹",
parentId: null,
});
expect(source.statusCode, source.body).toBe(200);
const copied = await request(
"POST",
`/files/folders/${source.json().id}/copy`,
{
parentId: null,
name: "新建文件夹 2",
},
);
expect(copied.statusCode, copied.body).toBe(200);
const root = await request("GET", "/files?parentType=system&parentId=root");
const names = root
.json()
.folders.map((folder: { name: string }) => folder.name);
expect(names).toEqual(expect.arrayContaining(["新建文件夹", "新建文件夹 2"]));
});
it("uploads zip files and groups copied files into one searchable physical resource", async () => {
const firstFolder = await request("POST", "/files/folders", {
name: "压缩包",
parentId: null,
});
const secondFolder = await request("POST", "/files/folders", {
name: "归档副本",
parentId: null,
});
const uploaded = await request(
"POST",
`/files/items?parentType=folder&parentId=${firstFolder.json().id}&filename=project.zip`,
Buffer.from("PK\u0003\u0004test archive"),
"application/octet-stream",
);
expect(uploaded.statusCode, uploaded.body).toBe(200);
expect(uploaded.json().mime).toBe("application/zip");
const copied = await request(
"POST",
`/files/items/${uploaded.json().id}/copy`,
{ parentType: "folder", parentId: secondFolder.json().id },
);
expect(copied.statusCode, copied.body).toBe(200);
await db
.updateTable("file_storage_objects")
.set({ ai_description: "前端工程源码压缩归档,封面是一只橘色猫" })
.where("id", "=", uploaded.json().storage_object_id)
.execute();
const search = await request("GET", "/files/search?q=前端工程");
expect(search.statusCode, search.body).toBe(200);
expect(search.json().items).toHaveLength(1);
expect(search.json().items[0]).toEqual(
expect.objectContaining({
storageObjectId: uploaded.json().storage_object_id,
mime: "application/zip",
}),
);
expect(search.json().items[0].locations).toHaveLength(2);
expect(
search
.json()
.items[0].locations.map((location: { id: string }) => location.id),
).toEqual(expect.arrayContaining([uploaded.json().id, copied.json().id]));
const aiSearch = await request("GET", "/files/search?q=猫猫图片&mode=ai");
expect(aiSearch.statusCode, aiSearch.body).toBe(200);
expect(aiSearch.json().items).toHaveLength(1);
expect(aiSearch.json().items[0].description).toContain("橘色猫");
});
it("shows one physical image result with AI, document and personal locations", async () => {
const document = await request("POST", "/resources", {
kind: "document",
format: "markdown",
title: "猫咪观察文档",
markdown: "# 猫咪观察",
});
const uploaded = await request(
"POST",
"/files/items?filename=orange-cat.webp",
await sharp({
create: {
width: 24,
height: 24,
channels: 3,
background: "orange",
},
})
.webp()
.toBuffer(),
"application/octet-stream",
);
await request("POST", `/files/items/${uploaded.json().id}/attach`, {
purpose: "ai_attachment",
});
await request("POST", `/files/items/${uploaded.json().id}/attach`, {
purpose: "attachment",
resourceId: document.json().id,
});
await db
.updateTable("file_storage_objects")
.set({ ai_description: "一只阳光下的橘色猫", ai_status: "ready" })
.where("id", "=", uploaded.json().storage_object_id)
.execute();
const search = await request("GET", "/files/search?q=橘色猫");
expect(search.statusCode, search.body).toBe(200);
expect(search.json().items).toHaveLength(1);
const locations = search.json().items[0].locations;
expect(locations).toHaveLength(3);
expect(
locations.filter(
(location: { parentType: string; parentId: string }) =>
location.parentType === "system" && location.parentId === "ai",
),
).toHaveLength(1);
expect(
locations.find(
(location: { parentType: string }) => location.parentType === "document",
).navigation,
).toEqual([
expect.objectContaining({
type: "document",
id: document.json().id,
name: "猫咪观察",
}),
]);
});
it("keeps a successful empty indexed file search empty instead of listing keyword candidates", async () => {
const uploaded = await request("POST", "/files/items?filename=doca问题记录.txt", Buffer.from("test"), "application/octet-stream");
expect(uploaded.statusCode, uploaded.body).toBe(200);
await db.updateTable("search_settings").set({
enabled: 1, endpoint: "http://127.0.0.1:7700", index_name: "doca",
}).where("id", "=", "system").execute();
await app.close();
app = await createApp(db, {
origin,
storage: { ...storageRuntime(), root: join(directory, "uploads") },
search: {
allowedOrigins: ["http://127.0.0.1:7700"],
fetch: async (url) => Response.json(String(url).endsWith("/search") ? { hits: [] } : {}),
},
});
const response = await request("GET", "/files/search?q=doca问题记录&mode=ai");
expect(response.statusCode, response.body).toBe(200);
expect(response.json().items).toEqual([]);
await db.updateTable("search_settings").set({ enabled: 0 }).where("id", "=", "system").execute();
const local = await request("GET", "/files/search?q=doca问题记录&mode=ai");
expect(local.json().items.map((item: any) => item.id)).toEqual([uploaded.json().id]);
const irrelevant = await request("GET", "/files/search?q=doca火星发射流程&mode=ai");
expect(irrelevant.json().items).toEqual([]);
});
it("keeps AI assistant files copy-only so originals stay in place", async () => {
const uploaded = await request(
"POST",
"/files/items?filename=ai-cat.png",
await sharp({
create: {
width: 16,
height: 16,
channels: 3,
background: "orange",
},
})
.png()
.toBuffer(),
"application/octet-stream",
);
expect(uploaded.statusCode, uploaded.body).toBe(200);
const attached = await request(
"POST",
`/files/items/${uploaded.json().id}/attach`,
{
purpose: "ai_attachment",
},
);
expect(attached.statusCode, attached.body).toBe(200);
const page = await request("GET", "/files?parentType=system&parentId=ai");
expect(page.statusCode, page.body).toBe(200);
const aiFile = page
.json()
.files.find((file: { name: string }) => file.name === "ai-cat.png");
expect(aiFile).toMatchObject({ name: "ai-cat.png", locked: true });
const moved = await request("PATCH", `/files/items/${aiFile.id}`, {
parentType: "system",
parentId: "root",
version: aiFile.version,
});
expect(moved.statusCode, moved.body).toBe(403);
const removed = await request("DELETE", `/files/items/${aiFile.id}`, {
version: aiFile.version,
});
expect(removed.statusCode, removed.body).toBe(403);
const copied = await request("POST", `/files/items/${aiFile.id}/copy`, {
parentType: "system",
parentId: "root",
});
expect(copied.statusCode, copied.body).toBe(200);
expect(copied.json().id).not.toBe(aiFile.id);
expect(copied.json().parent_id).toBe("root");
const still = await request("GET", "/files?parentType=system&parentId=ai");
expect(
still.json().files.some((file: { id: string }) => file.id === aiFile.id),
).toBe(true);
const intoAi = await request(
"POST",
`/files/items/${uploaded.json().id}/copy`,
{
parentType: "system",
parentId: "ai",
},
);
expect(intoAi.statusCode, intoAi.body).toBe(403);
});