合入小壹 P2-4 运行时数据精简
This commit is contained in:
commit
ee9f312e19
@ -59,9 +59,10 @@ export const executionCategory = action => operationCategories[action] ?? 'ui_ac
|
||||
export const activityToolLabel = name => Object.hasOwn(labels, name) ? labels[name] : '工具';
|
||||
|
||||
const inferencePhases = Object.freeze({
|
||||
provider_prepared:['prepare','prepared'], serialized_request:['serialize','prepared'],
|
||||
provider_prepared:['prepare','prepared'],
|
||||
provider_started:['dispatch','running'], provider_finished:['receipt','completed'],
|
||||
provider_error:['receipt','failed'], response_audit:['inspect','completed'],
|
||||
provider_error:['receipt','failed'],
|
||||
subagent_tools:['receipt','completed'],
|
||||
usage:['usage','completed'], pi_retry:['retry','pending'],
|
||||
});
|
||||
|
||||
|
||||
@ -18,7 +18,7 @@ import { COPY_IMAGE_SCREEN_CRITERIA, DRAW_LIMIT_GUIDANCE } from './copy-image-al
|
||||
import { runToolCall } from '@earendil-works/pi-agent-core';
|
||||
import { createAgentSession, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||||
import { anthropicMessagesApi, openAICompletionsApi, openAIResponsesApi, createAssistantMessageEventStream, parseStreamingJson } from '@earendil-works/pi-ai/compat';
|
||||
import { atomic, digest } from './store.mjs';
|
||||
import { atomic } from './store.mjs';
|
||||
import { jsonToolContext, decodeToolReply } from './json-tool-codec.mjs';
|
||||
import { parseReceipt } from './receipt.mjs';
|
||||
import { auditResponse, InvalidToolReply } from './response-audit.mjs';
|
||||
@ -87,24 +87,6 @@ transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同
|
||||
独立手动复核时可用 record_screen_check 登记实际结果。复核后用 finish_production 提交当前画布修订,以工具返回的文件和版本为交付依据。可随时用 open_production_output 切换其它成品或回到此前的草稿。收口时用 finish_production 的 scope=all 核验本轮交付。子代理正在运行时可用 await_image_slots 等待回执。已返回结果未知的生图请求用 reconcile_image_slots 按原编号核查,核查期间可继续其它可做的图位和画布编辑。普通缺项和验图退回继续制作,仅在需要外部介入时提交阻塞原因和所需动作。用简短中文说明实际进展。`;
|
||||
|
||||
const plain = value => ({ content: [{ type: 'text', text: JSON.stringify(value) }], details: value });
|
||||
function imageLengthSummary(data, start = 0) {
|
||||
const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
|
||||
const bytes = Math.floor((data.length - start - padding) * 3 / 4);
|
||||
return `[image-base64-omitted:${bytes}B]`;
|
||||
}
|
||||
|
||||
function summarizePayloadImages(value) {
|
||||
if (typeof value === 'string' && value.startsWith('data:image/')) {
|
||||
const comma = value.indexOf(',');
|
||||
if (comma !== -1 && value.startsWith(';base64,', comma - 7)) return imageLengthSummary(value, comma + 1);
|
||||
}
|
||||
if (Array.isArray(value)) return value.map(summarizePayloadImages);
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
if ((value.type === 'image' || value.type === 'base64' && value.media_type?.startsWith('image/')) && typeof value.data === 'string') {
|
||||
return {...value, data: imageLengthSummary(value.data)};
|
||||
}
|
||||
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, summarizePayloadImages(item)]));
|
||||
}
|
||||
// Both shapes are native projections of the frozen request, never the live selection.
|
||||
const frozenReferences = context => Array.isArray(context?.requestScope?.references)
|
||||
? context.requestScope.references : Array.isArray(context?.references) ? context.references : undefined;
|
||||
@ -506,13 +488,9 @@ export class DetailPiAgent {
|
||||
}
|
||||
if (encoded && api === 'openai-completions') payload.response_format = { type: 'json_object' };
|
||||
if (encoded && api === 'openai-responses') payload.text = { format: { type: 'json_object' } };
|
||||
// Private project evidence: BODY ONLY, never the fetch headers or API Key.
|
||||
promptCacheKeyPresent = typeof payload.prompt_cache_key === 'string';
|
||||
if (!worker) {
|
||||
const archivedPayload = process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1' ? payload : summarizePayloadImages(payload);
|
||||
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), archivedPayload);
|
||||
await store.appendEvent({ type: 'serialized_request', id: round.id, keys: Object.keys(payload), tools: (payload.tools || []).map(t => t.name || t.function?.name), bodyHash: digest(archivedPayload),
|
||||
promptCacheKeyPresent });
|
||||
if (!worker && process.env.XIAOYI_DUMP_RAW_PAYLOADS === '1') {
|
||||
await atomic(path.join(store.dir, 'payloads', round.id + '.json'), payload);
|
||||
}
|
||||
return payload;
|
||||
},
|
||||
@ -577,9 +555,7 @@ export class DetailPiAgent {
|
||||
await onEvent({ type: 'usage', id: round.id, model: model.id, ...usage });
|
||||
if (!worker && !host.compacting) await host.updateContextUsage({ ...usage, id: round.id, model: model.id, at: Date.now(), source: 'provider-response' }, 'running');
|
||||
const audit = auditResponse(wire.text, info.model.protocol);
|
||||
if (worker) {
|
||||
if (result.content.filter(item=>item.type==='toolCall').length!==audit.calls.length) throw new InvalidToolReply('原模型工具调用未完整返回');
|
||||
} else await store.appendEvent({ type: 'response_audit', id: round.id, ...audit, calls: audit.calls.map(c => ({ name: c.name })) });
|
||||
if (worker && result.content.filter(item=>item.type==='toolCall').length!==audit.calls.length) throw new InvalidToolReply('原模型工具调用未完整返回');
|
||||
host.productionSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
if (!encoded && requiredTool && !audit.calls.some(c => c.name === requiredTool)) throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
|
||||
|
||||
@ -10,26 +10,28 @@ import { executionCategory } from './activity-event.mjs';
|
||||
|
||||
assertPiNodeVersion(process.versions.node);
|
||||
|
||||
const canvasTelemetry = new Set(['pi-state', 'pi-context-usage', 'pi-ui-request', 'pi-ui-poll', 'pi-ui-cancel']);
|
||||
|
||||
export function observeCanvasCalls(store, call) {
|
||||
return async (action, input, execution) => {
|
||||
if (action === 'pi-delta' || action === 'pi-activity') return call(action,input);
|
||||
const identity={...store.executionScope,operationId:input.operationId ?? execution?.operationId ?? randomUUID(),
|
||||
attempt:execution?.attempt ?? 1,requestId:execution?.requestId,revision:input.revision ?? store.executionScope.revision};
|
||||
const category=executionCategory(action);
|
||||
const record=(type,phase,status,extra)=>store.appendEvent({type,action,...identity,phase,status,...extra})
|
||||
.catch(error=>console.warn('小壹画布事件写入失败',error.code ?? error.name));
|
||||
const startedAt = performance.now();
|
||||
const record = (status, extra) => store.appendEvent({
|
||||
type:'canvas_receipt', action, ...identity, phase:'receipt', status,
|
||||
durationMs:Math.round(performance.now() - startedAt), ...extra,
|
||||
}).catch(error=>console.warn('小壹画布事件写入失败',error.code ?? error.name));
|
||||
store.executionHealth.agentHeartbeat=Date.now();
|
||||
await record('canvas_enqueued','enqueue','pending',{category:'ui_ack'});
|
||||
let accepted;
|
||||
let accepted = false;
|
||||
try {
|
||||
const reply=call(action,action==='pi-production-finish'?{...input,execution:{...identity,...store.executionHealth}}:input,()=>{
|
||||
store.executionHealth.uiHeartbeat=Date.now();
|
||||
accepted=record('canvas_accepted','accept','completed',{category:'ui_ack'})
|
||||
.then(()=>record('canvas_started','execute','running',{category}));
|
||||
accepted = true;
|
||||
});
|
||||
execution?.onEnqueued?.();
|
||||
const value=await reply;
|
||||
await accepted;
|
||||
if (value?.conversationActive === true) store.executionHealth.uiHeartbeat=Date.now();
|
||||
const binding=value?.productionCanvas;
|
||||
if (binding?.documentKey) Object.assign(store.executionScope,{
|
||||
@ -41,13 +43,12 @@ export function observeCanvasCalls(store, call) {
|
||||
}
|
||||
const status=value?.executed===false && value?.error ? 'failed' :
|
||||
[value?.status,value?.phase].find(v=>typeof v==='string') ?? 'completed';
|
||||
await record('canvas_receipt','receipt',status,{category,revision:value?.revision ?? identity.revision,
|
||||
if (!canvasTelemetry.has(action) || status === 'failed') await record(status,{category,revision:value?.revision ?? identity.revision,
|
||||
...(value?.requestId ? {requestId:value.requestId} : null)});
|
||||
return value;
|
||||
} catch(error) {
|
||||
await accepted;
|
||||
const status=error.category==='cancelled'?'cancelled':error.category==='transport_interrupted'?'unknown':'failed';
|
||||
await record('canvas_receipt','receipt',status,{category:accepted?category:'ui_ack',failureCategory:error.category});
|
||||
await record(status,{category:accepted?category:'ui_ack',failureCategory:error.category});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@ -181,8 +182,6 @@ export async function runSession(config, call, sharedBroker, recovery, signal, o
|
||||
store.executionHealth={agentHeartbeat:Date.now()};
|
||||
heartbeat=setInterval(()=>{
|
||||
store.executionHealth.agentHeartbeat=Date.now();
|
||||
void store.appendEvent({type:'agent_heartbeat',phase:'heartbeat',status:'running',category:'ui_ack'})
|
||||
.catch(error=>console.warn('小壹心跳事件写入失败',error.code ?? error.name));
|
||||
},15_000);
|
||||
heartbeat.unref();
|
||||
const canvas = new StdioCanvas(observeCanvasCalls(store,call), config.documentId);
|
||||
|
||||
@ -218,6 +218,13 @@ export class ProjectRepository {
|
||||
|
||||
readVersion(kind, id, revision) {
|
||||
return this.#open(db => {
|
||||
if (kind === 'prompt') {
|
||||
const request = this.#readRequest(db, id);
|
||||
if (request && String(request.revision) === String(revision)) {
|
||||
const { prompt, promptHash } = request.prepared.spec;
|
||||
return { slotId:request.slotId, prompt, promptHash };
|
||||
}
|
||||
}
|
||||
const row = db.prepare(`SELECT value_json FROM project_versions WHERE ${scopeWhere} AND kind = ?
|
||||
AND record_id = ? AND revision = ?`).get(...this.scope, kind, id, String(revision));
|
||||
return row ? JSON.parse(row.value_json) : null;
|
||||
@ -225,7 +232,7 @@ export class ProjectRepository {
|
||||
}
|
||||
|
||||
#saveImageRequest(db, receipt, policy, candidateSetId) {
|
||||
const { requestId, operationId = requestId, slotId, requestSpecHash, revision, spec } = receipt;
|
||||
const { requestId, operationId = requestId, slotId, requestSpecHash, revision } = receipt;
|
||||
if (policy || candidateSetId) {
|
||||
const original = this.#readRequest(db, requestId);
|
||||
let candidateSet = original?.prepared.candidateSet;
|
||||
@ -244,13 +251,12 @@ export class ProjectRepository {
|
||||
}
|
||||
receipt = { ...receipt, candidateSet };
|
||||
}
|
||||
this.#saveVersion(db, 'prompt', requestId, revision, { slotId, prompt: spec.prompt, promptHash: spec.promptHash });
|
||||
db.prepare(`INSERT INTO image_requests (${scopeColumns}, request_id, operation_id, slot_id, request_spec_hash,
|
||||
revision, state, prepared_json) VALUES (${scopeValues}, ?, ?, ?, ?, ?, 'prepared', ?)
|
||||
ON CONFLICT (${scopeColumns}, request_id) DO NOTHING`).run(
|
||||
...this.scope, requestId, operationId, slotId, requestSpecHash, revision, json(receipt));
|
||||
const saved = this.#readRequest(db, requestId);
|
||||
if (json(saved.prepared) !== json(receipt)) throw Error('生图请求内容已变化,请重新准备');
|
||||
if (json(saved.prepared) !== json(receipt)) throw Error('生图请求内容已变化,请重新准备新版本');
|
||||
return saved;
|
||||
}
|
||||
|
||||
|
||||
@ -18,7 +18,7 @@ import { BridgeError } from '../src/bridge-error.mjs';
|
||||
const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22';
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
test('canvas observations join enqueue, acceptance and execution without transferring the viewer identity',async()=>{
|
||||
test('canvas observations save a single receipt and keep routine telemetry in memory',async()=>{
|
||||
const records=[];
|
||||
const executionScope={projectId:'project',runId,outputId:'detail',variantId:'oak',revision:7,documentKey:{variantId:'oak'}};
|
||||
const executionHealth={};
|
||||
@ -32,12 +32,14 @@ test('canvas observations join enqueue, acceptance and execution without transfe
|
||||
});
|
||||
const result=call('pi-detail-copy-apply',{operationId:'copy-1',revision:7},{onEnqueued:enqueued.resolve});
|
||||
await enqueued.promise;
|
||||
assert.ok(records.every(event=>event.phase!=='receipt'));
|
||||
assert.equal(records.length,0);
|
||||
reply.resolve();
|
||||
await result;
|
||||
await call('pi-state',{});
|
||||
await call('pi-context-usage',{});
|
||||
await call('pi-ui-poll',{});
|
||||
assert.deepEqual(records.map(event=>[event.category,event.phase,event.status,event.revision]),[
|
||||
['ui_ack','enqueue','pending',7],['ui_ack','accept','completed',7],
|
||||
['canvas_write','execute','running',7],['canvas_write','receipt','completed',8],
|
||||
['canvas_write','receipt','completed',8],
|
||||
]);
|
||||
for(const event of records){
|
||||
assert.equal(event.projectId,'project');
|
||||
@ -51,8 +53,9 @@ test('canvas observations join enqueue, acceptance and execution without transfe
|
||||
assert.equal(event.jobProgress,null);
|
||||
assert.equal(event.recentDurableCommit,null);
|
||||
}
|
||||
assert.equal(records[0].uiHeartbeat,null);
|
||||
assert.ok(Number.isFinite(records[1].uiHeartbeat));
|
||||
assert.ok(Number.isFinite(records[0].uiHeartbeat));
|
||||
assert.ok(records[0].durationMs >= 0);
|
||||
assert.equal(executionScope.revision,8);
|
||||
});
|
||||
|
||||
test('a retried canvas read keeps its operation ID and records the next attempt',async()=>{
|
||||
|
||||
@ -768,9 +768,10 @@ test('the model receives prior images and original tool receipts through Pi', as
|
||||
} finally {await x.close();}
|
||||
});
|
||||
|
||||
test('main request archives summarize image bytes by default and support raw payload opt-in',async t=>{
|
||||
test('main requests keep their original identity without saving a copy of the request body',async t=>{
|
||||
const setting='XIAOYI_DUMP_RAW_PAYLOADS';
|
||||
const previous=process.env[setting];
|
||||
delete process.env[setting];
|
||||
t.after(()=>{if(previous===undefined)delete process.env[setting];else process.env[setting]=previous;});
|
||||
const image='iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAAmkwkpAAAAEElEQVR4nGP43+AARwzEcQDiohvxgB7+wgAAAABJRU5ErkJggg==';
|
||||
const url=`data:image/png;base64,${image}`;
|
||||
@ -778,24 +779,24 @@ test('main request archives summarize image bytes by default and support raw pay
|
||||
t.after(x.close);
|
||||
const readImageUrl=payload=>payload.messages.flatMap(row=>Array.isArray(row.content)?row.content:[])
|
||||
.find(part=>part.type==='image_url')?.image_url.url;
|
||||
for(const raw of [false,true]){
|
||||
if(raw)process.env[setting]='1';else delete process.env[setting];
|
||||
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
|
||||
assert.equal(readImageUrl(x.requests.at(-1)),url);
|
||||
const stored=await fs.readFile(path.join(x.store.dir,'payloads',x.ids.at(-1)+'.json'),'utf8');
|
||||
assert.equal(readImageUrl(JSON.parse(stored)),raw?url:`[image-base64-omitted:${Buffer.from(image,'base64').length}B]`);
|
||||
assert.equal(stored.includes(image),raw);
|
||||
}
|
||||
const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
|
||||
await x.host.prompt('检查附件',{referenceContent:[{label:'测试图',image,mimeType:'image/png'}]});
|
||||
assert.equal(readImageUrl(x.requests.at(-1)),url);
|
||||
await assert.rejects(fs.access(path.join(x.store.dir,'payloads')), {code:'ENOENT'});
|
||||
const journal=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');
|
||||
assert.equal(journal.includes(image),false);
|
||||
const events=journal.trim().split('\n').map(line=>JSON.parse(line));
|
||||
const budget=events.find(event=>event.type==='context_budget');
|
||||
assert.equal(budget.originalChars-budget.inputChars,image.length);
|
||||
const requests=events.filter(event=>event.type==='serialized_request');
|
||||
const requests=events.filter(event=>event.type==='provider_prepared');
|
||||
assert.deepEqual(requests.map(event=>event.id),x.ids);
|
||||
for(const event of requests){
|
||||
assert.match(event.bodyHash,/^[a-f0-9]{64}$/u);
|
||||
assert.ok(event.keys.includes('messages'));
|
||||
assert.ok(Array.isArray(event.tools));
|
||||
}
|
||||
assert.equal(requests[0].purpose,'conversation');
|
||||
assert.ok(events.some(event=>event.type==='provider_finished' && event.id===x.ids[0]));
|
||||
process.env[setting]='1';
|
||||
await x.host.prompt('继续核对');
|
||||
const debugFile=path.join(x.store.dir,'payloads',x.ids.at(-1)+'.json');
|
||||
const archived=JSON.parse(await fs.readFile(debugFile,'utf8'));
|
||||
assert.equal(readImageUrl(archived),url);
|
||||
assert.equal(Object.hasOwn(archived,'headers'),false);
|
||||
});
|
||||
|
||||
test('a worker can change course after many identical calls without terminating',async t=>{
|
||||
|
||||
@ -115,12 +115,18 @@ test('P01 local facts, document evidence and delivery reopen without a collabora
|
||||
});
|
||||
|
||||
test('P02 stores the exact complete prompt and rejects changes at the same revision', async t => {
|
||||
const { open, repo } = await fixture(t);
|
||||
const { file, open, repo } = await fixture(t);
|
||||
const draft = request('long', { prompt: '自然光与质感。\n'.repeat(300) + '末尾必需限制:只保留一件。\r\n' });
|
||||
assert.ok(draft.spec.prompt.length > 2000);
|
||||
repo.saveImageRequest(draft);
|
||||
assert.equal(open().readVersion('prompt', 'long', 1).prompt, draft.spec.prompt);
|
||||
assert.equal(open().readImageRequest('long').prepared.spec.prompt, draft.spec.prompt);
|
||||
const db = new DatabaseSync(file, { readOnly:true });
|
||||
try {
|
||||
assert.equal(db.prepare("SELECT count(*) AS count FROM project_versions WHERE kind = 'prompt'").get().count, 0);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
assert.throws(() => repo.saveImageRequest(request('long', { prompt: 'changed' })), /新版本/);
|
||||
});
|
||||
|
||||
|
||||
@ -190,7 +190,9 @@ fn identifier(s: &str) -> R<&str> {
|
||||
fn read_json(path: &Path) -> R<Value> {
|
||||
let mut bytes = Vec::new();
|
||||
fs::File::open(path).map_err(|error| {
|
||||
log::warn!("local project record open failed: {}: {error}", path.display());
|
||||
if error.kind() != std::io::ErrorKind::NotFound {
|
||||
log::warn!("local project record open failed: {}: {error}", path.display());
|
||||
}
|
||||
"本机记录无法读取,请保留文件"
|
||||
})?.take(2_000_001).read_to_end(&mut bytes).map_err(|_| "本机记录读取中断,请保留文件")?;
|
||||
if bytes.len() > 2_000_000 {
|
||||
@ -1122,6 +1124,19 @@ impl Backend {
|
||||
photocraft_format::atomic_write(&path, &bytes).map_err(|_| "图片保存失败")?;
|
||||
Ok(json!({"doc":id,"path":path.to_string_lossy(),"reference":reference}))
|
||||
}
|
||||
fn serialize_draft(&self, doc: &Document) -> R<Vec<u8>> {
|
||||
self.draft_zip_writer.lock().map_err(|_| "草稿保存服务不可用,旧草稿已保留")?
|
||||
.get_or_insert_with(|| {
|
||||
let mut writer = photocraft_format::PcraftWriter::new();
|
||||
// Reuse the large compressed PSD blocks across consecutive draft saves.
|
||||
writer.set_compressed_cache_budget(2304 << 20);
|
||||
writer
|
||||
})
|
||||
.save_zip(doc, &Default::default())
|
||||
.map(|(bytes, _)| bytes)
|
||||
.map_err(|_| "原生项目序列化失败,旧草稿已保留".into())
|
||||
}
|
||||
|
||||
fn save_product_view(&self, doc: &Document) -> R<Value> {
|
||||
self.ensure_owner(doc.id.0)?;
|
||||
let dir = self.project_dir(doc.id.0)?;
|
||||
@ -1129,7 +1144,7 @@ impl Backend {
|
||||
if let Some((first, last)) = missing.first().zip(missing.last()) {
|
||||
return Err(format!("画布缺少 {first} 至 {last} 的原稿图层,已保留上一份编辑稿"));
|
||||
}
|
||||
let bytes = photocraft_format::save_to_bytes(doc, &Default::default()).map_err(|_| "当前输出序列化失败,旧草稿已保留")?;
|
||||
let bytes = self.serialize_draft(doc)?;
|
||||
let _guard = sync::context_guard();
|
||||
self.ensure_owner(doc.id.0)?;
|
||||
original_project_present(&dir)?;
|
||||
@ -1168,15 +1183,7 @@ impl Backend {
|
||||
self.last_saved.insert(doc.id.0, saved_identity.clone());
|
||||
} else {
|
||||
let serialize_started = Instant::now();
|
||||
let (bytes, _) = self.draft_zip_writer.lock().map_err(|_| "草稿保存服务不可用,旧草稿已保留")?
|
||||
.get_or_insert_with(|| {
|
||||
let mut writer = photocraft_format::PcraftWriter::new();
|
||||
// A single large PSD linked-object block can fill most of a local draft.
|
||||
// Keep its compressed allocation across consecutive document revisions.
|
||||
writer.set_compressed_cache_budget(2304 << 20);
|
||||
writer
|
||||
})
|
||||
.save_zip(&doc, &Default::default()).map_err(|_| "原生项目序列化失败,旧草稿已保留")?;
|
||||
let bytes = self.serialize_draft(&doc)?;
|
||||
let write_started = Instant::now();
|
||||
let workspace_saved = canvas_workspace::exists(&dir)
|
||||
&& canvas_workspace::save_edited_output(&dir, &doc, &bytes)?;
|
||||
|
||||
@ -209,6 +209,28 @@ fn reference_png(name: &str, bytes: &[u8]) -> R<Vec<u8>> {
|
||||
// Same bounded RGBA conversion and metadata removal as ordinary references.
|
||||
png(&rendered.bytes)
|
||||
}
|
||||
|
||||
fn read_staged_image(path: &Path) -> R<Option<Vec<u8>>> {
|
||||
let file = match fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(_) => return Err("原结果读取失败".into()),
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
file.take(IMAGE_BYTES + 1).read_to_end(&mut bytes).map_err(|_| "原结果读取失败")?;
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
fn remove_settled_response(dir: &Path, task: &Value) {
|
||||
if matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired")) {
|
||||
for name in ["response-image.bin", "response.json"] {
|
||||
let file = dir.join(name);
|
||||
if let Err(error) = fs::remove_file(&file) && error.kind() != std::io::ErrorKind::NotFound {
|
||||
log::warn!("temporary image response cleanup failed: {}: {error}", file.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn job_save(dir: &Path, t: &Value) -> R<()> {
|
||||
let _guard = sync::context_guard();
|
||||
job_save_locked(dir, t, false)
|
||||
@ -952,8 +974,12 @@ impl Backend {
|
||||
};
|
||||
let result = (|| -> R<()> {
|
||||
let raw_file = taskdir.join("response.json");
|
||||
let mut deferred_result_ready = false;
|
||||
let mut raw = if raw_file.exists() {
|
||||
let image_file = taskdir.join("response-image.bin");
|
||||
let saved_image = read_staged_image(&image_file)?;
|
||||
let mut deferred_result_ready = saved_image.is_some();
|
||||
let mut raw = if saved_image.is_some() {
|
||||
Value::Null
|
||||
} else if raw_file.exists() {
|
||||
let mut b = Vec::new();
|
||||
fs::File::open(&raw_file).map_err(|_| "原结果读取失败")?.take(RESPONSE_BYTES + 1).read_to_end(&mut b).map_err(|_| "原结果读取失败")?;
|
||||
if b.len() as u64 > RESPONSE_BYTES {
|
||||
@ -1140,39 +1166,49 @@ impl Backend {
|
||||
if raw["model"].is_string() && raw["model"] != t["modelId"] {
|
||||
return Err("原结果与任务模型不一致,未应用".into());
|
||||
}
|
||||
check()?;
|
||||
let mut safe_response = raw.clone();
|
||||
transfer::redact(&mut safe_response);
|
||||
job_bytes(&dir, &raw_file, &serde_json::to_vec(&safe_response).map_err(|_| "原响应保存失败")?, check).map_err(|_| "原结果保存失败,请保留原请求号")?;
|
||||
let outputs = raw["data"].as_array().filter(|a| a.len() == 1).ok_or("98k图片结果结构无法确认;不会重发")?;
|
||||
let out = &outputs[0];
|
||||
progress("正在下载并检查图片…", false);
|
||||
let bytes = if let Some(b) = out["b64_json"].as_str() {
|
||||
if b.len() > 28 * 1024 * 1024 {
|
||||
return Err("图片超过20MiB限制".into());
|
||||
}
|
||||
STANDARD.decode(b).map_err(|_| "原图片编码无效")?
|
||||
let bytes = if let Some(bytes) = saved_image {
|
||||
bytes
|
||||
} else {
|
||||
let url = asset_url(out["url"].as_str().ok_or("原响应没有可下载的图片")?)?;
|
||||
self.image_validate(deadline)?;
|
||||
check()?;
|
||||
let r = self
|
||||
.http
|
||||
.get(url)
|
||||
.bearer_auth(key)
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
|
||||
.send()
|
||||
.map_err(|_| "图片下载连接中断,保留原结果后可重取")?;
|
||||
if r.status() == reqwest::StatusCode::GONE {
|
||||
retain_result_expiry(&mut t, "image-asset");
|
||||
return Ok(());
|
||||
let outputs = raw["data"].as_array().filter(|a| a.len() == 1).ok_or("98k图片结果结构无法确认;不会重发")?;
|
||||
let out = &outputs[0];
|
||||
if let Some(b) = out["b64_json"].as_str() {
|
||||
if b.len() > 28 * 1024 * 1024 {
|
||||
return Err("图片超过20MiB限制".into());
|
||||
}
|
||||
let bytes = STANDARD.decode(b).map_err(|_| "原图片编码无效")?;
|
||||
if bytes.len() as u64 > IMAGE_BYTES {
|
||||
return Err("图片超过20MiB限制".into());
|
||||
}
|
||||
job_bytes(&dir, &image_file, &bytes, check).map_err(|_| "原结果保存失败,请保留原请求号")?;
|
||||
bytes
|
||||
} else {
|
||||
let raw_url = out["url"].as_str().ok_or("原响应没有可下载的图片")?;
|
||||
let url = asset_url(raw_url)?;
|
||||
if !raw_file.exists() {
|
||||
job_json(&dir, &raw_file, &json!({"data":[{"url":raw_url}]}), check)
|
||||
.map_err(|_| "原结果保存失败,请保留原请求号")?;
|
||||
}
|
||||
self.image_validate(deadline)?;
|
||||
check()?;
|
||||
let r = self
|
||||
.http
|
||||
.get(url)
|
||||
.bearer_auth(key)
|
||||
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
|
||||
.send()
|
||||
.map_err(|_| "图片下载连接中断,保留原结果后可重取")?;
|
||||
if r.status() == reqwest::StatusCode::GONE {
|
||||
retain_result_expiry(&mut t, "image-asset");
|
||||
return Ok(());
|
||||
}
|
||||
if !r.status().is_success() {
|
||||
return Err(format!("98k图片下载 HTTP {},原结果已保留", r.status().as_u16()));
|
||||
}
|
||||
let mut b = Vec::new();
|
||||
r.take(IMAGE_BYTES + 1).read_to_end(&mut b).map_err(|_| "图片下载中断")?;
|
||||
b
|
||||
}
|
||||
if !r.status().is_success() {
|
||||
return Err(format!("98k图片下载 HTTP {},原结果已保留", r.status().as_u16()));
|
||||
}
|
||||
let mut b = Vec::new();
|
||||
r.take(IMAGE_BYTES + 1).read_to_end(&mut b).map_err(|_| "图片下载中断")?;
|
||||
b
|
||||
};
|
||||
if bytes.len() as u64 > IMAGE_BYTES {
|
||||
return Err("图片超过20MiB限制".into());
|
||||
@ -1212,6 +1248,7 @@ impl Backend {
|
||||
// Concurrent late GETs may have settled a stronger terminal outcome.
|
||||
// Report the durable original journal, never the discarded stale copy.
|
||||
t = read_json(&taskdir.join("task.json"))?;
|
||||
remove_settled_response(&taskdir, &t);
|
||||
Ok(public(&t, id, &self.auth["account"], &self.origin))
|
||||
}
|
||||
pub(super) fn image_applied(&self, input: &Value) -> R<Value> {
|
||||
@ -1245,6 +1282,38 @@ impl Backend {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn response_is_recoverable_until_the_original_request_is_settled() {
|
||||
let fixture = canvas_post_fixture();
|
||||
let mut task = fixture.task.clone();
|
||||
let file = image_request_file(&fixture.dir, task["id"].as_str().unwrap()).unwrap();
|
||||
let job = file.parent().unwrap();
|
||||
let response = job.join("response-image.bin");
|
||||
let request_id = Uuid::new_v4().to_string();
|
||||
task["requestId"] = json!(request_id);
|
||||
task["phase"] = json!("unknown");
|
||||
job_save(&fixture.dir, &task).unwrap();
|
||||
fs::write(&response, b"original image bytes").unwrap();
|
||||
let mut reopened = read_json(&file).unwrap();
|
||||
remove_settled_response(job, &reopened);
|
||||
assert_eq!(read_staged_image(&response).unwrap().unwrap(), b"original image bytes");
|
||||
assert_eq!(reopened["requestId"], request_id);
|
||||
|
||||
let artifact = job.join("generated.png");
|
||||
fs::write(&artifact, b"fixture image").unwrap();
|
||||
reopened["artifact"] = json!(artifact);
|
||||
reopened["phase"] = json!("complete");
|
||||
job_save(&fixture.dir, &reopened).unwrap();
|
||||
let durable = read_json(&file).unwrap();
|
||||
remove_settled_response(job, &durable);
|
||||
|
||||
assert_eq!(read_staged_image(&response).unwrap(), None);
|
||||
assert!(artifact.is_file());
|
||||
let receipt = settled_recovery(&read_json(&file).unwrap(), 1, &json!({"id":"local"}), "local").unwrap();
|
||||
assert_eq!(receipt["requestId"], request_id);
|
||||
assert_eq!(receipt["phase"], "complete");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepared_image_request_round_trips_and_freezes_exact_transport_inputs() {
|
||||
let fixture = canvas_post_fixture();
|
||||
|
||||
@ -371,11 +371,13 @@ mod tests {
|
||||
let root = temp.path().join("internal");
|
||||
fs::create_dir(&root).unwrap();
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let doc = Document::new("演示", Size::new(60, 40), ColorMode::Rgb, SampleType::U8);
|
||||
let mut doc = Document::new("演示", Size::new(60, 40), ColorMode::Rgb, SampleType::U8);
|
||||
doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", std::sync::Arc::new(vec![123; 1 << 20])));
|
||||
fs::write(root.join("canvas.pcraft"), photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap()).unwrap();
|
||||
let job = root.join("image-jobs").join(Uuid::new_v4().to_string());
|
||||
fs::create_dir_all(&job).unwrap();
|
||||
fs::write(job.join("generated.png"), b"candidate pixels").unwrap();
|
||||
fs::write(job.join("response-image.bin"), b"unsettled cache").unwrap();
|
||||
write_json(&job.join("task.json"), &json!({"artifact":job.join("generated.png"),"phase":"complete"})).unwrap();
|
||||
let delivery = root.join("product-exports").join("variant");
|
||||
let generation = delivery.join("generations").join("generation-published");
|
||||
@ -401,12 +403,14 @@ mod tests {
|
||||
let reopened = photocraft_format::load_path(&restored.join("canvas.pcraft")).unwrap();
|
||||
assert_eq!(reopened.name, doc.name);
|
||||
assert_eq!(reopened.size, doc.size);
|
||||
assert_eq!(reopened.metadata.psd_global_blocks, doc.metadata.psd_global_blocks);
|
||||
let metadata = read_json(&restored.join(CONTEXT)).unwrap();
|
||||
assert_eq!(metadata["composer"], context["composer"]);
|
||||
assert!(metadata.get("messages").is_none());
|
||||
assert_eq!(metadata["projectFile"], context["projectFile"]);
|
||||
let job = restored.join(job.strip_prefix(&root).unwrap());
|
||||
assert_eq!(fs::read(job.join("generated.png")).unwrap(), b"candidate pixels");
|
||||
assert!(!job.join("response-image.bin").exists());
|
||||
assert_eq!(read_json(&job.join("task.json")).unwrap()["artifact"], json!(job.join("generated.png")));
|
||||
let exported = restored.join(generation.strip_prefix(&root).unwrap()).join("detail.pcraft");
|
||||
let restored_receipt = restored.join(delivery.strip_prefix(&root).unwrap()).join("detail.json");
|
||||
@ -422,7 +426,10 @@ mod tests {
|
||||
let resource_folder = manifest["resources"].as_str().unwrap();
|
||||
fs::rename(temp.path().join(resource_folder), keep.join(resource_folder)).unwrap();
|
||||
fs::rename(file, &moved).unwrap();
|
||||
assert_eq!(open(&moved, &temp.path().join("another-profile"), "guest").unwrap(), id);
|
||||
let moved_projects = temp.path().join("another-profile");
|
||||
assert_eq!(open(&moved, &moved_projects, "guest").unwrap(), id);
|
||||
let moved_canvas = photocraft_format::load_path(&moved_projects.join(&id).join("canvas.pcraft")).unwrap();
|
||||
assert_eq!(moved_canvas.metadata.psd_global_blocks, doc.metadata.psd_global_blocks);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user