Skip to content

Commit 886ba45

Browse files
fix(metadata-protocol): cloning a record whose file fields are set answers 201 (#36063)
Fixes #35721 Clause-②: no Metadata-protocol: none ## 维护者速读 - 终端用户在数据接口上复制一条带附件字段(文件、图片等)的记录,之前直接报 400 失败,现在成功复制,附件按现有规则复制一份给新记录。 - 为什么做:外部开发者在 18.6.0 上做审批流程时,带必填报告附件的记录无法复制,这张缺陷卡(复制带文件字段的记录失败)就是为他们修的。 - 出错会怎样:受影响的只是复制这一个入口;若有问题,复制会重新失败或附件归属不对,改动只有一处读取方式,可直接撤回。 - 要你做什么:无。 ## What changes `cloneData` (`packages/metadata-protocol/src/protocol-data-crud.ts`) read the source record through the caller's normal read, which serves every file-class field expanded to `{ id, name, size, mimeType, url }` (or `{ id, metadataRefused: true }` for a reader refused `sys_file`). It inserted that object back, and the engine's media value-shape check refused it: `400 VALIDATION_FAILED`, "Report has an invalid file value: Invalid input: expected string, received object". The source is now read with `RAW_FILE_VALUES_CONTEXT_KEY` added to the caller's context, so the read returns file fields in their stored form: the bare `sys_file` id, or the list of ids for a `multiple` field. Nothing else about the read changes: it is still the caller's read, with the caller's security. The copied ids then take the same path an `overrides` id already took (ADR-0104 D3 wave 2 exclusive ownership: an id owned by another slot is copied into a new `sys_file` that the clone's field owns). `overrides` are still applied after the read, so an explicit override still wins. No new file-ownership rule. **Route, and why it differs from the card's wording.** The card asks to normalise each file and multi-file value read from the source back to its id. This PR gets the same result by asking the engine for the stored form instead of converting the expanded form afterwards: - `RAW_FILE_VALUES_CONTEXT_KEY` is the spec-declared opt-out for "a caller whose subject is the stored form" (`packages/spec/src/data/field-value.zod.ts`). The engine's resolver honours it before it selects fields (`engine-file-reference-hydration.ts`, `resolveFileReferences`), and it selects them by `FILE_REFERENCE_TYPES` (`image`, `file`, `avatar`, `video`, `audio`). So the clone covers exactly the set the expansion covers, single and `multiple`, with no second list of types to keep in step. - The same shape, the caller's context plus the key, is already used for this purpose by the engine's update-time stored read (`packages/objectql/src/engine-validate.ts` line 427, `{ ...(options?.context ?? {}), [RAW_FILE_VALUES_CONTEXT_KEY]: true }`) and by storage's `readRecordAs` (`record-file-access.ts` line 811). - A hand-written converter would have to know all three expanded forms (object, bare id, refused marker). That is the consumer-side shape conversion AGENTS.md Prime Directive #12 warns against. Programmatic calls with no context: the read now carries `{ __rawFileValues: true }` where before it carried no context. `buildSession` (`engine-execution-plumbing.ts`) gives no session for a context with no identity fields, and the security layer's checks read `context?.isSystem`, which is unset in both cases. This is the same trade-off `engine-validate.ts` line 427 already makes. `packages/objectql/src/engine.ts` is not touched; it is still 6857 lines. ## Tests New pin: `packages/qa/dogfood/test/clone-file-field-reference.dogfood.test.ts`, through the real REST clone route, using `bootStack` + `PlatformObjectsPlugin` + `StorageServicePlugin` on a local adapter, with real bytes uploaded by presign, PUT and complete. The fixture object has a `file`, a `multiple: true` `file` and an `image` field. 1. CONTROL: a clone whose `overrides` name the source's file ids answers 201, and every file is copied. 2. A clone with no body answers 201, and each of its file fields holds a new id. The `sys_file` row for that id is owned by `(cff_doc, cloneId, field)` and has the source's bytes, and the source keeps its own file. This is the same assertion helper the control uses. 3. A file field named in `overrides` takes the override (an unowned upload is claimed as it stands, and `papers: null` clears the field). The field the overrides leave alone still follows the copy rule. Each one reads back the stored row (`RAW_FILE_VALUES_CONTEXT_KEY`, system context) and the `sys_file` ownership columns, not only the 201 body. <details><summary>Reproduction on main (BASE 8145424, file restored byte-for-byte from BASE)</summary> `protocol-data-crud.ts` was restored from `8145424b53` (blob `af1feb89cb3d` equals the BASE blob), and the new pin ran against it. `@objectstack/metadata-protocol` resolves to `src/` in the dogfood config's alias. ``` × a clone with no body answers 201, and its file fields follow the same copy rule × a file field named in overrides takes the override, not the source file AssertionError: {"error":"Report has an invalid file value: Invalid input: expected string, received object; Papers has an invalid file value: at index 0: Invalid input: expected string, received object; Cover has an invalid image value: Invalid input: expected string, received object","code":"VALIDATION_FAILED", ... expected 400 to be 201 Test Files 1 failed (1) Tests 2 failed | 1 passed (3) os-verify-lock: VERDICT command-exit 1 ``` The CONTROL (`overrides` naming the ids) passed on BASE, which matches the card's workaround. After the run, the restore was checked: blob `56a3c2a37d4c` equals HEAD's, and `git diff HEAD` is empty. </details> <details><summary>Ablation (fix committed at efe9ec3, then mutated via scripts/ablation-replace.mjs)</summary> The anchor `context: { ...(ctx ?? {}), [RAW_FILE_VALUES_CONTEXT_KEY]: true } }` was replaced with `...(ctx !== undefined ? { context: ctx } : {}) }`, which is BASE's read. ``` ablation-replace: ok mutation landed: anchor 1 -> 0, blob 56a3c2a -> e7b54d7d53c6 × a clone with no body answers 201, and its file fields follow the same copy rule × a file field named in overrides takes the override, not the source file Test Files 1 failed (1) Tests 2 failed | 1 passed (3) ablation-replace: ok restored: blob == HEAD (56a3c2a) and `git diff HEAD` is empty ``` With the fix (efe9ec3): ``` Test Files 1 passed (1) Tests 3 passed (3) os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Package tests and typecheck (head 9fea83f)</summary> - `pnpm --filter @objectstack/metadata-protocol test`: `Test Files 362 passed | 9 skipped (371)`, `Tests 23305 passed | 45 skipped (23350)`, lock VERDICT command-exit 0. - `pnpm --filter @objectstack/metadata-protocol run typecheck && pnpm --filter @objectstack/dogfood run typecheck`: VERDICT command-exit 0. `tsc --listFiles` lists both changed files (1 hit each). </details> ## Acceptance notes - Out of scope, as the card says, and unchanged here: if the source's `sys_file` row exists but its stored content is missing, the clone's copy step fails with `500 FileReferenceCopyError`. A 4xx would describe that case better. This PR does not change it. The plain clone now reaches the copy step that the `overrides` path already reached, so the same 500 can now come from a clone with no body as well as from the `overrides` workaround. - The pin is a dogfood test. CI's `Dogfood Regression Gate` does not run on `pull_request`, only in the merge queue (per `dispatch-gates.mjs`). The readings above are local runs under `os-verify-lock.sh`. ## Verification Read first, in order of risk: 1. `packages/metadata-protocol/src/protocol-data-crud.ts`, the `cloneData` source read (the only behaviour hunk). 2. `packages/qa/dogfood/test/clone-file-field-reference.dogfood.test.ts`, `expectCopiedPerReferenceRule`. Two-minute check: `pnpm --filter @objectstack/dogfood exec vitest run --maxWorkers=2 test/clone-file-field-reference.dogfood.test.ts` (after building the dogfood closure). Expect `Tests 3 passed (3)`. <details><summary>Local gate subset (head 9fea83f)</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 69 commands. Each was run, and its exit code was captured before any pipe: - 68 exited 0. Among them: `check-adr-0087-registration --base origin/main`, `check-changeset-no-major`, `check-empty-changeset`, `check:nul-bytes`, `check:test-source-alias`, `check:cross-package-test-inputs`, `check:durability-log-level`, `check:engine-double-contract`, `check:type-check-coverage`, `check:type-check-debt`, `check-governed-queue-guard --self-test`. - 1 NOT MEASURED: `pnpm check:dual-build-cjs-loads` exited 3 with `PREREQUISITE NOT MET — this gate reads built output, and some package has no dist/` (studio, client-react and others outside the dogfood closure built here). CI's build job owns it. - `dispatch-gates --ran`: `69 derived famil(ies) accounted for — 69 run, 0 NOT-MEASURED` (its own count, which takes the list as written). The exit-3 reading above corrects it to 1 NOT MEASURED. - `scripts/pm/overlap-check.mjs` before each push: `VERDICT clean exit 0`. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c757e07 commit 886ba45

4 files changed

Lines changed: 263 additions & 3 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
---
4+
5+
fix(metadata-protocol): cloning a record whose file fields are set answers 201
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`POST /data/:object/:id/clone` with no `overrides` answered `400 VALIDATION_FAILED` ("… has an invalid file value: … expected string, received object") for any record holding a file in a `file`, `image`, `avatar`, `video` or `audio` field, single or `multiple`. The clone read the source the way the caller reads it, with each file expanded to its `{ id, name, size, mimeType, url }` object, and inserted that object back; the insert takes a file field's stored value, the `sys_file` id, only.
11+
12+
The clone now reads the source's file fields in their stored form (the bare id, or the list of ids for a `multiple` field). Each one then follows the same rule a clone naming the id in `overrides` already followed: the file's bytes are copied into a new `sys_file` that the clone's field owns, and the source record keeps its own file. A file field named in `overrides` still takes the override. Because a clone with no body now reaches that same copy step, it also gets that path's answer when a source file's `sys_file` row exists but its stored bytes are missing: `500 FileReferenceCopyError`, the error the `overrides` path already returned in that case.

‎packages/metadata-protocol/src/protocol-data-crud.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import {
4747
foldQueryAliasSlots,
4848
isFilterAST,
4949
parseFilterAST,
50+
RAW_FILE_VALUES_CONTEXT_KEY,
5051
} from '@objectstack/spec/data';
5152
import type { EngineAggregateOptions, EngineCountOptions } from '@objectstack/spec/data';
5253
import { malformedFilterArrayError } from './protocol-data-request-shapes.js';
@@ -1050,11 +1051,18 @@ export class ProtocolDataCrudFacet {
10501051
}
10511052

10521053
const ctx = request.context;
1053-
const ctxOpt = ctx !== undefined ? { context: ctx } : undefined;
10541054

1055+
// The source is read as the caller reads it, but with its file-class
1056+
// fields (`FILE_REFERENCE_TYPES`, single and `multiple`) in their
1057+
// STORED form: the bare `sys_file` id(s), never the expanded
1058+
// `{ id, name, size, mimeType, url }` object (or the refused-reader
1059+
// `{ id, metadataRefused }` marker) the read resolver serves. The
1060+
// insert below takes the stored form only — an expanded object is
1061+
// refused by the media value-shape check — and a copied id then
1062+
// follows the same field-reference rule an `overrides` id does.
10551063
const source = await host.engine.findOne(
10561064
request.object,
1057-
{ where: { id: request.id }, ...ctxOpt },
1065+
{ where: { id: request.id }, context: { ...(ctx ?? {}), [RAW_FILE_VALUES_CONTEXT_KEY]: true } },
10581066
);
10591067
if (!source) throw recordNotFoundError(request.object, request.id, ctx);
10601068

‎packages/objectql/src/protocol-data.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { describe, it, expect, vi, beforeEach } from 'vitest';
44
import { ObjectStackProtocolImplementation, recordNotFoundError } from '@objectstack/metadata-protocol';
5+
import { RAW_FILE_VALUES_CONTEXT_KEY } from '@objectstack/spec/data';
56

67
/**
78
* Tests for the Protocol Implementation's data methods (findData, getData).
@@ -686,7 +687,18 @@ describe('ObjectStackProtocolImplementation - Data Operations', () => {
686687
const { protocol, insert, findOne } = makeProtocol();
687688
const ctx = { userId: 'u1' };
688689
await protocol.cloneData({ object: 'account', id: 'src-1', context: ctx });
689-
expect(findOne).toHaveBeenCalledWith('account', expect.objectContaining({ context: ctx }));
690+
// [#35721] The source is read as the caller reads it, with file
691+
// fields in their STORED form: the caller's context plus
692+
// `RAW_FILE_VALUES_CONTEXT_KEY`, so a file field reaches the insert
693+
// as its `sys_file` id, never as the expanded file object.
694+
expect(findOne).toHaveBeenCalledWith('account', {
695+
where: { id: 'src-1' },
696+
context: { userId: 'u1', [RAW_FILE_VALUES_CONTEXT_KEY]: true },
697+
});
698+
// The key is added to a copy: the caller's own context is untouched,
699+
// so the insert assertion below (deep equality against `ctx`) holds
700+
// the insert to the caller's context WITHOUT the key.
701+
expect(ctx).toEqual({ userId: 'u1' });
690702
// [#15703] The insert options carry the context AND the
691703
// `onFieldsDropped` listener `createData` wires — the clone reports
692704
// the engine's readonly-strip verdict on its 201 body since #15703.
Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// `POST /data/:object/:id/clone` on a record whose file fields are set, end to
4+
// end through the real stack: REST clone door → `cloneData` → ObjectQL insert
5+
// → the storage service's field-reference copy-on-claim hooks, with real bytes
6+
// on a local adapter.
7+
//
8+
// ── What this pins ──────────────────────────────────────────────────────────
9+
//
10+
// A clone with no body answers 201, and every file-class field of the copy
11+
// references the source's file the way any write naming an already-owned
12+
// `sys_file` id does (ADR-0104 D3 wave 2, exclusive ownership): the bytes are
13+
// copied into a fresh `sys_file`, the copy is owned by the clone's slot, and
14+
// the source keeps its own file. Covered: a single `file`, a `multiple: true`
15+
// `file`, and an `image` — the multi-capable pair and one more member of
16+
// `FILE_REFERENCE_TYPES`.
17+
//
18+
// The defect this guards: `cloneData` read the source through the caller's
19+
// expanded read, which serves a file field as the `{ id, name, size, mimeType,
20+
// url }` object, and re-inserted that object; the media value-shape check
21+
// refused it with 400 "… has an invalid file value: … expected string,
22+
// received object".
23+
//
24+
// ── Why each assertion is load-bearing ──────────────────────────────────────
25+
//
26+
// The CONTROL is the `overrides` workaround — the same clone naming the
27+
// source's ids explicitly — which answered 201 before the fix. The plain
28+
// clone is held to the SAME reference rule the control demonstrates (a new
29+
// id, owned by the clone, same bytes), so the pin cannot pass by inventing a
30+
// second ownership rule.
31+
//
32+
// The READ-BACK of the stored form (`RAW_FILE_VALUES_CONTEXT_KEY`) and of
33+
// `sys_file`'s ownership columns, under a system context: the 201 body alone
34+
// would not show which file the clone's slot holds.
35+
//
36+
// `overrides` still wins: a file field named in `overrides` takes the
37+
// override, not the source's file.
38+
39+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
40+
import { promises as fs, mkdtempSync } from 'node:fs';
41+
import { join } from 'node:path';
42+
import { tmpdir } from 'node:os';
43+
import { bootStack, type VerifyStack } from '@objectstack/verify';
44+
import { defineStack } from '@objectstack/spec';
45+
import { ObjectSchema, Field, RAW_FILE_VALUES_CONTEXT_KEY, isFileIdToken } from '@objectstack/spec/data';
46+
import { StorageServicePlugin } from '@objectstack/service-storage';
47+
import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin';
48+
49+
const SYS = { isSystem: true } as const;
50+
const RAW = { ...SYS, [RAW_FILE_VALUES_CONTEXT_KEY]: true } as const;
51+
const OBJECT = 'cff_doc';
52+
53+
const CffDoc = ObjectSchema.create({
54+
name: OBJECT,
55+
label: 'Clone File Document',
56+
fields: {
57+
name: Field.text({ label: 'Name' }),
58+
report: Field.file({ label: 'Report' }),
59+
papers: Field.file({ label: 'Papers', multiple: true }),
60+
cover: Field.image({ label: 'Cover' }),
61+
},
62+
});
63+
64+
const cffStack = defineStack({
65+
manifest: {
66+
id: 'com.dogfood.clone-file-field-reference',
67+
namespace: 'cff',
68+
version: '0.0.0',
69+
type: 'app',
70+
name: 'Clone File Field Reference Fixture',
71+
description: 'An object with single, multiple and image file fields, cloned through the data API.',
72+
},
73+
objects: [CffDoc],
74+
});
75+
76+
describe('POST /data/:object/:id/clone on a record whose file fields are set', () => {
77+
let stack: VerifyStack;
78+
let rootDir: string;
79+
let token: string;
80+
let ql: any;
81+
82+
/** Upload real bytes through presign → PUT → complete; returns the `sys_file` id. */
83+
async function upload(name: string, body: string, mimeType: string): Promise<string> {
84+
const auth = { Authorization: `Bearer ${token}` };
85+
const presign = await stack.api('/storage/upload/presigned', {
86+
method: 'POST',
87+
headers: { 'Content-Type': 'application/json', ...auth },
88+
body: JSON.stringify({ filename: name, mimeType, size: body.length, scope: 'user' }),
89+
});
90+
expect(presign.status, 'presign').toBe(200);
91+
const { data } = (await presign.json()) as any;
92+
const put = await stack.raw(String(data.uploadUrl).replace(/^https?:\/\/[^/]+/, ''), {
93+
method: 'PUT',
94+
headers: data.headers ?? { 'content-type': mimeType },
95+
body,
96+
});
97+
expect(put.status, 'raw PUT').toBeLessThan(300);
98+
const complete = await stack.api('/storage/upload/complete', {
99+
method: 'POST',
100+
headers: { 'Content-Type': 'application/json', ...auth },
101+
body: JSON.stringify({ fileId: data.fileId }),
102+
});
103+
expect(complete.status, 'complete').toBe(200);
104+
return String(data.fileId);
105+
}
106+
107+
const call = async (method: 'POST', path: string, body?: unknown) => {
108+
const res = await stack.apiAs(token, method, path, body);
109+
return { status: res.status, body: (await res.json()) as any };
110+
};
111+
112+
/** The record's file fields in their STORED form, read above every access layer. */
113+
const stored = async (id: string) => ql.findOne(OBJECT, { where: { id }, context: RAW });
114+
115+
/** A `sys_file` row's owner and bytes, read above every access layer. */
116+
const fileState = async (id: string) => {
117+
const row = await ql.findOne('sys_file', { where: { id }, context: SYS });
118+
expect(row, `sys_file ${id} exists`).toBeTruthy();
119+
const bytes = await fs.readFile(join(rootDir, String(row.key)), 'utf8');
120+
return { owner: [row.ref_object, String(row.ref_id), row.ref_field], bytes };
121+
};
122+
123+
/** Create a source record through the data door with every file field set. */
124+
async function sourceRecord(tag: string) {
125+
const files = {
126+
report: await upload(`${tag}-report.txt`, `${tag} report`, 'text/plain'),
127+
papers: [
128+
await upload(`${tag}-a.txt`, `${tag} paper a`, 'text/plain'),
129+
await upload(`${tag}-b.txt`, `${tag} paper b`, 'text/plain'),
130+
],
131+
cover: await upload(`${tag}-cover.png`, `${tag} cover`, 'image/png'),
132+
};
133+
const created = await call('POST', `/data/${OBJECT}`, { name: tag, ...files });
134+
expect(created.status, JSON.stringify(created.body)).toBe(201);
135+
const id = String(created.body.id ?? created.body.data?.id ?? created.body.record?.id);
136+
// The source owns every file it names.
137+
expect((await fileState(files.report)).owner).toEqual([OBJECT, id, 'report']);
138+
expect((await fileState(files.papers[0])).owner).toEqual([OBJECT, id, 'papers']);
139+
expect((await fileState(files.cover)).owner).toEqual([OBJECT, id, 'cover']);
140+
return { id, files };
141+
}
142+
143+
/** The clone's id from a 201 clone answer. */
144+
const cloneIdOf = (body: any) => String(body.id ?? body.data?.id ?? body.record?.id);
145+
146+
/**
147+
* Every file field of the clone holds a NEW `sys_file` id, owned by the
148+
* clone's slot, carrying the source file's bytes — and the source still owns
149+
* its own file. The exclusive-ownership copy rule, per value.
150+
*/
151+
async function expectCopiedPerReferenceRule(source: { id: string; files: any }, cloneId: string) {
152+
const copy = await stored(cloneId);
153+
const pairs: Array<[string, string, string]> = [
154+
['report', source.files.report, copy.report],
155+
['papers', source.files.papers[0], copy.papers?.[0]],
156+
['papers', source.files.papers[1], copy.papers?.[1]],
157+
['cover', source.files.cover, copy.cover],
158+
];
159+
expect(Array.isArray(copy.papers) ? copy.papers.length : copy.papers).toBe(2);
160+
for (const [field, srcId, copyId] of pairs) {
161+
expect(isFileIdToken(copyId), `${field}: the clone stores a file id, got ${JSON.stringify(copyId)}`).toBe(true);
162+
expect(copyId, `${field}: the clone references its own copy, not the source's file`).not.toBe(srcId);
163+
const src = await fileState(srcId);
164+
const dst = await fileState(copyId);
165+
expect(src.owner, `${field}: the source keeps its file`).toEqual([OBJECT, source.id, field]);
166+
expect(dst.owner, `${field}: the copy is owned by the clone's slot`).toEqual([OBJECT, cloneId, field]);
167+
expect(dst.bytes, `${field}: the copy carries the source's bytes`).toBe(src.bytes);
168+
}
169+
}
170+
171+
beforeAll(async () => {
172+
rootDir = mkdtempSync(join(tmpdir(), 'cff-dogfood-'));
173+
stack = await bootStack(cffStack, {
174+
extraPlugins: [
175+
// The `sys_migration` flag ledger (#4243): a store created by this boot
176+
// attests its file migration, so the media value-shape check enforces.
177+
new PlatformObjectsPlugin(),
178+
new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }),
179+
],
180+
});
181+
token = await stack.signIn();
182+
ql = await stack.kernel.getServiceAsync('objectql');
183+
}, 120_000);
184+
185+
afterAll(async () => {
186+
await stack?.stop();
187+
});
188+
189+
it('CONTROL: a clone whose overrides name the source file ids answers 201 and copies every file', async () => {
190+
const source = await sourceRecord('ctl');
191+
const r = await call('POST', `/data/${OBJECT}/${source.id}/clone`, { overrides: { ...source.files } });
192+
193+
expect(r.status, JSON.stringify(r.body)).toBe(201);
194+
await expectCopiedPerReferenceRule(source, cloneIdOf(r.body));
195+
});
196+
197+
it('a clone with no body answers 201, and its file fields follow the same copy rule', async () => {
198+
const source = await sourceRecord('bare');
199+
const r = await call('POST', `/data/${OBJECT}/${source.id}/clone`);
200+
201+
expect(r.status, JSON.stringify(r.body)).toBe(201);
202+
const cloneId = cloneIdOf(r.body);
203+
expect(cloneId).not.toBe(source.id);
204+
await expectCopiedPerReferenceRule(source, cloneId);
205+
});
206+
207+
it('a file field named in overrides takes the override, not the source file', async () => {
208+
const source = await sourceRecord('ovr');
209+
const replacement = await upload('ovr-replacement.txt', 'replacement', 'text/plain');
210+
const r = await call('POST', `/data/${OBJECT}/${source.id}/clone`, {
211+
overrides: { report: replacement, papers: null },
212+
});
213+
214+
expect(r.status, JSON.stringify(r.body)).toBe(201);
215+
const cloneId = cloneIdOf(r.body);
216+
const copy = await stored(cloneId);
217+
// An unowned upload is claimed by the clone's slot as it stands — no copy.
218+
expect(copy.report).toBe(replacement);
219+
expect((await fileState(replacement)).owner).toEqual([OBJECT, cloneId, 'report']);
220+
expect(copy.papers ?? null).toBeNull();
221+
// The field the overrides left alone still follows the copy rule.
222+
expect(isFileIdToken(copy.cover)).toBe(true);
223+
expect(copy.cover).not.toBe(source.files.cover);
224+
expect((await fileState(copy.cover)).owner).toEqual([OBJECT, cloneId, 'cover']);
225+
// The source is untouched.
226+
expect((await fileState(source.files.report)).owner).toEqual([OBJECT, source.id, 'report']);
227+
});
228+
});

0 commit comments

Comments
 (0)