Merge commit '60a5351ec2373ee56584b9bf91d90174dda34566' into feat/xiaoyi-integration-core
# Conflicts: # apps/detail-agent-pi/src/production-operations.mjs # apps/detail-agent-pi/test/production-operations.test.mjs
This commit is contained in:
commit
4104355bc5
@ -1,138 +1,147 @@
|
||||
"""Check an isolated run's delivered artwork against the saved canvas mappings."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import zipfile
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
OUTPUTS = ("detail", "main_images", "sku_images")
|
||||
WINDOWS_PREFIX = chr(92) * 2 + "?" + chr(92)
|
||||
|
||||
|
||||
def absolute_path(file):
|
||||
file = Path(file)
|
||||
if os.name == "nt" and not str(file).startswith(WINDOWS_PREFIX):
|
||||
return Path(WINDOWS_PREFIX + str(file.absolute()))
|
||||
return file.absolute()
|
||||
|
||||
|
||||
def read_json(file):
|
||||
with file.open(encoding="utf-8-sig") as stream:
|
||||
return json.load(stream)
|
||||
|
||||
|
||||
def layers_by_id(layers, parent_visible=True):
|
||||
for layer in layers:
|
||||
visible = parent_visible and layer["visible"] and layer["opacity"] > 0
|
||||
yield layer["id"], (visible, layer["content"])
|
||||
yield from layers_by_id(layer["content"].get("children", []), visible)
|
||||
|
||||
|
||||
def checked_file(record, generation, directory):
|
||||
file = absolute_path(record["path"])
|
||||
if record["generationId"] != generation or file.parent.parent != directory:
|
||||
raise ValueError(f"{file.name} 不属于本次交付版本")
|
||||
with file.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if digest != record["sha256"] or file.stat().st_size != record["sizeBytes"]:
|
||||
raise ValueError(f"{file.name} 内容与交付回执不一致")
|
||||
return file
|
||||
|
||||
|
||||
def inspect_receipt(receipt_file):
|
||||
receipt = read_json(receipt_file)
|
||||
generation = receipt["generationId"]
|
||||
directory = receipt_file.parent / "generations"
|
||||
source = receipt["sourceDocument"]
|
||||
files = []
|
||||
for photo in receipt["files"] + receipt.get("screenFiles", []):
|
||||
file = checked_file(photo, generation, directory)
|
||||
with Image.open(file) as image:
|
||||
image.load()
|
||||
if image.size != (photo["width"], photo["height"]):
|
||||
raise ValueError(f"{file.name} 解码尺寸与交付回执不一致")
|
||||
files.append(str(file))
|
||||
if not files:
|
||||
raise ValueError("没有导出图片")
|
||||
editable = checked_file(source, generation, directory)
|
||||
with zipfile.ZipFile(editable) as bundle:
|
||||
document = json.loads(bundle.read("manifest.json"))["document"]
|
||||
if document["size"] != {"width": source["width"], "height": source["height"]}:
|
||||
raise ValueError("可编辑画布尺寸与交付回执不一致")
|
||||
metadata = dict(document["metadata"]["text"])
|
||||
mapping = json.loads(metadata["jiansun.slot-mapping.v1"])
|
||||
if any(mapping[key] != receipt[value] for key, value in (
|
||||
("workspaceId", "workspaceId"), ("templateHash", "templateHash"),
|
||||
("variantId", "variantId"), ("component", "outputId"),
|
||||
)):
|
||||
raise ValueError("可编辑画布与交付身份不一致")
|
||||
pages = mapping["outputs"]
|
||||
screens = [(page["top"], page["width"], page["height"]) for page in pages]
|
||||
regions = lambda rows: [(row["top"], row["width"], row["height"]) for row in rows]
|
||||
if receipt["outputId"] == "detail":
|
||||
expected_long = (0, max(width for _, width, _ in screens), max(top + height for top, _, height in screens))
|
||||
if regions(receipt["files"]) != [expected_long] or regions(receipt.get("screenFiles", [])) != screens:
|
||||
raise ValueError("详情长图或分屏集与实际画布页面不一致")
|
||||
elif regions(receipt["files"]) != screens:
|
||||
raise ValueError("输出图片集与实际画布页面不一致")
|
||||
layers = dict(layers_by_id(document["layers"]))
|
||||
fixed = mapping.get("fixedTemplateText", {})
|
||||
blank_reasons = receipt.get("blankCopyReasons", {})
|
||||
fields = []
|
||||
issues = []
|
||||
for page in pages:
|
||||
for field in page["mapping"]["fields"]:
|
||||
layer = field["nativeLayerId"]
|
||||
label = f'{page["documentId"]}/{field["fieldId"]}'
|
||||
visible, content = layers.get(layer, (False, {}))
|
||||
if field["kind"] == "image":
|
||||
adopted = metadata.get(f'jiansun.adopted.{receipt["variantId"]}.{field["slotId"]}')
|
||||
if not visible or content.get("kind") != "smart" or not adopted:
|
||||
issues.append({"field": label, "problem": "缺已采纳并可见的图片"})
|
||||
fields.append({"field": label, "kind": "image", "adopted": adopted})
|
||||
elif field["kind"] == "text":
|
||||
current = content.get("text", "").strip()
|
||||
sample = (field.get("originalText") or "").strip()
|
||||
kept = bool(current and fixed.get(str(layer), "").strip() == current)
|
||||
blank = blank_reasons.get(str(layer), {})
|
||||
blank_reason = blank.get("reason") if (
|
||||
not current and content.get("kind") == "text" and blank.get("field") == field["fieldId"]
|
||||
) else None
|
||||
if not visible or (not current and not blank_reason):
|
||||
issues.append({"field": label, "problem": "文字缺失或不可见"})
|
||||
elif current == sample and not kept:
|
||||
issues.append({"field": label, "problem": "仍是模板样稿,缺保留依据"})
|
||||
fields.append({"field": label, "kind": "text", "changed": current != sample,
|
||||
"keepReason": "模板发布许可" if kept else blank_reason})
|
||||
return {"generation": generation, "files": files, "editable": str(editable),
|
||||
"fields": fields, "issues": issues}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("project", type=Path, help="独立验收配置中的本地项目目录")
|
||||
parser.add_argument("report", type=Path, help="验收日志输出文件")
|
||||
args = parser.parse_args()
|
||||
project = absolute_path(args.project)
|
||||
result = {output: [] for output in OUTPUTS}
|
||||
for receipt in sorted((project / "product-exports").glob("*/*.json")):
|
||||
if receipt.stem not in result:
|
||||
continue
|
||||
try:
|
||||
result[receipt.stem].append(inspect_receipt(receipt))
|
||||
except (OSError, ValueError, KeyError, zipfile.BadZipFile) as error:
|
||||
result[receipt.stem].append({"receipt": str(receipt), "issues": [{"problem": str(error)}]})
|
||||
passed = all(generations and all(item.get("files") and not item["issues"] for item in generations)
|
||||
for generations in result.values())
|
||||
args.report.write_text(json.dumps({"passed": passed, "outputs": result}, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8")
|
||||
return 0 if passed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
"""Check an isolated run's delivered artwork against the saved canvas mappings."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import zipfile
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
OUTPUTS = ("detail", "main_images", "sku_images")
|
||||
WINDOWS_PREFIX = chr(92) * 2 + "?" + chr(92)
|
||||
|
||||
|
||||
def absolute_path(file):
|
||||
file = Path(file)
|
||||
if os.name == "nt" and not str(file).startswith(WINDOWS_PREFIX):
|
||||
return Path(WINDOWS_PREFIX + str(file.absolute()))
|
||||
return file.absolute()
|
||||
|
||||
|
||||
def read_json(file):
|
||||
with file.open(encoding="utf-8-sig") as stream:
|
||||
return json.load(stream)
|
||||
|
||||
|
||||
def layers_by_id(layers, parent_visible=True):
|
||||
for layer in layers:
|
||||
visible = parent_visible and layer["visible"] and layer["opacity"] > 0
|
||||
yield layer["id"], (visible, layer["content"])
|
||||
yield from layers_by_id(layer["content"].get("children", []), visible)
|
||||
|
||||
|
||||
def checked_file(record, generation, directory):
|
||||
file = absolute_path(record["path"])
|
||||
if record["generationId"] != generation or file.parent.parent != directory:
|
||||
raise ValueError(f"{file.name} 不属于本次交付版本")
|
||||
with file.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if digest != record["sha256"] or file.stat().st_size != record["sizeBytes"]:
|
||||
raise ValueError(f"{file.name} 内容与交付回执不一致")
|
||||
return file
|
||||
|
||||
|
||||
def inspect_receipt(receipt_file):
|
||||
receipt = read_json(receipt_file)
|
||||
generation = receipt["generationId"]
|
||||
directory = receipt_file.parent / "generations"
|
||||
if "publishedPointer" in receipt:
|
||||
manifest = Path("generations") / generation / "manifest.json"
|
||||
if Path(generation).name != generation or not generation.startswith("generation-") or Path(receipt["publishedPointer"]) != manifest:
|
||||
raise ValueError("交付指针无效")
|
||||
published = read_json(receipt_file.parent / manifest)
|
||||
identity = ("generationId", "workspaceId", "outputId", "variantId")
|
||||
if any(published[key] != receipt[key] for key in identity):
|
||||
raise ValueError("交付指针与清单不一致")
|
||||
receipt = published
|
||||
source = receipt["sourceDocument"]
|
||||
files = []
|
||||
for photo in receipt["files"] + receipt.get("screenFiles", []):
|
||||
file = checked_file(photo, generation, directory)
|
||||
with Image.open(file) as image:
|
||||
image.load()
|
||||
if image.size != (photo["width"], photo["height"]):
|
||||
raise ValueError(f"{file.name} 解码尺寸与交付回执不一致")
|
||||
files.append(str(file))
|
||||
if not files:
|
||||
raise ValueError("没有导出图片")
|
||||
editable = checked_file(source, generation, directory)
|
||||
with zipfile.ZipFile(editable) as bundle:
|
||||
document = json.loads(bundle.read("manifest.json"))["document"]
|
||||
if document["size"] != {"width": source["width"], "height": source["height"]}:
|
||||
raise ValueError("可编辑画布尺寸与交付回执不一致")
|
||||
metadata = dict(document["metadata"]["text"])
|
||||
mapping = json.loads(metadata["jiansun.slot-mapping.v1"])
|
||||
if any(mapping[key] != receipt[value] for key, value in (
|
||||
("workspaceId", "workspaceId"), ("templateHash", "templateHash"),
|
||||
("variantId", "variantId"), ("component", "outputId"),
|
||||
)):
|
||||
raise ValueError("可编辑画布与交付身份不一致")
|
||||
pages = mapping["outputs"]
|
||||
screens = [(page["top"], page["width"], page["height"]) for page in pages]
|
||||
regions = lambda rows: [(row["top"], row["width"], row["height"]) for row in rows]
|
||||
if receipt["outputId"] == "detail":
|
||||
expected_long = (0, max(width for _, width, _ in screens), max(top + height for top, _, height in screens))
|
||||
if regions(receipt["files"]) != [expected_long] or regions(receipt.get("screenFiles", [])) != screens:
|
||||
raise ValueError("详情长图或分屏集与实际画布页面不一致")
|
||||
elif regions(receipt["files"]) != screens:
|
||||
raise ValueError("输出图片集与实际画布页面不一致")
|
||||
layers = dict(layers_by_id(document["layers"]))
|
||||
fixed = mapping.get("fixedTemplateText", {})
|
||||
blank_reasons = receipt.get("blankCopyReasons", {})
|
||||
fields = []
|
||||
issues = []
|
||||
for page in pages:
|
||||
for field in page["mapping"]["fields"]:
|
||||
layer = field["nativeLayerId"]
|
||||
label = f'{page["documentId"]}/{field["fieldId"]}'
|
||||
visible, content = layers.get(layer, (False, {}))
|
||||
if field["kind"] == "image":
|
||||
adopted = metadata.get(f'jiansun.adopted.{receipt["variantId"]}.{field["slotId"]}')
|
||||
if not visible or content.get("kind") != "smart" or not adopted:
|
||||
issues.append({"field": label, "problem": "缺已采纳并可见的图片"})
|
||||
fields.append({"field": label, "kind": "image", "adopted": adopted})
|
||||
elif field["kind"] == "text":
|
||||
current = content.get("text", "").strip()
|
||||
sample = (field.get("originalText") or "").strip()
|
||||
kept = bool(current and fixed.get(str(layer), "").strip() == current)
|
||||
blank = blank_reasons.get(str(layer), {})
|
||||
blank_reason = blank.get("reason") if (
|
||||
not current and content.get("kind") == "text" and blank.get("field") == field["fieldId"]
|
||||
) else None
|
||||
if not visible or (not current and not blank_reason):
|
||||
issues.append({"field": label, "problem": "文字缺失或不可见"})
|
||||
elif current == sample and not kept:
|
||||
issues.append({"field": label, "problem": "仍是模板样稿,缺保留依据"})
|
||||
fields.append({"field": label, "kind": "text", "changed": current != sample,
|
||||
"keepReason": "模板发布许可" if kept else blank_reason})
|
||||
return {"generation": generation, "files": files, "editable": str(editable),
|
||||
"fields": fields, "issues": issues}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("project", type=Path, help="独立验收配置中的本地项目目录")
|
||||
parser.add_argument("report", type=Path, help="验收日志输出文件")
|
||||
args = parser.parse_args()
|
||||
project = absolute_path(args.project)
|
||||
result = {output: [] for output in OUTPUTS}
|
||||
for receipt in sorted((project / "product-exports").glob("*/*.json")):
|
||||
if receipt.stem not in result:
|
||||
continue
|
||||
try:
|
||||
result[receipt.stem].append(inspect_receipt(receipt))
|
||||
except (OSError, ValueError, KeyError, zipfile.BadZipFile) as error:
|
||||
result[receipt.stem].append({"receipt": str(receipt), "issues": [{"problem": str(error)}]})
|
||||
passed = all(generations and all(item.get("files") and not item["issues"] for item in generations)
|
||||
for generations in result.values())
|
||||
args.report.write_text(json.dumps({"passed": passed, "outputs": result}, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8")
|
||||
return 0 if passed else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
@ -1,66 +1,108 @@
|
||||
// UI activity is an allowlisted description of SDK events, never tool arguments,
|
||||
// tool results, provider errors or arbitrary model-generated text.
|
||||
const labels = Object.freeze({
|
||||
ask_user: '等待用户回复',
|
||||
context_read: '读取项目规则', memory_set: '记录事实', memory_search: '检索历史',
|
||||
tool_develop: '编写并测试工具', tool_run: '运行工具', canvas_read: '读取画布', canvas_template_image: '读取模板原图',
|
||||
canvas_edit: '更新图层', canvas_preview: '预览修改', copywriting_options: '生成卖点选项',copywriting_fields:'准备逐格文案', workflow_read: '读取创作进度', workflow_navigate: '切换创作视图',
|
||||
workflow_propose: '添加待审核建议', workflow_execute: '执行创作操作',
|
||||
native_catalog: '查询原生命令', native_call: '执行原生操作', native_reconcile: '核查原生任务', codemode: '组合画布操作', tool_search: '查找工具',
|
||||
canvas_candidate_image: '核对图位和候选', bash: '运行项目终端',
|
||||
open_production_output: '打开制作画布',
|
||||
plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则',
|
||||
read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图',
|
||||
read_slot_images: '查看图位图片', use_product_image: '取用商品实拍',
|
||||
prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片',
|
||||
await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求',
|
||||
read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选',
|
||||
read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核',
|
||||
defer_production_output: '保留当前草稿', check_image_slots: '发起验图', finish_production: '提交成品导出',
|
||||
save_product_strategy: '保存商品策划', review_product_strategy: '核对卖点证据',
|
||||
plan_page_copy: '规划整页卖点', write_copy_fields: '填写画布文案', review_page_copy: '复核整页文案',
|
||||
});
|
||||
const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined;
|
||||
const safeNumber = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
||||
|
||||
// Read this once from pi-begin, whose requestScope is frozen by the native host.
|
||||
// IDs outside the expected format are omitted instead of copied as free text.
|
||||
export function activityScope(identity, canvas, begun) {
|
||||
const request = begun?.context?.requestScope;
|
||||
const subject = request?.subject;
|
||||
// Production canvas state omits the full context. Its active begin receipt
|
||||
// still confirms the document carried by this native connection.
|
||||
const documentId = begun?.context?.id ?? (
|
||||
begun?.conversationActive === true && begun.run === canvas?.run ? canvas?.documentId : undefined
|
||||
);
|
||||
const values = {
|
||||
accountScope: safeId(identity?.scope), project: safeId(identity?.project),
|
||||
documentId: safeNumber(documentId), run: safeId(canvas?.run),
|
||||
outputId: safeId(request?.outputId), variantId: safeId(request?.variantId),
|
||||
slotId: safeId(subject?.slotId), candidateId: safeId(subject?.candidateId),
|
||||
revision: safeNumber(begun?.revision),
|
||||
};
|
||||
return Object.freeze(Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)));
|
||||
}
|
||||
|
||||
function details(event) {
|
||||
const toolName = Object.hasOwn(labels, event.toolName) ? event.toolName : 'other';
|
||||
const stopped = event.isError && ['write_revoked','revision_conflict','cancelled']
|
||||
.includes(event.result?.details?.failure?.category);
|
||||
const pending = typeof event.result?.details?.pendingOriginal === 'string';
|
||||
const status = event.type === 'tool_execution_start' ? 'started' : stopped ? 'stopped' :
|
||||
event.isError ? 'failed' : pending ? 'pending' : 'completed';
|
||||
const label = labels[toolName] || '工具';
|
||||
const summary = `${{ started: '开始', stopped: '已停止', failed: '失败', pending: '待核查', completed: '完成' }[status]}:${label}`;
|
||||
return { toolName, status, summary };
|
||||
}
|
||||
|
||||
export function activitySummary(event) { return details(event).summary; }
|
||||
|
||||
export function toolActivity(event, scope, timestampMs = Date.now()) {
|
||||
if (!['tool_execution_start', 'tool_execution_end'].includes(event?.type)) return null;
|
||||
const toolCallId = safeId(event.toolCallId);
|
||||
if (!toolCallId || safeNumber(timestampMs) === undefined) return null;
|
||||
const durationMs = safeNumber(event.durationMs);
|
||||
return { version: 1, type: 'tool', toolCallId, ...details(event), timestampMs, ...(durationMs === undefined ? {} : { durationMs }), scope };
|
||||
}
|
||||
// UI activity is an allowlisted description of SDK events, never tool arguments,
|
||||
// tool results, provider errors or arbitrary model-generated text.
|
||||
const labels = Object.freeze({
|
||||
ask_user: '等待用户回复',
|
||||
context_read: '读取项目规则', memory_set: '记录事实', memory_search: '检索历史',
|
||||
tool_develop: '编写并测试工具', tool_run: '运行工具', canvas_read: '读取画布', canvas_template_image: '读取模板原图',
|
||||
canvas_edit: '更新图层', canvas_preview: '预览修改', copywriting_options: '生成卖点选项',copywriting_fields:'准备逐格文案', workflow_read: '读取创作进度', workflow_navigate: '切换创作视图',
|
||||
workflow_propose: '添加待审核建议', workflow_execute: '执行创作操作',
|
||||
native_catalog: '查询原生命令', native_call: '执行原生操作', native_reconcile: '核查原生任务', codemode: '组合画布操作', tool_search: '查找工具',
|
||||
canvas_candidate_image: '核对图位和候选', bash: '运行项目终端',
|
||||
open_production_output: '打开制作画布',
|
||||
plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则',
|
||||
read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图',
|
||||
read_slot_images: '查看图位图片', use_product_image: '取用商品实拍',
|
||||
prepare_image_request: '准备生图请求', dispatch_image_request: '生成候选图片',
|
||||
await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求',
|
||||
read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选',
|
||||
read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核',
|
||||
defer_production_output: '保留当前草稿', check_image_slots: '发起验图', finish_production: '提交成品导出',
|
||||
save_product_strategy: '保存商品策划', review_product_strategy: '核对卖点证据',
|
||||
plan_page_copy: '规划整页卖点', write_copy_fields: '填写画布文案', review_page_copy: '复核整页文案',
|
||||
});
|
||||
const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value) ? value : undefined;
|
||||
const safeNumber = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
||||
|
||||
const operationCategories = Object.freeze({
|
||||
'pi-state':'ui_ack', 'pi-production-open':'canvas_read', 'pi-canvas-read':'canvas_read',
|
||||
'pi-product-screen':'canvas_read', 'pi-detail-copy-fields':'canvas_read',
|
||||
'pi-template-image':'canvas_read', 'pi-detail-images':'canvas_read', 'pi-workflow-read':'canvas_read',
|
||||
'pi-preview':'canvas_read', 'pi-native-catalog':'canvas_read',
|
||||
'pi-image-request':'remote_image', 'pi-detail-copy-apply':'canvas_write', 'pi-edit':'canvas_write',
|
||||
'pi-write-request':'canvas_write', 'pi-workflow-execute':'canvas_write', 'pi-native-call':'canvas_write',
|
||||
canvas_read:'canvas_read', canvas_preview:'canvas_read', read_output_screen:'canvas_read', read_copy_fields:'canvas_read',
|
||||
prepare_image_request:'remote_image', dispatch_image_request:'remote_image',
|
||||
reconcile_image_slots:'remote_image', adopt_production_image:'canvas_write',
|
||||
write_copy_fields:'canvas_write', canvas_edit:'canvas_write', finish_production:'export',
|
||||
production_image_retired:'remote_image', whole_detail_review:'inference',
|
||||
});
|
||||
export const executionCategory = action => operationCategories[action] ?? 'ui_ack';
|
||||
|
||||
const inferencePhases = Object.freeze({
|
||||
provider_prepared:['prepare','prepared'], serialized_request:['serialize','prepared'],
|
||||
provider_started:['dispatch','running'], provider_finished:['receipt','completed'],
|
||||
provider_error:['receipt','failed'], response_audit:['inspect','completed'],
|
||||
usage:['usage','completed'], pi_retry:['retry','pending'],
|
||||
});
|
||||
|
||||
export function executionEvent(event, scope, health, at = Date.now()) {
|
||||
const inference = inferencePhases[event.type];
|
||||
const category = event.category ?? (inference ? 'inference' : executionCategory(event.toolName ?? event.type));
|
||||
const phase = event.phase ?? inference?.[0] ?? event.type;
|
||||
const status = event.status ?? (event.consumption === 'discarded_after_cancel' ? 'cancelled' :
|
||||
event.type === 'provider_finished' && event.phase ? event.phase :
|
||||
inference?.[1] ?? (event.isError ? 'failed' : 'completed'));
|
||||
// Keep legacy phase values on provider receipts and an independent lifecycle stage.
|
||||
return {at,...event,category,phase,status,stage:event.stage ?? inference?.[0] ?? phase,
|
||||
projectId:event.projectId ?? scope.projectId ?? null,runId:event.runId ?? scope.runId ?? null,
|
||||
operationId:event.operationId ?? event.id ?? event.toolCallId ?? scope.runId ?? null,
|
||||
attempt:event.attempt ?? 1,outputId:event.outputId ?? scope.outputId ?? null,
|
||||
variantId:event.variantId ?? scope.variantId ?? null,revision:event.revision ?? scope.revision ?? null,
|
||||
documentKey:event.documentKey ?? scope.documentKey ?? null,
|
||||
agentHeartbeat:health.agentHeartbeat ?? null,uiHeartbeat:health.uiHeartbeat ?? null,
|
||||
jobProgress:event.jobProgress ?? null,recentDurableCommit:health.recentDurableCommit ?? null};
|
||||
}
|
||||
|
||||
// Read this once from pi-begin, whose requestScope is frozen by the native host.
|
||||
// IDs outside the expected format are omitted instead of copied as free text.
|
||||
export function activityScope(identity, canvas, begun) {
|
||||
const request = begun?.context?.requestScope;
|
||||
const subject = request?.subject;
|
||||
// Production canvas state omits the full context. Its active begin receipt
|
||||
// still confirms the document carried by this native connection.
|
||||
const documentId = begun?.context?.id ?? (
|
||||
begun?.conversationActive === true && begun.run === canvas?.run ? canvas?.documentId : undefined
|
||||
);
|
||||
const values = {
|
||||
accountScope: safeId(identity?.scope), project: safeId(identity?.project),
|
||||
documentId: safeNumber(documentId), run: safeId(canvas?.run),
|
||||
outputId: safeId(request?.outputId), variantId: safeId(request?.variantId),
|
||||
slotId: safeId(subject?.slotId), candidateId: safeId(subject?.candidateId),
|
||||
revision: safeNumber(begun?.revision),
|
||||
};
|
||||
return Object.freeze(Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)));
|
||||
}
|
||||
|
||||
function details(event) {
|
||||
const toolName = Object.hasOwn(labels, event.toolName) ? event.toolName : 'other';
|
||||
const stopped = event.isError && ['write_revoked','revision_conflict','cancelled']
|
||||
.includes(event.result?.details?.failure?.category);
|
||||
const pending = typeof event.result?.details?.pendingOriginal === 'string';
|
||||
const status = event.type === 'tool_execution_start' ? 'started' : stopped ? 'stopped' :
|
||||
event.isError ? 'failed' : pending ? 'pending' : 'completed';
|
||||
const label = labels[toolName] || '工具';
|
||||
const summary = `${{ started: '开始', stopped: '已停止', failed: '失败', pending: '待核查', completed: '完成' }[status]}:${label}`;
|
||||
return { toolName, status, summary };
|
||||
}
|
||||
|
||||
export function activitySummary(event) { return details(event).summary; }
|
||||
|
||||
export function toolActivity(event, scope, timestampMs = Date.now()) {
|
||||
if (!['tool_execution_start', 'tool_execution_end'].includes(event?.type)) return null;
|
||||
const toolCallId = safeId(event.toolCallId);
|
||||
if (!toolCallId || safeNumber(timestampMs) === undefined) return null;
|
||||
const durationMs = safeNumber(event.durationMs);
|
||||
const activity = details(event);
|
||||
return { version: 1, type: 'tool', toolCallId, ...activity, phase:activity.status,
|
||||
category:executionCategory(activity.toolName),timestampMs, ...(durationMs === undefined ? {} : { durationMs }), scope };
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import {setTimeout as delay} from 'node:timers/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { confirmProductionResponse, confirmedProductionFailure, piRetryPolicy, productRequestScope, productionUsesAutomaticTools, ProductionOutputLimit, ProductionRequestFailed, ProductionRequestPending } from './production-recovery.mjs';
|
||||
import { enterpriseTools } from './enterprise-knowledge.mjs';
|
||||
import { executeWorkflow } from './workflow-execute.mjs';
|
||||
@ -10,6 +11,7 @@ import { Type } from '@sinclair/typebox';
|
||||
import { productionLedger } from './production-repository.mjs';
|
||||
import { CanvasOperations } from './canvas-operations.mjs';
|
||||
import { BridgeError, stoppedCanvas } from './bridge-error.mjs';
|
||||
import { protectSession, redactText } from './credentials.mjs';
|
||||
import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal,
|
||||
mayContinueProductionGoal, piGoalState } from './production-goal.mjs';
|
||||
import { Agent, runToolCall } from '@earendil-works/pi-agent-core';
|
||||
@ -87,6 +89,7 @@ function toolsFor(host) {
|
||||
if (name === 'memory_set' && !host.productionGoal && host.canvas?.workflowRead) await host.readWorkflow({section:'overview'});
|
||||
if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工具不会继续执行');
|
||||
try {
|
||||
host.productionSignal?.throwIfAborted();
|
||||
const value = await execute(args, signal, ctx);
|
||||
return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value);
|
||||
} catch(error) {
|
||||
@ -422,7 +425,7 @@ export class DetailPiAgent {
|
||||
return;
|
||||
}
|
||||
round = (host.goalBroker ?? broker).round({inference:true});
|
||||
await store.appendEvent({ type: 'provider_prepared', id: round.id, model: model.id, bindingHash: store.hash,
|
||||
await store.appendEvent({ type: 'provider_prepared', id: round.id, requestId:round.id, model: model.id, bindingHash: store.hash,
|
||||
purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation' });
|
||||
host.inflight = round.id;
|
||||
if (!host.compacting) requiredTool = host.requiredTool;
|
||||
@ -430,6 +433,8 @@ export class DetailPiAgent {
|
||||
let sentAt, headersAt, firstThinkingAt, firstTextAt, firstToolAt;
|
||||
const stream = apiImpl.streamSimple(model, wireContext, { ...options, apiKey: 'native-broker-only', fetch: async (...args) => {
|
||||
sentAt = Date.now();
|
||||
await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id});
|
||||
host.productionSignal?.throwIfAborted();
|
||||
const response = await round.fetch(...args);
|
||||
headersAt = Date.now();
|
||||
wireCapture = response.clone().text().then(text => ({ text }), error => ({ error }));
|
||||
@ -458,6 +463,7 @@ export class DetailPiAgent {
|
||||
if (event.type === 'text_delta' && firstTextAt === undefined) firstTextAt = Date.now();
|
||||
// Finalize the durable journal BEFORE Pi can execute any returned tool.
|
||||
if (event.type === 'done' || event.type === 'error') finalEvent = event;
|
||||
else if (options.signal?.aborted || host.productionSignal?.aborted) continue;
|
||||
else if (!encoded) output.push(event);
|
||||
else if (event.type === 'start') {
|
||||
partial = { ...event.partial, content: [] };
|
||||
@ -478,7 +484,8 @@ export class DetailPiAgent {
|
||||
? result.stopReason === 'stop' && !result.content.some(content => content.type === 'toolCall')
|
||||
: ['stop', 'toolUse', 'length'].includes(result.stopReason));
|
||||
const settled = await round.finish(valid, result.stopReason);
|
||||
await store.appendEvent({ type: 'provider_finished', id: round.id, ...settled,
|
||||
await store.appendEvent({ type: 'provider_finished', id: round.id, requestId:round.id, ...settled,
|
||||
...(options.signal?.aborted || host.productionSignal?.aborted ? {consumption:'discarded_after_cancel'} : null),
|
||||
...(sentAt === undefined ? {} : {
|
||||
...(headersAt === undefined ? {} : {responseHeadersMs:headersAt-sentAt}),
|
||||
...(firstThinkingAt === undefined ? {} : {firstThinkingMs:firstThinkingAt-sentAt}),
|
||||
@ -486,9 +493,12 @@ export class DetailPiAgent {
|
||||
...(firstToolAt === undefined ? {} : {firstToolMs:firstToolAt-sentAt}),
|
||||
}) });
|
||||
host.inflight = ['complete', 'failed'].includes(settled.phase) ? null : round.id;
|
||||
if (broker?.authority?.error) throw broker.authority.error;
|
||||
const failure = confirmedProductionFailure(settled, round.id);
|
||||
if (failure) throw failure;
|
||||
if (result.stopReason==='length' && ['complete','rejected'].includes(settled.phase)) {
|
||||
host.productionSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
const message={...result,content:result.content.filter(block=>block.type!=='toolCall')};
|
||||
output.push({type:'done',reason:'length',message});
|
||||
output.end(message);
|
||||
@ -500,10 +510,14 @@ export class DetailPiAgent {
|
||||
const usage = responseUsage(wire.text);
|
||||
await store.appendEvent({ type: 'usage', id: round.id, model: model.id,
|
||||
purpose: host.compacting ? 'compaction' : host.productionGoal ? 'product-goal' : 'conversation', ...usage });
|
||||
host.productionSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
await onEvent({ type: 'usage', id: round.id, model: model.id, ...usage });
|
||||
if (!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);
|
||||
await store.appendEvent({ type: 'response_audit', id: round.id, ...audit, calls: audit.calls.map(c => ({ name: c.name })) });
|
||||
host.productionSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
if (!encoded && requiredTool && !audit.calls.some(c => c.name === requiredTool)) throw Error('模型未返回要求的标准函数调用;本轮操作未执行,不会自动改用其他协议');
|
||||
if (!host.compacting && requiredTool) host.requiredTool = null;
|
||||
if (encoded) {
|
||||
@ -514,8 +528,10 @@ export class DetailPiAgent {
|
||||
output.push({ type: 'done', reason: message.stopReason, message }); output.end(message);
|
||||
} else { output.push(finalEvent); output.end(result); }
|
||||
} catch (error) {
|
||||
const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 'error', errorMessage: error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+error.message : String(error.message), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
|
||||
await store.appendEvent({ type: 'provider_error', id: round?.id, reason: message.errorMessage });
|
||||
const reason = redactText(String(error.message));
|
||||
const message = { role: 'assistant', api, provider: 'jiansun-native-98k', model: info.model.id, content: [], stopReason: 'error', errorMessage: error instanceof ProductionRequestFailed && error.httpStatus ? String(error.httpStatus)+' '+reason : reason, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { ...cost, total: 0 } }, timestamp: Date.now() };
|
||||
await store.appendEvent({ type: 'provider_error', id: round?.id, reason: message.errorMessage,
|
||||
...(options.signal?.aborted || host.productionSignal?.aborted ? {status:'cancelled',consumption:'discarded_after_cancel'} : null) });
|
||||
output.push({ type: 'error', reason: 'error', error: message }); output.end(message);
|
||||
}
|
||||
})();
|
||||
@ -523,7 +539,8 @@ export class DetailPiAgent {
|
||||
},
|
||||
});
|
||||
const saved = await store.get('session.json', null);
|
||||
host.manager = saved ? SessionManager.open(path.join(store.dir,'sessions',path.basename(saved.file)), store.dir, store.dir) : SessionManager.create(store.dir, path.join(store.dir, 'sessions'));
|
||||
host.manager = protectSession(saved ? SessionManager.open(path.join(store.dir,'sessions',path.basename(saved.file)), store.dir, store.dir)
|
||||
: SessionManager.create(store.dir, path.join(store.dir, 'sessions')));
|
||||
if (typeof canvas?.uiRequest === 'function') host.nativeUI = new NativeExtensionUI(canvas, { abort: () => { void host.session?.abort(); } });
|
||||
const files = await projectTools(host);
|
||||
const customTools = [...toolsFor(host),...files.tools];
|
||||
@ -596,6 +613,7 @@ export class DetailPiAgent {
|
||||
}
|
||||
});
|
||||
agent.beforeToolCall=async ({toolCall})=>{
|
||||
if(productionSignal?.aborted)return {block:true,terminate:true,reason:'原制作回合已停止'};
|
||||
if(host.productionRequests)return;
|
||||
const key=JSON.stringify([toolCall.name,toolCall.arguments]);
|
||||
const count=(used.get(key)??0)+1;
|
||||
@ -607,8 +625,11 @@ export class DetailPiAgent {
|
||||
const output=createAssistantMessageEventStream();
|
||||
(async()=>{
|
||||
let round;
|
||||
const operationId=randomUUID();
|
||||
let attempt=0;
|
||||
try {
|
||||
const result = await retryAssistantCall(async () => {
|
||||
attempt++;
|
||||
round = undefined;
|
||||
let requestBytes, firstOutputMs, promptCacheKeyPresent;
|
||||
try {
|
||||
@ -620,7 +641,8 @@ export class DetailPiAgent {
|
||||
const imageCount=context.messages.reduce((count,message)=>count+
|
||||
(Array.isArray(message.content)?message.content.filter(item=>item.type==='image').length:0),0);
|
||||
const started=Date.now();
|
||||
await store.appendEvent({type:'provider_prepared',id:round.id,model:selected.id,purpose:'whole-detail-worker',slotId,requestScope,imageCount});
|
||||
await store.appendEvent({type:'provider_prepared',id:round.id,requestId:round.id,operationId,attempt,
|
||||
model:selected.id,purpose:'whole-detail-worker',slotId,requestScope,imageCount});
|
||||
let wire;
|
||||
const stream=apiImpl.streamSimple(selected,context,{...options,toolChoice,apiKey:'native-broker-only',
|
||||
onPayload:payload=>{
|
||||
@ -630,6 +652,8 @@ export class DetailPiAgent {
|
||||
fetch:async (...args)=>{
|
||||
const body=args[1]?.body;
|
||||
if(typeof body==='string')requestBytes=Buffer.byteLength(body);
|
||||
await store.appendEvent({type:'provider_started',id:round.id,requestId:round.id,operationId,attempt,slotId});
|
||||
productionSignal?.throwIfAborted();
|
||||
const response=await round.fetch(...args);
|
||||
wire=response.clone().text().catch(()=>null);
|
||||
return response;
|
||||
@ -639,15 +663,18 @@ export class DetailPiAgent {
|
||||
if(event.type==='done'||event.type==='error')finalEvent=event;
|
||||
else{
|
||||
if(event.type==='text_delta'||event.type==='toolcall_delta')firstOutputMs??=Date.now()-started;
|
||||
output.push(event);
|
||||
if (!options.signal?.aborted && !productionSignal?.aborted) output.push(event);
|
||||
}
|
||||
}
|
||||
const message=await stream.result();
|
||||
const valid=finalEvent?.type==='done' && ['stop','toolUse'].includes(message.stopReason);
|
||||
const receipt=await round.finish(valid,message.stopReason);
|
||||
if (broker?.authority?.error) throw broker.authority.error;
|
||||
const raw=valid&&receipt.phase==='complete'?await wire:null;
|
||||
const usage=raw?responseUsage(raw):null;
|
||||
await store.appendEvent({type:'provider_finished',id:round.id,slotId,...receipt,requestBytes,firstOutputMs,promptCacheKeyPresent,
|
||||
await store.appendEvent({type:'provider_finished',id:round.id,requestId:round.id,operationId,attempt,
|
||||
slotId,...receipt,requestBytes,firstOutputMs,promptCacheKeyPresent,
|
||||
...(options.signal?.aborted || productionSignal?.aborted ? {consumption:'discarded_after_cancel'} : null),
|
||||
...(usage?{inputTokens:usage.inputTokens,outputTokens:usage.outputTokens,cachedTokens:usage.cachedTokens}:null)});
|
||||
if(receipt.phase==='rejected'&&message.stopReason==='length')throw new ProductionOutputLimit();
|
||||
const failure=confirmedProductionFailure(receipt,round.id);
|
||||
@ -657,8 +684,10 @@ export class DetailPiAgent {
|
||||
if(!raw)throw Error('原始模型响应尚未读完,工具未执行');
|
||||
const audit=auditResponse(raw,info.model.protocol);
|
||||
if(message.content.filter(item=>item.type==='toolCall').length!==audit.calls.length)throw Error('原模型工具调用未完整返回');
|
||||
await store.appendEvent({type:'usage',id:round.id,model:selected.id,purpose:'whole-detail-worker',slotId,...usage});
|
||||
await store.appendEvent({type:'usage',id:round.id,operationId,attempt,model:selected.id,purpose:'whole-detail-worker',slotId,...usage});
|
||||
await onEvent({type:'usage',id:round.id,model:selected.id,...usage});
|
||||
productionSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
return message;
|
||||
} catch(error) {
|
||||
if (error instanceof ProductionOutputLimit || error instanceof InvalidToolReply || options.signal?.aborted) throw error;
|
||||
@ -667,13 +696,19 @@ export class DetailPiAgent {
|
||||
timestamp:Date.now(),usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{...cost,total:0}}};
|
||||
}
|
||||
}, piRetryPolicy, options.signal, {onRetryScheduled:async(attempt,maxAttempts,delayMs)=>{
|
||||
await store.appendEvent({type:'pi_retry',id:round?.id,requestScope,slotId,attempt,maxAttempts,delayMs});
|
||||
await store.appendEvent({type:'pi_retry',id:round?.id,operationId,requestScope,slotId,attempt,maxAttempts,delayMs});
|
||||
}});
|
||||
productionSignal?.throwIfAborted();
|
||||
options.signal?.throwIfAborted();
|
||||
if (result.stopReason === 'error' || result.stopReason === 'aborted') {
|
||||
output.push({type:'error',reason:result.stopReason,error:result});
|
||||
} else output.push({type:'done',reason:result.stopReason,message:result});
|
||||
output.end(result);
|
||||
} catch (error) {
|
||||
if (round && (productionSignal?.aborted || options.signal?.aborted)) {
|
||||
await store.appendEvent({type:'provider_error',id:round.id,operationId,attempt,slotId,
|
||||
status:'cancelled',consumption:'discarded_after_cancel'});
|
||||
}
|
||||
if(error instanceof ProductionRequestPending||error instanceof ProductionRequestFailed||error instanceof ProductionOutputLimit||
|
||||
error instanceof InvalidToolReply)pendingError=error;
|
||||
const failure={role:'assistant',api,provider:selected.provider,model:selected.id,content:[],stopReason:'error',
|
||||
@ -786,7 +821,8 @@ export class DetailPiAgent {
|
||||
if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
|
||||
const activity = toolActivity(event, host.activityScope || activityScope(store.identity));
|
||||
if (canvas) void host.notifyCanvas('activity', activitySummary(event), activity).catch(()=>{});
|
||||
await store.appendEvent({ type: event.type, toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError ?? false });
|
||||
await store.appendEvent({ type: event.type, toolName: event.toolName, toolCallId: event.toolCallId, isError: event.isError ?? false,
|
||||
...(activity ? {status:activity.status,phase:activity.phase,category:activity.category,durationMs:activity.durationMs} : null) });
|
||||
void Promise.resolve().then(() => onEvent({ type: event.type, toolName: event.toolName, isError: event.isError ?? false, ...(activity ? { activity } : {}) })).catch(()=>{});
|
||||
}
|
||||
});
|
||||
@ -903,6 +939,7 @@ export class DetailPiAgent {
|
||||
if (this.needsReopen) throw Error('原响应已恢复,请重新打开此会话;未发起新请求');
|
||||
if ((await this.store.get('recovered-tools.json', [])).some(t => t.phase === 'review')) throw Error('原请求的工具建议已取回,需先核对画布;不会重跑工具或模型');
|
||||
if (typeof text !== 'string' || !text.trim()) throw Error('请输入本轮要求');
|
||||
text = redactText(text);
|
||||
const latest = this.firstTurnBrokerInfo ?? (this.broker ? await this.broker.info() : this.info);
|
||||
this.firstTurnBrokerInfo = null;
|
||||
if (latest.accountScope !== this.store.identity.scope) throw Error('账户与项目不一致;原草稿已保留');
|
||||
@ -976,6 +1013,7 @@ export class DetailPiAgent {
|
||||
if (this.manager.getSessionFile()) await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
|
||||
await running;
|
||||
await closeProductionTurn(this);
|
||||
this.productionSignal?.throwIfAborted();
|
||||
await atomic(path.join(this.store.dir, 'session.json'), { file: this.manager.getSessionFile() });
|
||||
const last = this.session.messages.filter(m => m.role === 'assistant').at(-1);
|
||||
const useStageReceipt = last?.stopReason === 'error' && this.goalStageResult && !this.canvasOperations.writesBlocked;
|
||||
@ -1130,6 +1168,13 @@ export class DetailPiAgent {
|
||||
}
|
||||
record = { id, ...await this.broker.read(id) };
|
||||
}
|
||||
if (purpose.kind === 'cancelled') {
|
||||
const receipt=record.phase==='received'
|
||||
? await confirmProductionResponse(this.broker,record,this.session.model,this.session.agent.state.tools,this.protocolMode)
|
||||
: record;
|
||||
const phase=['failed','rejected'].includes(receipt.phase)?'failed':receipt.phase==='complete'?'complete':'unknown';
|
||||
return {phase,requestId:record.requestId,reposted:false,toolsExecuted:0,canvasWrites:0,consumption:'discarded_after_cancel'};
|
||||
}
|
||||
if (['whole-detail-worker','product-goal','whole-detail-review'].includes(purpose.kind)) {
|
||||
const {requestId}=record;
|
||||
if (['failed','rejected'].includes(record.phase)) return {phase:'failed',requestId,reposted:false};
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
import { redactText } from './credentials.mjs';
|
||||
|
||||
export class BridgeError extends Error {
|
||||
constructor(message, category = 'failed', {retryable = false, dispatched = false} = {}) {
|
||||
super(message);
|
||||
super(redactText(String(message ?? '本机操作未完成')));
|
||||
this.category=category;
|
||||
this.retryable=retryable;
|
||||
this.dispatched=dispatched;
|
||||
@ -19,4 +21,11 @@ export class BridgeError extends Error {
|
||||
}
|
||||
|
||||
export const stoppedCanvas = error =>
|
||||
['scope_changed','write_revoked','revision_conflict','result_unknown','cancelled','transport_interrupted'].includes(error?.category);
|
||||
['scope_changed','auth_revoked','write_revoked','revision_conflict','result_unknown','cancelled','transport_interrupted'].includes(error?.category);
|
||||
|
||||
export const authorityLost = error => ['scope_changed', 'auth_revoked'].includes(error?.category);
|
||||
|
||||
export function authorityFailure(category, options) {
|
||||
return new BridgeError(category === 'scope_changed' ? '账户已改变,原项目和原请求已保留;请切回原账户'
|
||||
: '授权已失效,制作已暂停;请重新登录', category, options);
|
||||
}
|
||||
|
||||
23
apps/detail-agent-pi/src/credentials.mjs
Normal file
23
apps/detail-agent-pi/src/credentials.mjs
Normal file
@ -0,0 +1,23 @@
|
||||
const credentialText = /\b(?:authorization|(?:set[-_ ]?)?cookie|x[-_ ]?api[-_ ]?key|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|secret[-_ ]?key)["']?\s*[:=]\s*[^\r\n]+|\bbearer[ \t]+[a-z0-9._~+/=-]{4,}|\b(?:sk-(?:proj-)?|dcs_|dca_)[a-z0-9_-]{16,}/gi;
|
||||
const credentialKeys = new Set(['authorization', 'cookie', 'setcookie', 'apikey', 'xapikey',
|
||||
'accesstoken', 'refreshtoken', 'password', 'secretkey', 'credentials', 'privatekey', 'token', 'composerdrafttoken']);
|
||||
|
||||
export const redactText = text => text.replace(credentialText, '[已脱敏]');
|
||||
|
||||
export function redact(value) {
|
||||
if (typeof value === 'string') return redactText(value);
|
||||
if (Array.isArray(value)) return value.map(redact);
|
||||
if (!value || typeof value !== 'object') return value;
|
||||
return Object.fromEntries(Object.entries(value)
|
||||
.filter(([key, item]) => !credentialKeys.has(key.toLowerCase().replace(/[-_ ]/g, '')) && redactText(key) === key
|
||||
&& !(key.toLowerCase() === 'key' && typeof item === 'string' && item.startsWith('sk-')))
|
||||
.map(([key, item]) => [key, redact(item)]));
|
||||
}
|
||||
|
||||
export function protectSession(manager) {
|
||||
for (const name of ['appendMessage', 'appendCompaction', 'branchWithSummary', 'appendCustomEntry', 'appendCustomMessageEntry']) {
|
||||
const append = manager[name].bind(manager);
|
||||
manager[name] = (...args) => append(...args.map(redact));
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
@ -1,112 +1,160 @@
|
||||
import { BridgeError } from './bridge-error.mjs';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { Native98kBroker } from './native-bridge.mjs';
|
||||
|
||||
const uuid = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
|
||||
export function startDaemon({runSession, readKnowledge, input=process.stdin, output=process.stdout, parentPid=process.ppid,
|
||||
parentAlive=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code==='EPERM';}},
|
||||
intervalMs=100, brokerFactory=config=>new Native98kBroker(config), exit=code=>process.exit(code)}={}) {
|
||||
const lines=createInterface({input,crlfDelay:Infinity});
|
||||
let active=null, broker=null, identity=null, closed=false, serial=0;
|
||||
const waiting=new Map(), seen=new Set(), knowledge=new Map();
|
||||
// Retain unresolved operations across the distinct SDK Host instances owned
|
||||
// by this daemon. Never evict an unresolved identity to make room.
|
||||
const recovery = new Map();
|
||||
const send=value=>{if(!closed)output.write(JSON.stringify(value)+'\n');};
|
||||
const stop=async()=>{
|
||||
if(closed)return; closed=true;clearInterval(watch);lines.close();
|
||||
for(const controller of knowledge.values())controller.abort();knowledge.clear();
|
||||
for(const item of waiting.values()){clearTimeout(item.timer);item.reject(new BridgeError('客户端连接中断,原操作需核查;不会重发','transport_interrupted',{retryable:true,dispatched:true}));}waiting.clear();
|
||||
// Kill only our child. Never wait for a synchronous HTTP call to return.
|
||||
const killTimer=setTimeout(()=>exit(1),500);killTimer.unref?.();
|
||||
try { if(broker)await broker.close({force:true}); } finally {clearTimeout(killTimer);exit(0);}
|
||||
};
|
||||
// The native owner times heartbeat acknowledgements. Cold SDK imports can
|
||||
// delay stdin delivery, so the child only monitors the owner and the pipe.
|
||||
const watch=setInterval(()=>{
|
||||
if(!parentAlive(parentPid))void stop();
|
||||
},intervalMs);
|
||||
const failure=(runId,error,unknown=false)=>send({type:'complete',runId,value:{error,unknown,reposted:false}});
|
||||
lines.on('line',line=>{
|
||||
if(closed)return;
|
||||
let value;try{if(line.length>2*1024*1024)throw Error();value=JSON.parse(line);}catch{send({type:'fatal',error:'本地消息无效;不会重发'});void stop();return;}
|
||||
if(value?.type==='heartbeat') {send({type:'heartbeat_ack',id:value.id,brokerPid:broker?.child?.pid??null});return;}
|
||||
if(value?.type==='production_pause') {
|
||||
const config=active?.config;
|
||||
if(config?.productProduction===true && value.documentId===config.documentId
|
||||
&& value.project===config.project && value.scope===config.scope) {
|
||||
active.abort(Error('本轮制作已停止,已保留原请求'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(value?.type==='knowledge_cancel' && uuid.test(value.id||'')) {
|
||||
knowledge.get(value.id)?.abort(Error('已取消模板读取,已下载内容保留'));
|
||||
return;
|
||||
}
|
||||
if(value?.type==='knowledge' && uuid.test(value.id||'') && readKnowledge) {
|
||||
if(knowledge.has(value.id))return;
|
||||
const controller=new AbortController();knowledge.set(value.id,controller);
|
||||
void Promise.resolve().then(()=>readKnowledge(value.input,{signal:controller.signal,onProgress:progress=>{
|
||||
if(!controller.signal.aborted)send({type:'knowledge_progress',id:value.id,value:progress});
|
||||
}})).then(
|
||||
result=>send({type:'knowledge_result',id:value.id,value:result}),
|
||||
error=>send({type:'knowledge_result',id:value.id,error:error.message || '企业知识库读取失败'}))
|
||||
.finally(()=>knowledge.delete(value.id));
|
||||
return;
|
||||
}
|
||||
if(value?.type==='canvas_result') {
|
||||
const task=waiting.get(value.id);
|
||||
if(!task||value.runId!==task.runId||active?.runId!==task.runId)return;
|
||||
waiting.delete(value.id);clearTimeout(task.timer);value.error?task.reject(BridgeError.from(value.error)):task.resolve(value.value);return;
|
||||
}
|
||||
if(value?.type!=='run'||!uuid.test(value.runId||'')||!value.config||typeof value.config!=='object'||Array.isArray(value.config)) {send({type:'fatal',error:'本地消息无效;不会重发'});return;}
|
||||
if(active){if(active.runId!==value.runId)failure(value.runId,'已有运行中的任务,未派发');return;}
|
||||
if(seen.has(value.runId)||seen.size>=10000){failure(value.runId,'会话编号已使用或达到上限,未派发');return;}
|
||||
const runId=value.runId, config=structuredClone(value.config);
|
||||
seen.add(runId);
|
||||
const deadline = config.productProduction === true && Number.isSafeInteger(config.productionDeadline)
|
||||
? config.productionDeadline * 1000 : null;
|
||||
const controller = config.productProduction === true ? new AbortController() : null;
|
||||
const abort = error => {
|
||||
controller.abort(error);
|
||||
for (const [id, task] of waiting) {
|
||||
if (task.runId !== runId) continue;
|
||||
waiting.delete(id);
|
||||
clearTimeout(task.timer);
|
||||
task.reject(new BridgeError(error.message,'cancelled',{dispatched:true}));
|
||||
}
|
||||
};
|
||||
active={runId,config,abort};
|
||||
const expire = () => abort(Error('整套制作已达到时限,已保留当前编辑和原请求'));
|
||||
const timer = deadline === null ? null : setTimeout(expire, Math.max(0, deadline - Date.now()));
|
||||
const call=(action,input)=>new Promise((resolve,reject)=>{
|
||||
if(closed||active?.runId!==runId){reject(new BridgeError('客户端连接已关闭,原操作需核查','transport_interrupted',{retryable:true}));return;}
|
||||
if(controller?.signal.aborted){reject(new BridgeError(controller.signal.reason.message,'cancelled'));return;}
|
||||
if (action === 'pi-delta' || action === 'pi-activity') {
|
||||
send({type:'presentation',runId,action,input});
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const id=++serial;
|
||||
waiting.set(id,{resolve,reject,runId});send({type:'canvas',runId,id,action,input});
|
||||
});
|
||||
void (async()=>{
|
||||
try {
|
||||
if (config.mode !== 'record-production-export') {
|
||||
const next=JSON.stringify([config.binary,config.profile,config.scope,config.project]);
|
||||
if(identity!==null&&identity!==next){await broker.close({force:true});broker=null;identity=null;}
|
||||
if(closed)return;
|
||||
if(!broker){broker=brokerFactory({binary:config.binary,profile:config.profile,project:config.project});identity=next;}
|
||||
}
|
||||
if (deadline !== null && deadline <= Date.now()) expire();
|
||||
const result=await runSession(config,call,broker,recovery,controller?.signal);
|
||||
if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;send({type:'complete',runId,value:result});}
|
||||
} catch {if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;failure(runId,controller?.signal.reason?.message??'本地模型桥失败;请核查原请求,不会重发',true);}}
|
||||
finally { if (timer !== null) clearTimeout(timer); }
|
||||
})();
|
||||
});
|
||||
lines.on('close',()=>void stop());
|
||||
input.on('error',()=>void stop());output.on('error',()=>void stop());
|
||||
send({type:'ready'});
|
||||
return {stop};
|
||||
}
|
||||
import { BridgeError, authorityFailure, authorityLost } from './bridge-error.mjs';
|
||||
import { redact } from './credentials.mjs';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { Native98kBroker } from './native-bridge.mjs';
|
||||
|
||||
const uuid = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
|
||||
export function startDaemon({runSession, readKnowledge, input=process.stdin, output=process.stdout, parentPid=process.ppid,
|
||||
parentAlive=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code==='EPERM';}},
|
||||
intervalMs=100, brokerFactory=config=>new Native98kBroker(config), exit=code=>process.exit(code)}={}) {
|
||||
const lines=createInterface({input,crlfDelay:Infinity});
|
||||
let active=null, broker=null, identity=null, closed=false, exiting=false, serial=0;
|
||||
const waiting=new Map(), seen=new Set(), knowledge=new Map();
|
||||
// Retain unresolved operations across the distinct SDK Host instances owned
|
||||
// by this daemon. Never evict an unresolved identity to make room.
|
||||
const recovery = new Map();
|
||||
const send=value=>{if(!closed)output.write(JSON.stringify(redact(value))+'\n');};
|
||||
const stop=async()=>{
|
||||
if(closed)return; closed=true;clearInterval(watch);lines.close();
|
||||
active?.abort(Error('客户端连接中断,原操作需核查'));
|
||||
for(const controller of knowledge.values())controller.abort();knowledge.clear();
|
||||
for(const item of waiting.values()){clearTimeout(item.timer);item.reject(new BridgeError('客户端连接中断,原操作需核查;不会重发','transport_interrupted',{retryable:true,dispatched:true}));}waiting.clear();
|
||||
// Kill only our child. Never wait for a synchronous HTTP call to return.
|
||||
const killTimer=setTimeout(()=>exit(1),500);killTimer.unref?.();
|
||||
try { if(broker)await broker.close({force:true}); } finally {clearTimeout(killTimer);exit(0);}
|
||||
};
|
||||
// The native owner times heartbeat acknowledgements. Cold SDK imports can
|
||||
// delay stdin delivery, so the child only monitors the owner and the pipe.
|
||||
const watch=setInterval(()=>{
|
||||
if(!parentAlive(parentPid))void stop();
|
||||
},intervalMs);
|
||||
const failure=(runId,error,unknown=false)=>send({type:'complete',runId,value:{error,unknown,reposted:false}});
|
||||
const exitReady=()=>{if(exiting&&!active&&!knowledge.size)send({type:'exit_ready'});};
|
||||
lines.on('line',line=>{
|
||||
if(closed)return;
|
||||
let value;try{if(line.length>2*1024*1024)throw Error();value=JSON.parse(line);}catch{send({type:'fatal',error:'本地消息无效;不会重发'});void stop();return;}
|
||||
if(value?.type==='heartbeat') {send({type:'heartbeat_ack',id:value.id,brokerPid:broker?.child?.pid??null});return;}
|
||||
if(value?.type==='prepare_exit') {
|
||||
if(exiting)return;
|
||||
exiting=true;
|
||||
const reason=Error('客户端正在退出,已保留原请求');
|
||||
active?.abort(reason);
|
||||
for(const controller of knowledge.values())controller.abort(reason);
|
||||
exitReady();
|
||||
return;
|
||||
}
|
||||
if (value?.type === 'auth_revoke') {
|
||||
if (active && active.config.scope === value.scope) {
|
||||
const error = authorityFailure(value.category);
|
||||
broker?.revoke?.(error, false);
|
||||
active.abort(error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(value?.type==='production_pause') {
|
||||
const config=active?.config;
|
||||
if(config?.productProduction===true && value.documentId===config.documentId
|
||||
&& value.project===config.project && value.scope===config.scope
|
||||
&& (value.writeEpoch??null)===(config.writeEpoch??null)) {
|
||||
active.abort(Error('本轮制作已停止,已保留原请求'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(value?.type==='knowledge_cancel' && uuid.test(value.id||'')) {
|
||||
knowledge.get(value.id)?.abort(Error('已取消模板读取,已下载内容保留'));
|
||||
return;
|
||||
}
|
||||
if(value?.type==='knowledge' && uuid.test(value.id||'') && readKnowledge) {
|
||||
if(exiting){send({type:'knowledge_result',id:value.id,error:'客户端正在退出,未派发新任务'});return;}
|
||||
if(knowledge.has(value.id))return;
|
||||
const controller=new AbortController();knowledge.set(value.id,controller);
|
||||
void Promise.resolve().then(()=>readKnowledge(value.input,{signal:controller.signal,onProgress:progress=>{
|
||||
if(!controller.signal.aborted)send({type:'knowledge_progress',id:value.id,value:progress});
|
||||
}})).then(
|
||||
result=>send({type:'knowledge_result',id:value.id,value:result}),
|
||||
error=>send({type:'knowledge_result',id:value.id,error:error.message || '企业知识库读取失败'}))
|
||||
.finally(()=>{knowledge.delete(value.id);exitReady();});
|
||||
return;
|
||||
}
|
||||
if(value?.type==='canvas_result') {
|
||||
const task=waiting.get(value.id);
|
||||
if(!task||value.runId!==task.runId||active?.runId!==task.runId)return;
|
||||
waiting.delete(value.id);clearTimeout(task.timer);
|
||||
if (value.error) {
|
||||
const error = BridgeError.from(value.error);
|
||||
if (authorityLost(error)) {
|
||||
broker?.revoke?.(error, false);
|
||||
active.abort(error);
|
||||
}
|
||||
task.reject(error);
|
||||
} else task.resolve(value.value);
|
||||
return;
|
||||
}
|
||||
if(value?.type==='canvas_accepted') {
|
||||
const task=waiting.get(value.id);
|
||||
if(task && value.runId===task.runId) task.accepted?.();
|
||||
return;
|
||||
}
|
||||
if(value?.type!=='run'||!uuid.test(value.runId||'')||!value.config||typeof value.config!=='object'||Array.isArray(value.config)) {send({type:'fatal',error:'本地消息无效;不会重发'});return;}
|
||||
if(exiting){failure(value.runId,'客户端正在退出,未派发新任务');return;}
|
||||
if(active){if(active.runId!==value.runId)failure(value.runId,'已有运行中的任务,未派发');return;}
|
||||
if(seen.has(value.runId)||seen.size>=10000){failure(value.runId,'会话编号已使用或达到上限,未派发');return;}
|
||||
const runId=value.runId, config=structuredClone(value.config);
|
||||
seen.add(runId);
|
||||
const deadline = config.productProduction === true && Number.isSafeInteger(config.productionDeadline)
|
||||
? config.productionDeadline * 1000 : null;
|
||||
const controller = new AbortController();
|
||||
const abort = error => {
|
||||
controller.abort(error);
|
||||
for (const [id, task] of waiting) {
|
||||
if (task.runId !== runId || task.retainOriginal) continue;
|
||||
waiting.delete(id);
|
||||
clearTimeout(task.timer);
|
||||
task.reject(new BridgeError(error.message,error.category ?? 'cancelled',{dispatched:true}));
|
||||
}
|
||||
};
|
||||
active={runId,config,abort};
|
||||
config.runId=runId;
|
||||
const expire = () => abort(Error('整套制作已达到时限,已保留当前编辑和原请求'));
|
||||
const timer = deadline === null ? null : setTimeout(expire, Math.max(0, deadline - Date.now()));
|
||||
const call=(action,input,accepted)=>new Promise((resolve,reject)=>{
|
||||
if(closed||active?.runId!==runId){reject(new BridgeError('客户端连接已关闭,原操作需核查','transport_interrupted',{retryable:true}));return;}
|
||||
if(controller.signal.aborted){reject(new BridgeError(controller.signal.reason.message,controller.signal.reason.category ?? 'cancelled'));return;}
|
||||
if (action === 'pi-delta' || action === 'pi-activity') {
|
||||
send({type:'presentation',runId,action,input});
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
const id=++serial;
|
||||
const retainOriginal=action==='pi-image-request' && input.action==='dispatch';
|
||||
waiting.set(id,{resolve,reject,runId,retainOriginal,accepted});send({type:'canvas',runId,id,action,input});
|
||||
});
|
||||
void (async()=>{
|
||||
try {
|
||||
if (config.mode !== 'record-production-export') {
|
||||
const next=JSON.stringify([config.binary,config.profile,config.scope,config.project]);
|
||||
if(identity!==null&&identity!==next){await broker.close({force:true});broker=null;identity=null;}
|
||||
if(closed)return;
|
||||
if(!broker){broker=brokerFactory({binary:config.binary,profile:config.profile,project:config.project});identity=next;}
|
||||
}
|
||||
if (deadline !== null && deadline <= Date.now()) expire();
|
||||
controller.signal.throwIfAborted();
|
||||
const result=await runSession(config,call,broker,recovery,controller.signal,error=>{
|
||||
if (active?.runId===runId && !controller.signal.aborted) {
|
||||
send({type:'auth_failure',runId,category:error.category});
|
||||
abort(error);
|
||||
}
|
||||
});
|
||||
if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;send({type:'complete',runId,value:result});}
|
||||
} catch {if(!closed&&active?.runId===runId){for(const [id,task] of waiting)if(task.runId===runId){waiting.delete(id);clearTimeout(task.timer);task.reject(new BridgeError('原会话已结束,操作结果需核查','transport_interrupted',{retryable:true,dispatched:true}));}active=null;failure(runId,controller?.signal.reason?.message??'本地模型桥失败;请核查原请求,不会重发',true);}}
|
||||
finally {
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
exitReady();
|
||||
}
|
||||
})();
|
||||
});
|
||||
lines.on('close',()=>void stop());
|
||||
input.on('error',()=>void stop());output.on('error',()=>void stop());
|
||||
send({type:'ready'});
|
||||
return {stop};
|
||||
}
|
||||
|
||||
@ -1,12 +1,56 @@
|
||||
import { CanvasOperations } from './canvas-operations.mjs';
|
||||
import { BridgeError } from './bridge-error.mjs';
|
||||
import { BridgeError, authorityFailure, authorityLost } from './bridge-error.mjs';
|
||||
import { redact } from './credentials.mjs';
|
||||
import { createInterface } from 'node:readline';
|
||||
import path from 'node:path';
|
||||
import { assertPiNodeVersion } from './runtime-policy.mjs';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { executionCategory } from './activity-event.mjs';
|
||||
|
||||
assertPiNodeVersion(process.versions.node);
|
||||
|
||||
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));
|
||||
store.executionHealth.agentHeartbeat=Date.now();
|
||||
await record('canvas_enqueued','enqueue','pending',{category:'ui_ack'});
|
||||
let accepted;
|
||||
try {
|
||||
const value=await call(action,input,()=>{
|
||||
store.executionHealth.uiHeartbeat=Date.now();
|
||||
accepted=record('canvas_accepted','accept','completed',{category:'ui_ack'})
|
||||
.then(()=>record('canvas_started','execute','running',{category}));
|
||||
});
|
||||
await accepted;
|
||||
if (value?.conversationActive === true) store.executionHealth.uiHeartbeat=Date.now();
|
||||
const binding=value?.productionCanvas;
|
||||
if (binding?.documentKey) Object.assign(store.executionScope,{
|
||||
outputId:binding.outputId,variantId:binding.variantId,documentKey:binding.documentKey,
|
||||
});
|
||||
if (Number.isSafeInteger(value?.revision) &&
|
||||
(binding?.documentKey || value.revision >= (store.executionScope.revision ?? 0))) {
|
||||
store.executionScope.revision=value.revision;
|
||||
}
|
||||
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,
|
||||
...(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});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Explicit local QA only. Matching a pending real job consumes the switch;
|
||||
// model arguments can neither configure nor re-arm it.
|
||||
export function qaNativeTimeout(raw) {
|
||||
@ -28,7 +72,7 @@ async function cli() {
|
||||
const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
let initial, serial = 0, closed = false;
|
||||
const waiting = new Map();
|
||||
const send = value => { if (!closed) process.stdout.write(JSON.stringify(value) + '\n'); };
|
||||
const send = value => { if (!closed) process.stdout.write(JSON.stringify(redact(value)) + '\n'); };
|
||||
const call = (action, input) => new Promise((resolve, reject) => {
|
||||
const id = ++serial;
|
||||
waiting.set(id, { resolve, reject }); send({ type: 'canvas', id, action, input });
|
||||
@ -82,14 +126,14 @@ export function bindRecovery(host, recovery, identity) {
|
||||
}
|
||||
};
|
||||
}
|
||||
export async function runSession(config, call, sharedBroker, recovery, signal) {
|
||||
export async function runSession(config, call, sharedBroker, recovery, signal, onAuthorizationLost) {
|
||||
if (config.mode === 'record-production-export') {
|
||||
try {
|
||||
const {recordProductionExport} = await import('./production-goal.mjs');
|
||||
return await recordProductionExport(config.sessionDir, config.goalId);
|
||||
} catch(error) { return {error:error.message}; }
|
||||
} catch(error) { return {error:BridgeError.from(error).message}; }
|
||||
}
|
||||
let host, broker, store, output;
|
||||
let host, broker, store, output, atomic, heartbeat;
|
||||
let releaseRecovery;
|
||||
const productionGoal=config.mode==='prompt'&&config.wholeDetail===true&&config.productProduction===true
|
||||
? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs,
|
||||
@ -99,24 +143,21 @@ export async function runSession(config, call, sharedBroker, recovery, signal) {
|
||||
const startedAt = performance.now();
|
||||
const abort = () => { if (host) void host.session.abort().catch(()=>{}); };
|
||||
try {
|
||||
signal?.throwIfAborted();
|
||||
if (!authorityLost(signal?.reason)) signal?.throwIfAborted();
|
||||
signal?.addEventListener('abort',abort,{once:true});
|
||||
const [{DetailPiAgent},{Native98kBroker},{ProjectStore,atomic},{StdioCanvas},{resolveRules},{productionGoalPreflight}] =
|
||||
const [{DetailPiAgent},{Native98kBroker},storage,{StdioCanvas},{resolveRules},{productionGoalPreflight}] =
|
||||
await Promise.all([import('./agent.mjs'),import('./native-bridge.mjs'),import('./store.mjs'),
|
||||
import('./stdio-canvas.mjs'),import('./rules.mjs'),import('./production-goal.mjs')]);
|
||||
atomic = storage.atomic;
|
||||
if (productionGoal) {
|
||||
const blocked = productionGoalPreflight(productionGoal);
|
||||
if (blocked) return blocked;
|
||||
}
|
||||
const modelRole=config.mode==='recover'?config.modelRole||'chat':config.wholeDetail?'detail':'chat';
|
||||
const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole};
|
||||
const bindingConfig={binary:config.binary,profile:config.profile,project:config.project,scope:config.scope,modelRole,
|
||||
dispatchLease:config.dispatchLease,onAuthorizationLost};
|
||||
broker=sharedBroker??new Native98kBroker(bindingConfig);
|
||||
broker.bind(bindingConfig);
|
||||
const brokerStartedAt = performance.now();
|
||||
const info = await broker.info(config.mode==='recover'?{original:true,id:config.productionOriginals?.[0]}
|
||||
:productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined);
|
||||
const brokerReadyAt = performance.now();
|
||||
if (info.accountScope !== config.scope) throw Error('账户已切换,未发送请求');
|
||||
let binding;
|
||||
if(config.ruleCatalog==null&&config.ruleId==null){
|
||||
binding={brandId:'unconfigured',shopId:'unconfigured',categoryId:'unconfigured',brandName:'未配置',shopName:'未配置',categoryName:'未配置',platform:'native-project',version:'unconfigured-v1',source:'explicit-unconfigured-project-discussion',rules:['当前项目未配置品牌/店铺/品类规则。可以讨论通用思路;不得编造或借用其他品牌规则,产品事实以本项目只读资料为准。']};
|
||||
@ -126,8 +167,23 @@ export async function runSession(config, call, sharedBroker, recovery, signal) {
|
||||
const shop = config.ruleCatalog.shops.find(s => s.id === combo.shopId);
|
||||
binding = resolveRules({ brandId: shop.brandId, shopId: shop.id, categoryId: combo.categoryId }, config.ruleCatalog);
|
||||
}
|
||||
store = await ProjectStore.open(config.root, { scope: info.accountScope, project: config.project }, binding, { continuous:true });
|
||||
const canvas = new StdioCanvas(call, config.documentId);
|
||||
store = await storage.ProjectStore.open(config.root, { scope: config.scope, project: config.project }, binding, { continuous:true });
|
||||
signal?.throwIfAborted();
|
||||
broker.bind(bindingConfig);
|
||||
const info = await broker.info(config.mode==='recover'?{original:true,id:config.productionOriginals?.[0]}
|
||||
:productionGoal&&!config.goalUserEntry?{reuseDetailSelection:true}:undefined);
|
||||
const brokerReadyAt = performance.now();
|
||||
if (info.accountScope !== config.scope) throw authorityFailure('scope_changed');
|
||||
store.executionScope={runId:config.runId ?? randomUUID(),outputId:config.outputId,variantId:config.variantId,
|
||||
revision:config.revision,documentKey:config.documentKey};
|
||||
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);
|
||||
const usage = [];
|
||||
host = await DetailPiAgent.open({ store, broker, productionGoal, productionSignal:signal, brokerInfo:info, canvas, projectEvidence:config.projectEvidence, documentId:config.documentId, onEvent: event => {
|
||||
if (event.type === 'usage') usage.push(event);
|
||||
@ -171,15 +227,39 @@ export async function runSession(config, call, sharedBroker, recovery, signal) {
|
||||
outputId:config.outputId, production:config.productProduction===true,
|
||||
});
|
||||
else result = await host.prompt(config.text, { referenceContent: config.referenceContent, goalContinuation: !!productionGoal&&!config.goalUserEntry });
|
||||
signal?.throwIfAborted();
|
||||
if (broker.authority?.error) throw broker.authority.error;
|
||||
const pending = (await broker.status()).pending;
|
||||
const reviews = (await store.get('recovered-tools.json', [])).filter(t => t.phase === 'review');
|
||||
output = { ...result, unknown: pending.length > 0, review: reviews.length > 0, usage, contextUsage: host.contextUsage,
|
||||
pending, bindingHash: store.hash, sessionFile: host.manager.getSessionFile() };
|
||||
if (result.production?.complete) {
|
||||
output.production.execution={...store.executionScope,...store.executionHealth,
|
||||
operationId:randomUUID(),revision:result.production.canvasRevision};
|
||||
await store.appendEvent({type:'export_submitted',...output.production.execution,category:'export',phase:'enqueue',status:'pending'})
|
||||
.catch(error=>console.warn('小壹导出事件写入失败',error.code ?? error.name));
|
||||
}
|
||||
} catch (error) {
|
||||
const authority = [signal?.reason, broker?.authority?.error, error].find(authorityLost);
|
||||
if (authority) {
|
||||
onAuthorizationLost?.(authority);
|
||||
let draftSaved = false;
|
||||
if (store) {
|
||||
const draft = {state:'paused', reason:authority.category, documentId:config.documentId,
|
||||
scope:config.scope, project:config.project, text:config.text, sessionFile:host?.manager.getSessionFile()};
|
||||
try {
|
||||
await atomic(path.join(store.dir, 'authorization-pause.json'), draft);
|
||||
draftSaved = true;
|
||||
} catch { /* The paused receipt reports the actual draft write outcome. */ }
|
||||
}
|
||||
return {phase:'paused', draftSaved, error:authority.message, failure:authority.wire(),
|
||||
unknown:broker?.hasUnconfirmedRequest ?? false, reposted:false};
|
||||
}
|
||||
let pending = [], unknown = false;
|
||||
if (broker) { try { pending = (await broker.status()).pending; unknown = pending.length > 0; } catch { unknown = broker.hasUnconfirmedRequest; } }
|
||||
else if (sharedBroker && sharedBroker.binary===config.binary && sharedBroker.profile===config.profile && sharedBroker.project===config.project && sharedBroker.scope===config.scope) unknown=sharedBroker.hasUnconfirmedRequest;
|
||||
output = { error:error.message, failure:BridgeError.from(error).wire(), unknown, pending, reposted:false, contextUsage:host?.contextUsage };
|
||||
const failure = BridgeError.from(error).wire();
|
||||
output = { error:failure.message, failure, unknown, pending, reposted:false, contextUsage:host?.contextUsage };
|
||||
if (host && productionGoal) {
|
||||
const scope=host.goalRequestScope;
|
||||
const models=pending.filter(request=>request.modelRole==='detail'&&request.detailSlot===scope)
|
||||
@ -192,6 +272,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal) {
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
clearInterval(heartbeat);
|
||||
signal?.removeEventListener('abort',abort);
|
||||
try { if (host) await host.dispose(); } finally { releaseRecovery?.(); if (broker && !sharedBroker) await broker.close(); }
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import path from 'node:path';
|
||||
import { BridgeError, authorityFailure, authorityLost } from './bridge-error.mjs';
|
||||
|
||||
/** Keep an explicit local upstream exception consistent across Windows casing. */
|
||||
export function nativeBrokerEnvironment(profile, source = process.env) {
|
||||
@ -35,27 +36,40 @@ export class Native98kBroker {
|
||||
Object.assign(this, { binary, profile, project, modelRole, invocationHeaders, spawnProcess });
|
||||
this.potentiallyDispatched = new Set();
|
||||
this.dispatchScopes = new Map();
|
||||
this.children = new Set();
|
||||
this.authority = {};
|
||||
}
|
||||
forDetailSlot(slotId) {
|
||||
const worker = new Native98kBroker({binary:this.binary, profile:this.profile, project:this.project, modelRole:this.modelRole, invocationHeaders:this.invocationHeaders, spawnProcess:this.spawnProcess});
|
||||
worker.parent = this;
|
||||
worker.scope = this.scope;
|
||||
worker.authority = this.authority;
|
||||
worker.dispatchLease = this.dispatchLease;
|
||||
worker.detailSlot = slotId;
|
||||
worker.selectionId = this.selectionId;
|
||||
return worker;
|
||||
}
|
||||
bind({ binary, profile, project, scope, modelRole = 'chat' }) {
|
||||
bind({ binary, profile, project, scope, modelRole = 'chat', dispatchLease, onAuthorizationLost }) {
|
||||
if (this.active || this.closed || this.failed) throw Error('模型桥状态不可复用,未派发新请求');
|
||||
if (binary !== this.binary || profile !== this.profile || !/^[a-f0-9-]{36}$/i.test(project) || typeof scope !== 'string' || !scope) throw Error('模型桥账户或项目配置不匹配');
|
||||
if(!['chat','copy','detail'].includes(modelRole))throw Error('模型用途无效');
|
||||
this.project = project; this.scope = scope; this.modelRole=modelRole; this.invocationHeaders = {};
|
||||
this.selectionId = undefined;
|
||||
this.authority = { onAuthorizationLost };
|
||||
this.dispatchLease = dispatchLease;
|
||||
const identity = JSON.stringify([scope, project]);
|
||||
if (!this.dispatchScopes.has(identity)) this.dispatchScopes.set(identity, new Set());
|
||||
this.potentiallyDispatched = this.dispatchScopes.get(identity);
|
||||
}
|
||||
async open() {
|
||||
revoke(error, notify = true) {
|
||||
if (!this.authority.error) {
|
||||
this.authority.error = error;
|
||||
if (notify) this.authority.onAuthorizationLost?.(error);
|
||||
}
|
||||
}
|
||||
async open(signal) {
|
||||
if (this.failed) throw this.failed;
|
||||
if (this.closed) throw Error('模型桥已关闭');
|
||||
if (this.closed || this.parent?.closed) throw Error('模型桥已关闭');
|
||||
if (this.child) return;
|
||||
let local;
|
||||
try { local = JSON.parse((await fs.readFile(path.join(this.profile, 'jiansun', 'runtime-network.json'), 'utf8')).replace(/^\uFEFF/, '')); }
|
||||
@ -63,9 +77,11 @@ export class Native98kBroker {
|
||||
const owned = ownedBrokerNetwork(local, process.ppid, this.binary);
|
||||
const env = nativeBrokerEnvironment(this.profile, owned ? { ...process.env, PHOTOCRAFT_BYPASS_UPSTREAM_PROXY: '1' } : process.env);
|
||||
if (owned) await fs.appendFile(path.join(this.profile, 'jiansun', 'runtime-network-audit.jsonl'), JSON.stringify({at:Date.now(),method:'rpc',ownerPid:process.ppid,upstreamExceptionApplied:true,noProxyAliasesMatch:env.NO_PROXY===env.no_proxy})+'\n');
|
||||
if (this.closed) throw Error('模型桥已关闭');
|
||||
signal?.throwIfAborted();
|
||||
if (this.closed || this.parent?.closed) throw Error('模型桥已关闭');
|
||||
const child = this.spawnProcess(this.binary, ['--jiansun-pi-rpc'], { env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
||||
this.child = child;
|
||||
this.parent?.children.add(this);
|
||||
this.exited = new Promise(resolve => child.once('close', resolve));
|
||||
const fail = () => {
|
||||
if (this.closed) return;
|
||||
@ -79,11 +95,16 @@ export class Native98kBroker {
|
||||
try { value = JSON.parse(line); } catch { fail(); return; }
|
||||
const active = this.active;
|
||||
if (!active || !value || !['headers', 'chunk', 'result', 'error'].includes(value.type) || (value.type === 'error' && typeof value.error !== 'string') || (value.type === 'result' && (!value.value || typeof value.value !== 'object')) || (['headers', 'chunk'].includes(value.type) && !['request', 'recover'].includes(active.method))) { fail(); return; }
|
||||
if (value.type === 'headers' && value.status === 401) {
|
||||
if (active.method === 'request') this.potentiallyDispatched.delete(active.requestId);
|
||||
this.revoke(authorityFailure('auth_revoked', {dispatched:true}));
|
||||
}
|
||||
try { active.onEvent(value); } catch { fail(); return; }
|
||||
if (value.type === 'result' || value.type === 'error') {
|
||||
this.active = null;
|
||||
if (value.type === 'error') {
|
||||
const error = Error(value.error);
|
||||
const error = new BridgeError(value.error, value.category, value);
|
||||
if (authorityLost(error)) this.revoke(error);
|
||||
if (active.method === 'request' && value.dispatched === false) {
|
||||
this.potentiallyDispatched.delete(active.requestId);
|
||||
error.retryPreparation = value.retryPreparation === true;
|
||||
@ -100,16 +121,25 @@ export class Native98kBroker {
|
||||
child.once('error', fail);
|
||||
child.once('close', fail);
|
||||
}
|
||||
async start(method, args = {}, onEvent = () => {}) {
|
||||
async start(method, args = {}, onEvent = () => {}, signal) {
|
||||
signal?.throwIfAborted();
|
||||
if (method !== 'info' && !this.scope) await this.info();
|
||||
const authority = this.authority;
|
||||
const run = async () => {
|
||||
await this.open();
|
||||
signal?.throwIfAborted();
|
||||
const needsAuthority = !['status','read','finish'].includes(method);
|
||||
if (authority !== this.authority) throw authorityFailure('scope_changed');
|
||||
if (needsAuthority && authority.error) throw authority.error;
|
||||
await this.open(signal);
|
||||
signal?.throwIfAborted();
|
||||
if (authority !== this.authority) throw authorityFailure('scope_changed');
|
||||
if (needsAuthority && authority.error) throw authority.error;
|
||||
if (this.failed) throw this.failed;
|
||||
if (this.closed) throw Error('模型桥已关闭');
|
||||
return new Promise((resolve, reject) => {
|
||||
this.active = { resolve, reject, onEvent, method, requestId: args.id };
|
||||
if (method === 'request' && args.id && args.inference !== true) this.potentiallyDispatched.add(args.id);
|
||||
try { this.child.stdin.write(JSON.stringify({ method, project: this.project, accountScope: this.scope, ...(this.modelRole==='chat'?{}:{modelRole:this.modelRole}), ...(this.detailSlot?{detailSlot:this.detailSlot}:{}), ...args }) + '\n', error => {
|
||||
try { this.child.stdin.write(JSON.stringify({ ...args, method, project: this.project, accountScope: this.scope, ...(this.modelRole==='chat'?{}:{modelRole:this.modelRole}), ...(this.detailSlot?{detailSlot:this.detailSlot}:{}), dispatchLease:this.dispatchLease }) + '\n', error => {
|
||||
if (error && this.active) { this.failed = Error('模型桥连接中断;请核查原请求,不会重发'); const active = this.active; this.active = null; active.reject(this.failed); this.child.kill(); }
|
||||
}); } catch { this.failed = Error('模型桥连接中断;请核查原请求,不会重发'); this.active = null; reject(this.failed); this.child.kill(); }
|
||||
});
|
||||
@ -127,6 +157,7 @@ export class Native98kBroker {
|
||||
isUnconfirmed(id) { return this.potentiallyDispatched.has(id); }
|
||||
async close({ force = false } = {}) {
|
||||
this.closed = true;
|
||||
const children = [...this.children].map(worker => worker.close({ force }));
|
||||
const active = this.active;
|
||||
if (active) { this.active = null; active.reject(Error('模型桥已关闭,原请求需核查;不会重发')); }
|
||||
if (this.child) {
|
||||
@ -135,11 +166,17 @@ export class Native98kBroker {
|
||||
const timer = setTimeout(() => this.child.kill(), 2000);
|
||||
try { await this.exited; } finally { clearTimeout(timer); }
|
||||
}
|
||||
await Promise.all(children);
|
||||
this.parent?.children.delete(this);
|
||||
}
|
||||
status() { return this.start('status'); }
|
||||
async info(args) {
|
||||
const info = await this.start('info', args);
|
||||
if (this.scope && info.accountScope !== this.scope) throw Error('账户已改变,请切回原账户');
|
||||
if (this.scope && info.accountScope !== this.scope) {
|
||||
const error = authorityFailure('scope_changed');
|
||||
this.revoke(error);
|
||||
throw error;
|
||||
}
|
||||
this.scope = info.accountScope;
|
||||
if (info.invocationHeaders) this.invocationHeaders = info.invocationHeaders;
|
||||
this.selectionId = info.selectionId ?? undefined;
|
||||
@ -165,14 +202,14 @@ export class Native98kBroker {
|
||||
metadata = event;
|
||||
resolveHeaders(new Response(body, { status: event.status, headers: event.headers }));
|
||||
} else if (event.type === 'chunk') enqueue(Buffer.from(event.data, 'base64'));
|
||||
});
|
||||
}, init.signal);
|
||||
if (inference && this.failed) {
|
||||
await this.exited;
|
||||
this.child = null;
|
||||
this.failed = null;
|
||||
}
|
||||
const abort = () => {
|
||||
if (this.active?.requestId === id) this.child?.kill();
|
||||
if (!this.authority.error && this.active?.requestId === id) this.child?.kill();
|
||||
};
|
||||
init.signal?.addEventListener('abort', abort, {once:true});
|
||||
completed = request().catch(error=>{
|
||||
|
||||
@ -231,7 +231,7 @@ export async function openProductionOperations(host) {
|
||||
};
|
||||
let displayEpoch=0;
|
||||
const progress=async ({heading,epoch})=>{
|
||||
if(epoch!==displayEpoch||host.canvasEndAttempted)return;
|
||||
if(epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return;
|
||||
const pictureCells=slots.map(({id,label})=>{
|
||||
const item=journal.items[id];
|
||||
const matched=filled.has(id);
|
||||
@ -243,13 +243,18 @@ export async function openProductionOperations(host) {
|
||||
label,state:!templateSample&&evidenceMatches(plan)&&journal.copyEvidence?.[layer]?.text===currentText?'verified':
|
||||
!templateSample&¤tText?'filled':'empty',
|
||||
}));
|
||||
if(epoch!==displayEpoch||host.canvasEndAttempted)return;
|
||||
return canvas.delta('',undefined,{heading,outputId,variantId,workers:[...jobs.values()].map(job=>job.row),
|
||||
reviews:pendingReviews().map(job=>job.row),candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells,
|
||||
total:slots.length,rendered:filled.size,copy:copyCells.filter(row=>row.state==='verified').length,
|
||||
if(epoch!==displayEpoch||host.canvasEndAttempted||host.productionSignal?.aborted)return;
|
||||
const jobProgress={total:slots.length,rendered:filled.size,
|
||||
copy:copyCells.filter(row=>row.state==='verified').length,
|
||||
copyPending:copyCells.filter(row=>row.state!=='verified').length,
|
||||
unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption||
|
||||
Object.keys(item.pendingGenerations??{}).length).length});
|
||||
Object.keys(item.pendingGenerations??{}).length).length};
|
||||
const category=jobs.size?'remote_image':pendingReviews().length?'inference':'canvas_read';
|
||||
await store.appendEvent({type:'production_progress',category,phase:'progress',status:'running',outputId,variantId,jobProgress});
|
||||
return canvas.delta('',undefined,{heading,outputId,variantId,category,phase:'progress',status:'running',
|
||||
workers:[...jobs.values()].map(job=>job.row),
|
||||
reviews:pendingReviews().map(job=>job.row),candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells,
|
||||
...jobProgress});
|
||||
};
|
||||
const display=new PresentationBatch(progress);
|
||||
const notice=heading=>display.push({heading,epoch:displayEpoch});
|
||||
@ -375,7 +380,7 @@ export async function openProductionOperations(host) {
|
||||
}
|
||||
const {operationId}=original;
|
||||
let receipt;
|
||||
try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id}); }
|
||||
try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id},{operationId,requestId:candidateId}); }
|
||||
catch(error) {
|
||||
if (error.dispatched===false) {
|
||||
await update(journal=>{delete journal.items[slot.id].pendingGenerations[candidateId];},
|
||||
@ -387,17 +392,25 @@ export async function openProductionOperations(host) {
|
||||
}
|
||||
const phase=receipt.status??receipt.phase;
|
||||
const settled=settledImagePhases.includes(phase);
|
||||
const late=signal?.aborted || host.productionSignal?.aborted;
|
||||
const evidence={...receipt,requestId:candidateId,operationId,reworkOf:request.reworkOf,
|
||||
...(late?{consumption:'archived_after_cancel'}:null)};
|
||||
await update(journal=>{
|
||||
const item=journal.items[slot.id]??={};
|
||||
if(settled)delete item.pendingGenerations[candidateId];
|
||||
if(late)return;
|
||||
if(settled)Object.assign(item,{candidateId,state:phase==='complete'?'candidate':phase});
|
||||
Object.assign(item,{prompt:request.prompt,source:'generate'});
|
||||
const attempts=item.attempts??=[];
|
||||
if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate',
|
||||
prompt:request.prompt,reworkOf:request.reworkOf,change:request.reworkChange});
|
||||
rememberImageExpiry(item,candidateId,receipt);
|
||||
},{receipt:[candidateId,settled?phase:'unknown',receipt],
|
||||
evidence:[slot.id,candidateId,'candidate',{requestId:candidateId,...receipt,operationId,reworkOf:request.reworkOf}]});
|
||||
},{receipt:[candidateId,settled?phase:'unknown',evidence],
|
||||
evidence:[slot.id,candidateId,'candidate',evidence]});
|
||||
await store.appendEvent({type:'image_request_receipt',operationId,requestId:candidateId,outputId,variantId,slotId:slot.id,
|
||||
category:'remote_image',phase:'archive',status:late?'cancelled':settled?phase:'unknown',consumption:evidence.consumption})
|
||||
.catch(error=>console.warn('小壹生图事件写入失败',error.code ?? error.name));
|
||||
if(late)return {candidateId,operationId,phase:'cancelled',consumption:evidence.consumption};
|
||||
return {candidateId,operationId,phase:settled?phase:'unknown',reason:receipt.message,
|
||||
requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null),
|
||||
...(!settled?{pendingOriginal:candidateId}:null),
|
||||
@ -556,7 +569,12 @@ export async function openProductionOperations(host) {
|
||||
}
|
||||
return {
|
||||
get active(){return jobs.size;},
|
||||
async close(){await drain();displayEpoch++;},
|
||||
async close(){
|
||||
await drain();
|
||||
await canvasWrite;
|
||||
await journalWrite;
|
||||
displayEpoch++;
|
||||
},
|
||||
async plan_production({slotIds}={}){
|
||||
await current({refresh:true});
|
||||
recordProductionInputs(repository,plan,slots);
|
||||
|
||||
@ -1,22 +1,23 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
export async function requestPurpose(host, id) {
|
||||
const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;});
|
||||
const events = text.split('\n').filter(Boolean).map(line => {try {return JSON.parse(line);} catch {return null;}}).filter(Boolean);
|
||||
const index = events.findIndex(event => event.type === 'provider_prepared' && event.id === id && (!event.bindingHash || event.bindingHash === host.store.hash));
|
||||
if (index < 0) throw Error('原请求没有当前会话归属记录');
|
||||
const event = events[index];
|
||||
if (event.purpose === 'compaction') return {kind: 'compaction', event};
|
||||
if (['whole-detail-review','whole-detail-worker','product-goal'].includes(event.purpose)) return {kind:event.purpose,event};
|
||||
if (event.purpose === 'conversation') return {kind: 'conversation', event};
|
||||
// Legacy automatic summaries lack a durable cut-point contract. Recognize
|
||||
// their purpose, but never guess a checkpoint from the returned prose.
|
||||
let started = -1, finished = -1;
|
||||
for (let i = 0; i < index; i++) {
|
||||
if (events[i].type === 'automatic_compaction_started') started = i;
|
||||
if (events[i].type === 'automatic_compaction_completed') finished = i;
|
||||
}
|
||||
if (started > finished) return {kind: 'legacy-compaction', event};
|
||||
return {kind: 'conversation', event};
|
||||
}
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
export async function requestPurpose(host, id) {
|
||||
const text = await fs.readFile(path.join(host.store.dir, 'events.jsonl'), 'utf8').catch(error => {if (error.code === 'ENOENT') return ''; throw error;});
|
||||
const events = text.split('\n').filter(Boolean).map(line => {try {return JSON.parse(line);} catch {return null;}}).filter(Boolean);
|
||||
const index = events.findIndex(event => event.type === 'provider_prepared' && event.id === id && (!event.bindingHash || event.bindingHash === host.store.hash));
|
||||
if (index < 0) throw Error('原请求没有当前会话归属记录');
|
||||
const event = events[index];
|
||||
if (events.some(row=>row.id===id && row.consumption==='discarded_after_cancel')) return {kind:'cancelled',event};
|
||||
if (event.purpose === 'compaction') return {kind: 'compaction', event};
|
||||
if (['whole-detail-review','whole-detail-worker','product-goal'].includes(event.purpose)) return {kind:event.purpose,event};
|
||||
if (event.purpose === 'conversation') return {kind: 'conversation', event};
|
||||
// Legacy automatic summaries lack a durable cut-point contract. Recognize
|
||||
// their purpose, but never guess a checkpoint from the returned prose.
|
||||
let started = -1, finished = -1;
|
||||
for (let i = 0; i < index; i++) {
|
||||
if (events[i].type === 'automatic_compaction_started') started = i;
|
||||
if (events[i].type === 'automatic_compaction_completed') finished = i;
|
||||
}
|
||||
if (started > finished) return {kind: 'legacy-compaction', event};
|
||||
return {kind: 'conversation', event};
|
||||
}
|
||||
|
||||
@ -1,114 +1,118 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { BridgeError } from './bridge-error.mjs';
|
||||
|
||||
export function canvasReplyTimedOut(error) {
|
||||
return error?.category === 'transport_interrupted';
|
||||
}
|
||||
|
||||
/** Private parent/child pipes; no production terminal or general control socket. */
|
||||
export class StdioCanvas {
|
||||
durableGenerationIds = true;
|
||||
constructor(call, documentId) { this.call = call; this.documentId = documentId; }
|
||||
action(action, input = {}) { return this.call(action, { ...input, run: this.run, documentId: this.documentId }); }
|
||||
async #observe(action, input = {}, signal) {
|
||||
const {run,documentId}=this;
|
||||
const deadline=Date.now()+120_000;
|
||||
for(;;){
|
||||
signal?.throwIfAborted();
|
||||
if(this.run!==run||this.documentId!==documentId)throw Error('原回合已结束,未继续查询');
|
||||
try { return await this.call(action,{...input,run,documentId}); }
|
||||
catch(error) {
|
||||
if(!canvasReplyTimedOut(error)||Date.now()>=deadline)throw error;
|
||||
await delay(500,undefined,{signal});
|
||||
}
|
||||
}
|
||||
}
|
||||
async begin(text) { this.run = randomUUID(); return this.action('pi-begin', { text, ...(this.identity || {}) }); }
|
||||
read() { return this.#observe('pi-state'); }
|
||||
async openProductionOutput({outputId,variantId},signal) {
|
||||
signal?.throwIfAborted();
|
||||
let status;
|
||||
try {
|
||||
status=await this.action('pi-production-open',{outputId,variantId});
|
||||
} catch(error) {
|
||||
if (!canvasReplyTimedOut(error)) throw error;
|
||||
status=await this.#observe('pi-state',{},signal);
|
||||
}
|
||||
while(status.openingProductionCanvas) {
|
||||
await delay(500,undefined,{signal});
|
||||
status=await this.#observe('pi-state',{},signal);
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
const binding=status.productionCanvas;
|
||||
if(binding?.outputId!==outputId || binding.variantId!==variantId) {
|
||||
if (status.conversationActive === false) {
|
||||
throw new BridgeError('制作项目已切换,原画布操作已保留','scope_changed');
|
||||
}
|
||||
throw new BridgeError(status.error || '所选画布尚未绑定,请重新打开本轮工作画布',
|
||||
'production_canvas_open_failed',{retryable:true});
|
||||
}
|
||||
return binding;
|
||||
}
|
||||
readCanvas(input = {}) { return this.action('pi-canvas-read', input); }
|
||||
imageRequest(action,request) { return this.action('pi-image-request',{action,request}); }
|
||||
detailRender(options) { return this.#observe('pi-product-screen', options); }
|
||||
detailCopyFields(options) { return this.#observe('pi-detail-copy-fields', options); }
|
||||
detailApplyCopy(items,revision) { return this.action('pi-detail-copy-apply',{items,revision}); }
|
||||
commitDetailCopy(items,revision,signal) {
|
||||
signal?.throwIfAborted();
|
||||
return this.action('pi-detail-copy-apply',{items,revision,matchFields:true});
|
||||
}
|
||||
detailRetire(slotId,candidateId,reason) { return this.action('pi-detail-archive',{slotId,source:{candidateId,retireReason:reason}}); }
|
||||
detailHistory(options) { return this.action('pi-detail-archive',options); }
|
||||
detailArchive(slotId,{projectId,candidateId,forReview}) { return this.action('pi-detail-archive',{slotId,source:{projectId,candidateId,forReview}}); }
|
||||
detailRecover(slotId,{projectId,candidateId}) { return this.action('pi-detail-archive',{slotId,source:{projectId,candidateId,recover:true}}); }
|
||||
detailImages(slotId,candidateId,options) { return this.#observe('pi-detail-images', {slotId,candidateId,...options}); }
|
||||
detailCropPreview(slotId,referenceIndex,referenceCrop) {
|
||||
return this.#observe('pi-detail-images', {slotId,cropPreview:{referenceIndex,referenceCrop}});
|
||||
}
|
||||
readTemplateImage(fieldId) { return this.action('pi-template-image', { fieldId }); }
|
||||
nativeCatalog(input = {}) { return this.action('pi-native-catalog', input); }
|
||||
nativeCall(input) { return this.action('pi-native-call', input); }
|
||||
nativePoll(job) { return this.action('pi-native-poll', { job }); }
|
||||
nativeReconcile({ run, documentId, job }) { return this.call('pi-native-reconcile', { run, documentId, job }); }
|
||||
editReconcile({run,documentId,beforeRevision,command,targetLayerId}) { return this.call('pi-edit-reconcile', {run,documentId,beforeRevision,command,targetLayerId}); }
|
||||
preview(input) { return this.action('pi-preview', input); }
|
||||
copyOptions(input) { return this.action('pi-copy-options', input); }
|
||||
copyFields(input) { return this.action('pi-copy-fields',input); }
|
||||
uiRequest(request) { return this.action('pi-ui-request', { request }); }
|
||||
uiPoll(id) { return this.action('pi-ui-poll', { id }); }
|
||||
uiCancel(id) { return this.action('pi-ui-cancel', { id }); }
|
||||
async delta(text, thinking, production, output) {
|
||||
try {
|
||||
return await this.action('pi-delta',{text,...(thinking===undefined?{}:{thinking}),...(production?{production}:{}),...(output?{output}:{})});
|
||||
} catch(error) {
|
||||
if(!production||!canvasReplyTimedOut(error))throw error;
|
||||
}
|
||||
}
|
||||
reply(text) { return this.action('pi-reply', {text}); }
|
||||
activity(text, event) { return this.action('pi-activity', { text, ...(event ? { event } : {}) }); }
|
||||
async contextUsage(value) {
|
||||
try { return await this.action('pi-context-usage', { value }); }
|
||||
catch (error) { if (!canvasReplyTimedOut(error)) throw error; }
|
||||
}
|
||||
requestWrite(revision) { return this.action('pi-write-request', { revision }); }
|
||||
workflowRead(input = {}) { return this.#observe('pi-workflow-read', input); }
|
||||
workflowNavigate(input) { return this.action('pi-workflow-navigate', input); }
|
||||
workflowPropose(input) { return this.action('pi-workflow-propose', input); }
|
||||
workflowExecute(input) { return this.action('pi-workflow-execute', input); }
|
||||
workflowPoll(operationId) { return this.#observe('pi-workflow-poll', { operationId }); }
|
||||
workflowReconcile({ run, documentId, operationId, adoption }) { return this.call('pi-workflow-reconcile', { run, documentId, operationId, ...(adoption?{adoption}:null) }); }
|
||||
async edit(edit, revision, signal) {
|
||||
signal?.throwIfAborted();
|
||||
await this.action('pi-edit', { edit, revision });
|
||||
for (;;) {
|
||||
await delay(90, undefined, {signal});
|
||||
const state = await this.read();
|
||||
if (!state.allowed) throw Error('用户已接手,后续画布操作已停止');
|
||||
if (state.error) throw Error(state.error);
|
||||
if (!state.queued && state.revision !== revision) return state;
|
||||
}
|
||||
}
|
||||
end(text) { return this.action('pi-end', { text }); }
|
||||
}
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { BridgeError } from './bridge-error.mjs';
|
||||
|
||||
export function canvasReplyTimedOut(error) {
|
||||
return error?.category === 'transport_interrupted';
|
||||
}
|
||||
|
||||
/** Private parent/child pipes; no production terminal or general control socket. */
|
||||
export class StdioCanvas {
|
||||
durableGenerationIds = true;
|
||||
constructor(call, documentId) { this.call = call; this.documentId = documentId; }
|
||||
action(action, input = {}, execution) {
|
||||
return this.call(action, { ...input, run: this.run, documentId: this.documentId }, execution);
|
||||
}
|
||||
async #observe(action, input = {}, signal) {
|
||||
const {run,documentId}=this;
|
||||
const deadline=Date.now()+120_000;
|
||||
const operationId=randomUUID();
|
||||
let attempt=0;
|
||||
for(;;){
|
||||
signal?.throwIfAborted();
|
||||
if(this.run!==run||this.documentId!==documentId)throw Error('原回合已结束,未继续查询');
|
||||
try { return await this.call(action,{...input,run,documentId},{operationId,attempt:++attempt}); }
|
||||
catch(error) {
|
||||
if(!canvasReplyTimedOut(error)||Date.now()>=deadline)throw error;
|
||||
await delay(500,undefined,{signal});
|
||||
}
|
||||
}
|
||||
}
|
||||
async begin(text) { this.run = randomUUID(); return this.action('pi-begin', { text, ...(this.identity || {}) }); }
|
||||
read() { return this.#observe('pi-state'); }
|
||||
async openProductionOutput({outputId,variantId},signal) {
|
||||
signal?.throwIfAborted();
|
||||
let status;
|
||||
try {
|
||||
status=await this.action('pi-production-open',{outputId,variantId});
|
||||
} catch(error) {
|
||||
if (!canvasReplyTimedOut(error)) throw error;
|
||||
status=await this.#observe('pi-state',{},signal);
|
||||
}
|
||||
while(status.openingProductionCanvas) {
|
||||
await delay(500,undefined,{signal});
|
||||
status=await this.#observe('pi-state',{},signal);
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
const binding=status.productionCanvas;
|
||||
if(binding?.outputId!==outputId || binding.variantId!==variantId) {
|
||||
if (status.conversationActive === false) {
|
||||
throw new BridgeError('制作项目已切换,原画布操作已保留','scope_changed');
|
||||
}
|
||||
throw new BridgeError(status.error || '所选画布尚未绑定,请重新打开本轮工作画布',
|
||||
'production_canvas_open_failed',{retryable:true});
|
||||
}
|
||||
return binding;
|
||||
}
|
||||
readCanvas(input = {}) { return this.action('pi-canvas-read', input); }
|
||||
imageRequest(action,request,execution) { return this.action('pi-image-request',{action,request},execution); }
|
||||
detailRender(options) { return this.#observe('pi-product-screen', options); }
|
||||
detailCopyFields(options) { return this.#observe('pi-detail-copy-fields', options); }
|
||||
detailApplyCopy(items,revision) { return this.action('pi-detail-copy-apply',{items,revision}); }
|
||||
commitDetailCopy(items,revision,signal) {
|
||||
signal?.throwIfAborted();
|
||||
return this.action('pi-detail-copy-apply',{items,revision,matchFields:true});
|
||||
}
|
||||
detailRetire(slotId,candidateId,reason) { return this.action('pi-detail-archive',{slotId,source:{candidateId,retireReason:reason}}); }
|
||||
detailHistory(options) { return this.action('pi-detail-archive',options); }
|
||||
detailArchive(slotId,{projectId,candidateId,forReview}) { return this.action('pi-detail-archive',{slotId,source:{projectId,candidateId,forReview}}); }
|
||||
detailRecover(slotId,{projectId,candidateId}) { return this.action('pi-detail-archive',{slotId,source:{projectId,candidateId,recover:true}}); }
|
||||
detailImages(slotId,candidateId,options) { return this.#observe('pi-detail-images', {slotId,candidateId,...options}); }
|
||||
detailCropPreview(slotId,referenceIndex,referenceCrop) {
|
||||
return this.#observe('pi-detail-images', {slotId,cropPreview:{referenceIndex,referenceCrop}});
|
||||
}
|
||||
readTemplateImage(fieldId) { return this.action('pi-template-image', { fieldId }); }
|
||||
nativeCatalog(input = {}) { return this.action('pi-native-catalog', input); }
|
||||
nativeCall(input) { return this.action('pi-native-call', input); }
|
||||
nativePoll(job) { return this.action('pi-native-poll', { job }); }
|
||||
nativeReconcile({ run, documentId, job }) { return this.call('pi-native-reconcile', { run, documentId, job }); }
|
||||
editReconcile({run,documentId,beforeRevision,command,targetLayerId}) { return this.call('pi-edit-reconcile', {run,documentId,beforeRevision,command,targetLayerId}); }
|
||||
preview(input) { return this.action('pi-preview', input); }
|
||||
copyOptions(input) { return this.action('pi-copy-options', input); }
|
||||
copyFields(input) { return this.action('pi-copy-fields',input); }
|
||||
uiRequest(request) { return this.action('pi-ui-request', { request }); }
|
||||
uiPoll(id) { return this.action('pi-ui-poll', { id }); }
|
||||
uiCancel(id) { return this.action('pi-ui-cancel', { id }); }
|
||||
async delta(text, thinking, production, output) {
|
||||
try {
|
||||
return await this.action('pi-delta',{text,...(thinking===undefined?{}:{thinking}),...(production?{production}:{}),...(output?{output}:{})});
|
||||
} catch(error) {
|
||||
if(!production||!canvasReplyTimedOut(error))throw error;
|
||||
}
|
||||
}
|
||||
reply(text) { return this.action('pi-reply', {text}); }
|
||||
activity(text, event) { return this.action('pi-activity', { text, ...(event ? { event } : {}) }); }
|
||||
async contextUsage(value) {
|
||||
try { return await this.action('pi-context-usage', { value }); }
|
||||
catch (error) { if (!canvasReplyTimedOut(error)) throw error; }
|
||||
}
|
||||
requestWrite(revision) { return this.action('pi-write-request', { revision }); }
|
||||
workflowRead(input = {}) { return this.#observe('pi-workflow-read', input); }
|
||||
workflowNavigate(input) { return this.action('pi-workflow-navigate', input); }
|
||||
workflowPropose(input) { return this.action('pi-workflow-propose', input); }
|
||||
workflowExecute(input) { return this.action('pi-workflow-execute', input); }
|
||||
workflowPoll(operationId) { return this.#observe('pi-workflow-poll', { operationId }); }
|
||||
workflowReconcile({ run, documentId, operationId, adoption }) { return this.call('pi-workflow-reconcile', { run, documentId, operationId, ...(adoption?{adoption}:null) }); }
|
||||
async edit(edit, revision, signal) {
|
||||
signal?.throwIfAborted();
|
||||
await this.action('pi-edit', { edit, revision });
|
||||
for (;;) {
|
||||
await delay(90, undefined, {signal});
|
||||
const state = await this.read();
|
||||
if (!state.allowed) throw Error('用户已接手,后续画布操作已停止');
|
||||
if (state.error) throw Error(state.error);
|
||||
if (!state.queued && state.revision !== revision) return state;
|
||||
}
|
||||
}
|
||||
end(text) { return this.action('pi-end', { text }); }
|
||||
}
|
||||
|
||||
@ -3,6 +3,8 @@ import path from 'node:path';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { ruleContext, templateConstraints } from './rule-context.mjs';
|
||||
import { redact, redactText } from './credentials.mjs';
|
||||
import { executionEvent } from './activity-event.mjs';
|
||||
|
||||
export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
export async function atomic(file, value) {
|
||||
@ -10,7 +12,7 @@ export async function atomic(file, value) {
|
||||
const temp = `${file}.${randomUUID()}.tmp`;
|
||||
const handle = await fs.open(temp, 'wx', 0o600);
|
||||
try {
|
||||
try { await handle.writeFile(JSON.stringify(value, null, 2)); await handle.sync(); } finally { await handle.close(); }
|
||||
try { await handle.writeFile(JSON.stringify(redact(value), null, 2)); await handle.sync(); } finally { await handle.close(); }
|
||||
const retryDelays = [25, 75, 225];
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
@ -42,11 +44,20 @@ async function copyIdentical(file, bytes) {
|
||||
if (!stat.isFile() || stat.isSymbolicLink() || !(await fs.readFile(file)).equals(bytes)) throw Error('旧会话迁移目标与原件不一致,请保留文件核查');
|
||||
}
|
||||
}
|
||||
function cleanLegacyJsonLines(bytes) {
|
||||
return Buffer.from(bytes.toString('utf8').split(/(?<=\n)/).map(line => {
|
||||
if (!line.trim()) return line;
|
||||
const value = JSON.parse(line);
|
||||
const safe = JSON.stringify(redact(value));
|
||||
return safe === JSON.stringify(value) ? line : safe + (line.endsWith('\n') ? '\n' : '');
|
||||
}).join(''));
|
||||
}
|
||||
export class ProjectStore {
|
||||
static async open(root, identity, binding, { continuous = false } = {}) {
|
||||
if (!/^[a-f0-9]{64}$/.test(identity.scope) || !/^[a-f0-9-]{36}$/i.test(identity.project)) throw Error('项目身份无效');
|
||||
for (const key of ['brandId', 'shopId', 'categoryId', 'platform', 'version', 'source']) if (typeof binding[key] !== 'string' || !binding[key]) throw Error(`规则缺少 ${key}`);
|
||||
if (!Array.isArray(binding.rules) || binding.rules.length > 100 || binding.rules.some(s => typeof s !== 'string' || s.length > 2000)) throw Error('规则内容无效');
|
||||
binding = redact(binding);
|
||||
const dir = path.join(root, identity.scope, identity.project), hash = digest(binding);
|
||||
// Different shop/category/version gets an independent conversation and memory.
|
||||
const ruleDir = path.join(dir, hash);
|
||||
@ -71,8 +82,17 @@ export class ProjectStore {
|
||||
if(!resolved.startsWith(realLegacy+path.sep)||!resolved.endsWith('.jsonl'))throw Error('旧会话文件不属于当前项目,未迁移');
|
||||
const bytes=await fs.readFile(resolved),target=path.join(scopeDir,'sessions','legacy-'+previous.bindingHash+'.jsonl');
|
||||
await fs.mkdir(path.dirname(target),{recursive:true});
|
||||
await copyIdentical(target,bytes);
|
||||
for(const name of ['events.jsonl','recovered-tools.json'])if(await exists(path.join(legacy,name)))await copyIdentical(path.join(scopeDir,name),await fs.readFile(path.join(legacy,name)));
|
||||
await copyIdentical(target,cleanLegacyJsonLines(bytes));
|
||||
for (const name of ['events.jsonl','recovered-tools.json']) {
|
||||
if (!await exists(path.join(legacy,name))) continue;
|
||||
const original = await fs.readFile(path.join(legacy,name));
|
||||
const safe = name.endsWith('.jsonl') ? cleanLegacyJsonLines(original) : (() => {
|
||||
const value = JSON.parse(original);
|
||||
const sanitized = JSON.stringify(redact(value));
|
||||
return sanitized === JSON.stringify(value) ? original : Buffer.from(sanitized);
|
||||
})();
|
||||
await copyIdentical(path.join(scopeDir,name),safe);
|
||||
}
|
||||
await copyIdentical(path.join(scopeDir,'migration.json'),Buffer.from(JSON.stringify({sourceBindingHash:previous.bindingHash,sourceSha256:createHash('sha256').update(bytes).digest('hex'),originalRetained:true},null,2)));
|
||||
// Publish the pointer last, after every required file is durably present.
|
||||
await copyIdentical(path.join(scopeDir,'session.json'),Buffer.from(JSON.stringify({file:target},null,2)));
|
||||
@ -105,6 +125,7 @@ export class ProjectStore {
|
||||
}
|
||||
async recordUserEvidence(text) {
|
||||
if(typeof text!=='string'||!text.trim()||text.length>6000)throw Error('当前用户证据无效');
|
||||
text = redactText(text);
|
||||
await fs.appendFile(path.join(this.memoryDir,'user-evidence.jsonl'),JSON.stringify({...this.identity,bindingHash:this.hash,text,textHash:digest(text),at:Date.now()})+'\n',{mode:0o600});
|
||||
}
|
||||
async context() {
|
||||
@ -117,7 +138,8 @@ export class ProjectStore {
|
||||
constraints: templateConstraints(this.binding, options) };
|
||||
}
|
||||
async appendEvent(event) {
|
||||
await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify({ at: Date.now(), ...event }) + '\n', { mode: 0o600 });
|
||||
const record = executionEvent(event, {projectId:this.identity.project,...this.executionScope}, this.executionHealth ?? {});
|
||||
await fs.appendFile(path.join(this.dir, 'events.jsonl'), JSON.stringify(redact(record)) + '\n', { mode: 0o600 });
|
||||
}
|
||||
async ownsRequest(id) {
|
||||
let text; try { text = await fs.readFile(path.join(this.dir, 'events.jsonl'), 'utf8'); } catch { return false; }
|
||||
|
||||
104
apps/detail-agent-pi/test/account-authorization.test.mjs
Normal file
104
apps/detail-agent-pi/test/account-authorization.test.mjs
Normal file
@ -0,0 +1,104 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { test } from 'node:test';
|
||||
import { SessionManager } from '@earendil-works/pi-coding-agent';
|
||||
import { BridgeError } from '../src/bridge-error.mjs';
|
||||
import { protectSession } from '../src/credentials.mjs';
|
||||
import { runSession } from '../src/desktop-host.mjs';
|
||||
import { Native98kBroker } from '../src/native-bridge.mjs';
|
||||
import { ProjectStore } from '../src/store.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
|
||||
const scope = 'a'.repeat(64);
|
||||
const nextScope = 'b'.repeat(64);
|
||||
const binding = {brandId:'brand',shopId:'shop',categoryId:'category',platform:'local',version:'1',source:'fixture',rules:[]};
|
||||
|
||||
async function fixture(t) {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-auth-'));
|
||||
t.after(() => cleanup(root));
|
||||
return {root, profile:root, binary:'fixture', scope, project:randomUUID(), documentId:7};
|
||||
}
|
||||
|
||||
test('native HTTP 401 revokes the bound broker and all workers without another dispatch', async t => {
|
||||
const config = await fixture(t);
|
||||
const child = new EventEmitter();
|
||||
for (const name of ['stdin', 'stdout', 'stderr']) child[name] = new PassThrough();
|
||||
child.stdin.once('finish', () => {
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit('close', 0);
|
||||
});
|
||||
const requests = [];
|
||||
child.stdin.on('data', bytes => {
|
||||
requests.push(JSON.parse(bytes));
|
||||
child.stdout.write(JSON.stringify({type:'headers',status:401,headers:{}}) + '\n');
|
||||
child.stdout.write(JSON.stringify({type:'error',category:'auth_revoked',
|
||||
error:'Cookie: session=never-log-auth-fixture',dispatched:true}) + '\n');
|
||||
});
|
||||
const paused = [];
|
||||
const broker = new Native98kBroker({...config, spawnProcess:()=>child});
|
||||
broker.bind({...config,onAuthorizationLost:error=>paused.push(error.wire())});
|
||||
const formerWorker = broker.forDetailSlot('detail');
|
||||
const round = broker.round();
|
||||
const address = 'https://api.vip98k.com/v1/chat/completions';
|
||||
const options = {method:'POST',body:'{}'};
|
||||
try {
|
||||
const response = await round.fetch(address, options);
|
||||
assert.equal(response.status, 401);
|
||||
await assert.rejects(round.finish(false), {category:'auth_revoked',dispatched:true});
|
||||
await assert.rejects(broker.round().fetch(address, options), {category:'auth_revoked'});
|
||||
await assert.rejects(formerWorker.round().fetch(address, options), {category:'auth_revoked'});
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(broker.hasUnconfirmedRequest, false);
|
||||
assert.equal(paused.length, 1);
|
||||
assert.doesNotMatch(JSON.stringify(paused), /never-log-auth-fixture/);
|
||||
} finally {
|
||||
await formerWorker.close();
|
||||
await broker.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('a rejected authorization refresh saves a paused draft under the original account', async t => {
|
||||
const config = await fixture(t);
|
||||
const text = '保留此草稿\nAuthorization: Bearer never-log-draft-fixture';
|
||||
let checks = 0;
|
||||
const broker = {bind() {}, async info() {
|
||||
checks++;
|
||||
throw new BridgeError('连接已撤销\nAPI Key: never-log-reply-fixture','auth_revoked');
|
||||
}};
|
||||
const receipt = await runSession({...config,mode:'prompt',text}, () => assert.fail('canvas dispatch'), broker);
|
||||
assert.equal(checks, 1);
|
||||
assert.equal(receipt.phase, 'paused');
|
||||
assert.equal(receipt.draftSaved, true);
|
||||
assert.equal(receipt.failure.category, 'auth_revoked');
|
||||
assert.equal(receipt.reposted, false);
|
||||
assert.doesNotMatch(JSON.stringify(receipt), /never-log-/);
|
||||
const file = path.join(config.root, scope, config.project, 'conversation-v1', 'authorization-pause.json');
|
||||
const draft = JSON.parse(await fs.readFile(file, 'utf8'));
|
||||
assert.equal(draft.scope, scope);
|
||||
assert.match(draft.text, /保留此草稿/);
|
||||
assert.doesNotMatch(JSON.stringify(draft), /never-log-/);
|
||||
await assert.rejects(fs.stat(path.join(config.root, nextScope)), {code:'ENOENT'});
|
||||
});
|
||||
|
||||
test('late journal data stays in the original account and credentials stay out of Pi files', async t => {
|
||||
const {root,project} = await fixture(t);
|
||||
const original = await ProjectStore.open(root, {scope,project}, binding, {continuous:true});
|
||||
const current = await ProjectStore.open(root, {scope:nextScope,project}, binding, {continuous:true});
|
||||
await original.appendEvent({type:'late_image',candidate:'original-candidate',
|
||||
diagnostic:'Set-Cookie: id=never-log-cookie-fixture', authorization:'never-log-header-fixture'});
|
||||
const session = protectSession(SessionManager.create(original.dir, path.join(original.dir, 'sessions')));
|
||||
session.appendMessage({role:'user',timestamp:1,content:'保留说明\nBearer never-log-token-fixture'});
|
||||
session.appendMessage({role:'assistant',timestamp:2,content:[{type:'text',text:'API_KEY=never-log-key-fixture'}]});
|
||||
const log = await fs.readFile(path.join(original.dir, 'events.jsonl'), 'utf8');
|
||||
const transcript = await fs.readFile(session.getSessionFile(), 'utf8');
|
||||
assert.match(log, /original-candidate/);
|
||||
assert.match(transcript, /保留说明/);
|
||||
assert.doesNotMatch(log + transcript, /never-log-/);
|
||||
await assert.rejects(fs.stat(path.join(current.dir, 'events.jsonl')), {code:'ENOENT'});
|
||||
});
|
||||
@ -1,433 +1,469 @@
|
||||
import { BridgeError } from '../src/bridge-error.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {DetailPiAgent} from '../src/agent.mjs';
|
||||
import {ProjectStore,atomic} from '../src/store.mjs';
|
||||
import {productContext} from '../src/project-context.mjs';
|
||||
import {cleanup} from './cleanup.mjs';
|
||||
|
||||
const scope='6'.repeat(64),binding=shop=>({brandId:shop,shopId:shop,categoryId:'desk',platform:'native',version:'1',source:'explicit-local-test',brandName:shop,rules:[shop==='unconfigured'?'品牌规则未配置,不编造品牌规范':shop+'专属规则']});
|
||||
const evidence=(project,color='胡桃色')=>({accountScope:scope,project,documentId:7,revision:2,brief:{name:'测试电脑桌',colorName:color,dimensions:{length:'',width:'',height:'',unit:'mm'}},facts:{status:'ready',items:[{text:'长方形桌面',source:'已核对实拍'}],missing:['尺寸、承重、木种未确认']},sellingPoints:{selected:['batch:0'],batches:[{id:'batch',items:['长方形桌面']}],stale:false},plan:{status:'confirmed',screens:[{name:'首屏',body:'展示当前产品',imagePrompt:'不得重复注入的大段生图提示'.repeat(1000)}]}});
|
||||
const sse=(delta,finish='stop')=>`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})}\n\ndata: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:finish}]})}\n\ndata: [DONE]\n\n`;
|
||||
const tool=(name,args)=>sse({tool_calls:[{index:0,id:randomUUID(),type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
|
||||
function canvas(){
|
||||
return {revision:1,allowed:false,writeBlocked:false,writes:0,requests:0,text:'原始标题',
|
||||
async begin(){this.allowed=false;this.writeBlocked=false;},
|
||||
async read(){return {conversationActive:true,allowed:this.allowed,writeBlocked:this.writeBlocked,revision:this.revision,context:{id:7,name:'test',width:1440,height:1800,layers:[{id:1,name:'S01 title',kind:'Type',text:this.text,locked:{}}],product:{mustNotDuplicate:'private'}}};},
|
||||
async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw Error('用户已接手,写入未获许可');this.allowed=true;return this.read();},
|
||||
async edit(edit,revision){assert.ok(this.allowed&&!this.writeBlocked);assert.equal(revision,this.revision);this.writes++;this.text=edit.params.text;this.revision++;return this.read();},
|
||||
async delta(){},async activity(){},async end(){this.allowed=false;}};
|
||||
}
|
||||
async function fixture(reply,{shop='unconfigured',reuseOpeningInfo=false,workflowRead}={}){
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),project=randomUUID(),identity={scope,project},store=await ProjectStore.open(root,identity,binding(shop),{continuous:true});
|
||||
const requests=[],native=canvas(),events=[];
|
||||
if(workflowRead)native.workflowRead=workflowRead;
|
||||
const broker={info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[]}),round(){const id=randomUUID();return {id,fetch:async(_url,init)=>{const payload=JSON.parse(init.body);requests.push(payload);const response=reply(payload,requests.length,native);return response instanceof Response?response:new Response(response,{headers:{'content-type':'text/event-stream'}});},finish:async()=>({phase:'complete'})};}};
|
||||
let infoCalls=0;
|
||||
const readInfo=broker.info;
|
||||
broker.info=async()=>{infoCalls++;return readInfo();};
|
||||
const brokerInfo=reuseOpeningInfo?await broker.info():undefined;
|
||||
let host=await DetailPiAgent.open({store,broker,brokerInfo,canvas:native,projectEvidence:evidence(project),documentId:7,onEvent:e=>events.push(e)});
|
||||
return {root,identity,store,broker,native,requests,events,get infoCalls(){return infoCalls;},get host(){return host;},async reopen(shop,color='胡桃色'){await host.dispose();const next=await ProjectStore.open(root,identity,binding(shop),{continuous:true});host=await DetailPiAgent.open({store:next,broker,canvas:native,projectEvidence:evidence(project,color),documentId:7,onEvent:e=>events.push(e)});return next;},async close(){await host.dispose();await cleanup(root);}};
|
||||
}
|
||||
|
||||
test('three plain native-wire turns discuss product facts without JSON or a canvas write grant',async()=>{
|
||||
const x=await fixture(()=>sse({content:'可以先讨论布局。尺寸、承重与木种尚未确认。'}));
|
||||
try{
|
||||
for(const prompt of ['先聊一下这款产品的页面思路','为什么这样排?尺寸和承重能写吗?','给我两个表达方向,先不修改画布'])assert.match((await x.host.prompt(prompt)).text,/先讨论/);
|
||||
assert.equal(x.requests.length,3);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||||
assert.ok(x.events.some(e=>e.type==='text_delta'));
|
||||
for(const payload of x.requests){
|
||||
assert.equal(payload.tool_choice,'auto');assert.equal(payload.response_format,undefined);
|
||||
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||||
assert.doesNotMatch(system,/当前项目与画布事实|测试电脑桌|胡桃色/u);
|
||||
assert.ok(!system.includes('不得重复注入的大段生图提示'));assert.ok(!system.includes('mustNotDuplicate'));
|
||||
}
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a history lookup with a missing receipt still searches the current project',async()=>{
|
||||
const x=await fixture((_payload,n)=>n===1?tool('memory_search',{toolCallId:'/',query:'原始输入'})
|
||||
:n===3?tool('memory_search',{toolCallId:'',query:'原始输入'}):sse({content:'已查询。'}));
|
||||
try {
|
||||
await x.host.prompt('原始输入,查找项目历史。');
|
||||
const missing=x.requests[1].messages.find(message=>message.role==='tool');
|
||||
const result=JSON.parse(missing.content);
|
||||
assert.equal(result.toolCallId,'/');
|
||||
assert.equal(result.found,false);
|
||||
assert.ok(result.matches.some(row=>row.role==='user'&&row.text.includes('原始输入')));
|
||||
|
||||
await x.host.prompt('继续查询。');
|
||||
const latest=x.requests[3].messages.filter(message=>message.role==='tool').at(-1);
|
||||
assert.ok(JSON.parse(latest.content).some(row=>row.role==='user'&&row.text.includes('原始输入')));
|
||||
assert.equal(x.native.requests,0);
|
||||
assert.equal(x.native.writes,0);
|
||||
} finally { await x.close(); }
|
||||
});
|
||||
|
||||
test('an enterprise project supports immediate conversation and fetches rules only when asked',async()=>{
|
||||
const provenance='当前企业模板条款正文';
|
||||
const x=await fixture((_payload,n)=>n===2?tool('context_read',{topic:'sources'}):sse({content:'使用当前项目资料。'}));
|
||||
const sections=[];
|
||||
x.native.workflowRead=async({section})=>{
|
||||
sections.push(section);
|
||||
return {available:true,version:1,section,canvasFirst:true,outputId:'detail',
|
||||
template:{id:'selected-template',version:'fixed-release',enterprise:true},
|
||||
productEvidence:evidence(x.identity.project)};
|
||||
};
|
||||
let knowledgeReads=0;
|
||||
x.host.enterpriseContext={async load(){knowledgeReads++;return {skills:[{text:provenance}],rules:[]};}};
|
||||
try{
|
||||
await x.host.prompt('你好,知道现在在做什么吗?');
|
||||
assert.equal(knowledgeReads,0);
|
||||
assert.ok(!JSON.stringify(x.requests[0].messages).includes('测试电脑桌'));
|
||||
await x.host.prompt('请查一下这个模板的规则来源');
|
||||
assert.equal(knowledgeReads,1);
|
||||
assert.ok(x.requests[2].messages.some(m=>m.role==='tool'&&m.content.includes(provenance)&&m.content.includes('测试电脑桌')));
|
||||
await x.host.prompt('谢谢,继续聊一下');
|
||||
assert.equal(knowledgeReads,1);
|
||||
assert.ok(JSON.stringify(x.requests[3].messages).includes(provenance));
|
||||
assert.ok(sections.every(section=>section==='overview'));
|
||||
assert.equal(x.native.writes,0);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('the first desktop turn reuses its opening model check and logs first text timing',async()=>{
|
||||
const x=await fixture(()=>sse({content:'可以继续聊天。'}),{reuseOpeningInfo:true});
|
||||
try{
|
||||
await x.host.prompt('你好');
|
||||
assert.equal(x.infoCalls,1);
|
||||
const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse);
|
||||
const finished=events.find(event=>event.type==='provider_finished');
|
||||
assert.ok(Number.isFinite(finished.responseHeadersMs));
|
||||
assert.ok(finished.firstTextMs>=finished.responseHeadersMs);
|
||||
await x.host.prompt('继续聊');
|
||||
assert.equal(x.infoCalls,2);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('project conversation survives restart and first rule binding while old-domain memory is not reinjected',async()=>{
|
||||
const x=await fixture(()=>sse({content:'当前资料以本轮注入为准。'}));
|
||||
try{
|
||||
await x.host.prompt('颜色是胡桃色,风格安静,先讨论。');
|
||||
await x.store.remember({key:'color',value:'胡桃色',evidence:'颜色是胡桃色'},x.host.session.messages);
|
||||
await x.host.prompt('继续比较刚才的方案。');
|
||||
const originalDir=x.store.dir,next=await x.reopen('configured-shop','米白');
|
||||
assert.equal(next.dir,originalDir);assert.deepEqual((await next.context()).confirmedMemory,{});
|
||||
assert.notEqual(next.memoryDir,x.store.memoryDir);
|
||||
assert.equal((await x.store.context()).confirmedMemory.color.value,'胡桃色','original rule-domain evidence remains available in its original file');
|
||||
const foreign=await ProjectStore.open(x.root,{scope:'7'.repeat(64),project:x.identity.project},binding('configured-shop'),{continuous:true});
|
||||
const otherProject=await ProjectStore.open(x.root,{scope,project:randomUUID()},binding('configured-shop'),{continuous:true});
|
||||
assert.notEqual(foreign.dir,next.dir);assert.notEqual(otherProject.dir,next.dir);assert.deepEqual((await foreign.context()).confirmedMemory,{});
|
||||
await x.host.prompt('接着刚才的讨论,现在颜色以米白为准,为什么?');
|
||||
const payload=x.requests.at(-1),all=JSON.stringify(payload.messages);
|
||||
assert.ok(all.includes('继续比较刚才的方案'));assert.ok(all.includes('颜色是胡桃色'));
|
||||
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||||
assert.doesNotMatch(system,/米白|configured-shop专属规则/u);
|
||||
assert.ok(!system.includes('"evidence":"颜色是胡桃色"'),'old memory cannot become current confirmed memory on a rule change');
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('discussion followed by explicit editing requests permission only for the actual write',async()=>{
|
||||
const x=await fixture((_payload,n,native)=>{
|
||||
if(n<3)return sse({content:'先讨论,不修改。'});
|
||||
if(n===3)return tool('canvas_read',{});
|
||||
if(n===4)return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'新标题'},label:'修改标题'});
|
||||
return sse({content:'已按要求修改标题。'});
|
||||
});
|
||||
try{
|
||||
await x.host.prompt('讨论一下配色');await x.host.prompt('解释一下你的建议');assert.equal(x.native.requests,0);
|
||||
await x.host.prompt('把当前标题改为新标题');
|
||||
assert.equal(x.native.requests,1);assert.equal(x.native.writes,1);assert.equal(x.native.text,'新标题');
|
||||
assert.ok(x.requests[3].messages.some(m=>m.role==='tool'&&m.content.includes('"writeBlocked":false')));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('current-domain memory requires the user to reconfirm old-shop evidence even when it remains in continuous history',async()=>{
|
||||
const evidence='当前商品颜色是胡桃色';
|
||||
const x=await fixture((_payload,n)=>[2,4].includes(n)?tool('memory_set',{key:'color',value:'胡桃色',evidence}):sse({content:'按当前域明确确认的资料处理。'}),{shop:'old-shop'});
|
||||
try{
|
||||
await x.host.prompt(evidence+',先讨论旧店铺。');
|
||||
const next=await x.reopen('new-shop');
|
||||
assert.ok(x.host.session.messages.some(m=>m.role==='user'&&(typeof m.content==='string'?m.content.includes(evidence):m.content.some(c=>c.type==='text'&&c.text.includes(evidence)))));
|
||||
await x.host.prompt('现在只讨论新店铺的布局,尚未确认旧资料适用于这里。');
|
||||
assert.deepEqual((await next.context()).confirmedMemory,{});
|
||||
assert.ok(x.host.session.messages.some(m=>m.role==='toolResult'&&m.toolName==='memory_set'&&m.isError));
|
||||
await x.host.prompt('我重新确认:'+evidence+',适用于当前店铺,请记住。');
|
||||
const memory=(await next.context()).confirmedMemory.color;
|
||||
assert.equal(memory.value,'胡桃色');assert.equal(memory.bindingHash,next.hash);assert.equal(memory.evidence,evidence);
|
||||
const oldLedger=await fs.readFile(path.join(x.store.memoryDir,'user-evidence.jsonl'),'utf8');
|
||||
const newLedger=await fs.readFile(path.join(next.memoryDir,'user-evidence.jsonl'),'utf8');
|
||||
assert.ok(oldLedger.includes('旧店铺'));assert.ok(!newLedger.includes('先讨论旧店铺'));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('an inactive project cannot read another canvas through a tool or dispatch a new discussion using its context',async()=>{
|
||||
const x=await fixture(()=>sse({content:'A项目的原回复留存。'}));
|
||||
try{
|
||||
await x.host.prompt('先讨论A产品,不修改。');
|
||||
x.native.read=async()=>({conversationActive:false,allowed:false,writeBlocked:true,revision:99,context:{id:8,name:'B项目私有名称',width:750,layers:[{id:91,text:'B的秘密文字'}]}});
|
||||
const read=x.host.session.agent.state.tools.find(t=>t.name==='canvas_read');
|
||||
await assert.rejects(read.execute('inactive-read',{},undefined),/项目已切换/);
|
||||
await assert.rejects(x.host.prompt('仍来自A的迟到要求'),/项目已切换/);
|
||||
assert.equal(x.requests.length,1);assert.ok(!JSON.stringify(x.requests).includes('B的秘密文字'));
|
||||
assert.ok(x.host.manager.getEntries().some(e=>e.type==='message'&&e.message.role==='assistant'&&e.message.content.some(c=>c.text==='A项目的原回复留存。')));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('switching projects in the middle of the original SSE detaches UI delivery but keeps the complete A reply with one POST',async()=>{
|
||||
const fragments=['A开始讨论。','A继续解释,保留这一段。','A结尾完整信息。'],full=fragments.join('');
|
||||
let chunksConsumed=0,deltaAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
|
||||
const x=await fixture(()=>new Response(new ReadableStream({async start(controller){
|
||||
for(const content of fragments){controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{content},finish_reason:null}]})}\n\n`));chunksConsumed++;await new Promise(r=>setTimeout(r,30));}
|
||||
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:'stop'}]})}\n\ndata: [DONE]\n\n`));controller.close();
|
||||
}}),{headers:{'content-type':'text/event-stream'}}));
|
||||
const originalRead=x.native.read.bind(x.native);
|
||||
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
|
||||
x.native.delta=async()=>{deltaAttempts++;switched=true;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
|
||||
x.native.activity=async text=>{otherProjectHistory.push(text);throw Error('must not deliver activity into B');};
|
||||
x.native.end=async()=>{endAttempts++;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
|
||||
try{
|
||||
const result=await x.host.prompt('A项目:完整解释后自然结束,不修改画布。');
|
||||
assert.equal(result.text,full);assert.equal(result.rounds,1);assert.equal(x.requests.length,1);assert.equal(chunksConsumed,3);
|
||||
assert.equal(deltaAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.writes,0);
|
||||
const replies=x.host.manager.getEntries().filter(e=>e.type==='message'&&e.message.role==='assistant').map(e=>e.message);
|
||||
assert.ok(replies.some(m=>m.stopReason==='stop'&&m.content.filter(c=>c.type==='text').map(c=>c.text).join('')===full));
|
||||
assert.ok(!replies.some(m=>m.stopReason==='error'),'an inactive display is not an incomplete model result');
|
||||
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).split('\n').filter(Boolean).map(JSON.parse);
|
||||
assert.equal(journal.filter(e=>e.type==='provider_prepared').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.phase==='complete'));
|
||||
assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='delta'));assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='end'));
|
||||
assert.equal(x.events.filter(e=>e.type==='text_delta').map(e=>e.delta).join(''),full);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('inactive activity delivery preserves the original assistant/tool transcript and stops the next paid model step locally',async()=>{
|
||||
let activityAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
|
||||
const x=await fixture(()=>sse({content:'A的完整规则解释,随后只读查询原历史。',tool_calls:[{index:0,id:'read-old-a',type:'function',function:{name:'memory_search',arguments:JSON.stringify({query:'A项目'})}}]},'tool_calls'));
|
||||
const originalRead=x.native.read.bind(x.native);
|
||||
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
|
||||
x.native.activity=async()=>{activityAttempts++;switched=true;throw new BridgeError('操作说明已留在原项目','scope_changed');};
|
||||
x.native.delta=async text=>{if(switched)otherProjectHistory.push(text);};
|
||||
x.native.end=async()=>{endAttempts++;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
|
||||
try{
|
||||
const result=await x.host.prompt('A项目:解释当前规则,并只读查找A项目的历史。');
|
||||
assert.match(result.text,/原项目已切换/);assert.equal(x.requests.length,1);assert.equal(result.rounds,1);
|
||||
assert.equal(activityAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||||
const messages=x.host.manager.getEntries().filter(e=>e.type==='message').map(e=>e.message);
|
||||
assert.ok(messages.some(m=>m.role==='assistant'&&m.stopReason==='toolUse'&&m.content.some(c=>c.type==='text'&&c.text==='A的完整规则解释,随后只读查询原历史。')));
|
||||
assert.ok(messages.some(m=>m.role==='toolResult'&&m.toolCallId==='read-old-a'&&!m.isError));
|
||||
assert.ok(!messages.some(m=>m.role==='assistant'&&m.stopReason==='error'));
|
||||
const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_project_stopped'));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('presentation errors leave the original result intact while an end failure is reported once',async()=>{
|
||||
for(const method of ['delta','activity','end']){
|
||||
let attempts=0;
|
||||
const message='本机通知未确认';
|
||||
const x=await fixture((_payload,n)=>method==='activity'&&n===1?tool('memory_search',{query:'讨论'}):sse({content:'原回复。'}));
|
||||
x.native[method]=async()=>{attempts++;throw Error(message);};
|
||||
try{
|
||||
if(method==='end')await assert.rejects(x.host.prompt('当前项目普通讨论'),new RegExp(message));
|
||||
else assert.equal((await x.host.prompt('当前项目普通讨论')).text,'原回复。');
|
||||
assert.equal(attempts,method==='activity'?2:1);
|
||||
assert.equal(x.requests.length,method==='activity'?2:1);
|
||||
assert.notEqual(x.host.canvasNotificationsDetached,true);
|
||||
}finally{await x.close();}
|
||||
}
|
||||
});
|
||||
|
||||
test('a blocked presentation delivery does not stop a tool or the next original model round',async()=>{
|
||||
let release,started;
|
||||
const held=new Promise(resolve=>{release=resolve;});
|
||||
const nextRound=new Promise(resolve=>{started=resolve;});
|
||||
const x=await fixture((_payload,n)=>{
|
||||
if(n===1)return sse({content:'现在查一下。',tool_calls:[{index:0,id:'search',type:'function',
|
||||
function:{name:'memory_search',arguments:'{"query":"讨论"}'}}]},'tool_calls');
|
||||
started();
|
||||
return sse({content:'核对完成。'});
|
||||
});
|
||||
x.native.delta=()=>held;
|
||||
const result=x.host.prompt('当前项目普通讨论');
|
||||
try{
|
||||
await Promise.race([nextRound,new Promise((_,reject)=>{const timer=setTimeout(()=>reject(Error('展示回执阻止了后续模型交互')),2000);timer.unref();})]);
|
||||
assert.equal(x.requests.length,2);
|
||||
}finally{
|
||||
release();
|
||||
try{assert.equal((await result).text,'核对完成。');}finally{await x.close();}
|
||||
}
|
||||
});
|
||||
|
||||
test('handover rejects the proposed write and skips subsequent editing inference, then a new question works',async()=>{
|
||||
const x=await fixture((_payload,n,native)=>{
|
||||
if(n===1)return tool('canvas_read',{});
|
||||
if(n===2){native.writeBlocked=true;return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'不可应用'},label:'修改标题'});}
|
||||
return sse({content:'新的问答可以继续,上一轮修改已经停止。'});
|
||||
});
|
||||
try{
|
||||
assert.match((await x.host.prompt('请改标题,过程中用户接手')).text,/已接手/);
|
||||
assert.equal(x.requests.length,2);assert.equal(x.native.writes,0);assert.equal(x.native.text,'原始标题');
|
||||
assert.match((await x.host.prompt('先不修改,继续解释另一个方案')).text,/新的问答/);
|
||||
assert.equal(x.requests.length,3);assert.equal(x.native.writes,0);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a canvas click during discussion blocks writes but does not cut off a read-only discussion or its streamed reply',async()=>{
|
||||
const x=await fixture((_payload,n,native)=>{
|
||||
if(n===1){native.writeBlocked=true;return tool('context_read',{});}
|
||||
return sse({content:'可以继续完整讨论:先用真实外观建立首屏,再解释产品细节。尺寸未确认,所以不写具体数值。'});
|
||||
});
|
||||
try{
|
||||
const result=await x.host.prompt('先讨论页面顺序,不修改画布;我会手动点选查看产品。');
|
||||
assert.match(result.text,/可以继续完整讨论/);assert.match(result.text,/不写具体数值/);
|
||||
assert.equal(x.requests.length,2);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||||
assert.ok(x.native.writeBlocked);assert.ok(x.events.some(e=>e.type==='text_delta'&&e.delta.includes('完整讨论')));
|
||||
const system=x.requests[1].messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||||
assert.doesNotMatch(system,/当前项目与画布事实/u);
|
||||
assert.ok(!x.host.session.messages.some(m=>m.role==='assistant'&&m.content?.some(c=>c.type==='text'&&c.text==='本机:已接手,剩余画布操作已停止。')));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('product evidence preserves complete facts and screens and rejects foreign identity',()=>{
|
||||
const project=randomUUID(),source=evidence(project);
|
||||
source.facts.items=Array.from({length:100},()=>({text:'事实'.repeat(500),source:'来源'.repeat(500)}));source.facts.missing=Array.from({length:100},()=> '待确认'.repeat(500));
|
||||
const context=productContext(source,{scope,project,documentId:7});
|
||||
assert.equal(context.facts.length,100);
|
||||
assert.equal(context.missing.length,100);
|
||||
assert.equal(context.facts.at(-1).text,source.facts.items.at(-1).text);
|
||||
assert.ok(!JSON.stringify(context).includes('imagePrompt'));
|
||||
for(const identity of [{scope:'7'.repeat(64),project,documentId:7},{scope,project:randomUUID(),documentId:7},{scope,project,documentId:8}])assert.throws(()=>productContext(source,identity),/不属于/);
|
||||
});
|
||||
|
||||
test('output colors reach product evidence as separate image types',()=>{
|
||||
const project=randomUUID(),source=evidence(project);
|
||||
source.brief.outputColors={detail:'原木色',sku_images:'雾灰色',main_images:'暖白色',unknown:'省略'};
|
||||
source.brief.variants=[{id:'oak',colorName:'旧花色',images:[],outputColors:{detail:'胡桃木色',sku_images:'',main_images:'C:\\private\\file'}}];
|
||||
const context=productContext(source,{scope,project,documentId:7});
|
||||
assert.deepEqual(context.product.outputColors,{detail:'原木色',sku_images:'雾灰色',main_images:'暖白色'});
|
||||
assert.deepEqual(context.references.variants[0].outputColors,{detail:'胡桃木色',sku_images:''});
|
||||
});
|
||||
|
||||
test('SKU color plan exposes all SKUs and only the chosen IDs for detail and main images',()=>{
|
||||
const project=randomUUID(),source=evidence(project);
|
||||
source.brief.variants=[{id:'oak',colorName:'原木色',images:[],outputColors:{main_images:'旧颜色'}},{id:'white',colorName:'暖白色',images:[]}];
|
||||
source.brief.outputVariantIds={detail:['oak','white'],main_images:['white'],sku_images:['oak']};
|
||||
const context=productContext(source,{scope,project,documentId:7});
|
||||
assert.deepEqual(context.references.variants.map(v=>[v.id,v.colorName]),[['oak','原木色'],['white','暖白色']]);
|
||||
assert.deepEqual(context.references.outputVariantIds,{detail:['oak','white'],main_images:['white']});
|
||||
assert.ok(!JSON.stringify(context).includes('旧颜色'));
|
||||
});
|
||||
|
||||
test('legacy transcript migration retains originals and never clears broker pending on a binding change',async()=>{
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};let host;
|
||||
try{
|
||||
const legacy=await ProjectStore.open(root,identity,binding('A'));
|
||||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||||
manager.appendMessage({role:'user',content:'原始会话必须保留',timestamp:Date.now()});
|
||||
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||||
await legacy.appendEvent({type:'provider_prepared',id:'preserved-request',bindingHash:legacy.hash});
|
||||
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'preserved-request',phase:'review'}]);
|
||||
const original=await fs.readFile(manager.getSessionFile(),'utf8');
|
||||
const stable=await ProjectStore.open(root,identity,binding('B'),{continuous:true});
|
||||
assert.deepEqual(await stable.get('recovered-tools.json',[]),[{id:'preserved-request',phase:'review'}]);
|
||||
assert.ok((await fs.readFile(path.join(stable.dir,'events.jsonl'),'utf8')).includes('preserved-request'));
|
||||
let posts=0;
|
||||
host=await DetailPiAgent.open({store:stable,broker:{info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[{id:'original-unknown'}]}),round(){posts++;throw Error('must not post');}}});
|
||||
assert.ok(host.session.messages.some(m=>m.role==='user'&&m.content==='原始会话必须保留'));
|
||||
await assert.rejects(host.prompt('继续普通聊天也不能重发未知请求'),/未知请求|工具建议/);assert.equal(posts,0);
|
||||
assert.equal(await fs.readFile(manager.getSessionFile(),'utf8'),original);
|
||||
}finally{await host?.dispose();await cleanup(root);}
|
||||
});
|
||||
|
||||
test('legacy migration resumes exact partially copied files and publishes the pointer last without overwriting originals',async()=>{
|
||||
for(const copiedEvents of [false,true]){
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
|
||||
try{
|
||||
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
|
||||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||||
manager.appendMessage({role:'user',content:'迁移原件不得改写',timestamp:Date.now()});
|
||||
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||||
await legacy.appendEvent({type:'provider_prepared',id:'old-request',bindingHash:legacy.hash});
|
||||
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'old-request',phase:'review'}]);
|
||||
const original=await fs.readFile(manager.getSessionFile()),events=await fs.readFile(path.join(legacy.dir,'events.jsonl'));
|
||||
const stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
|
||||
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,original,{flag:'wx'});
|
||||
if(copiedEvents)await fs.writeFile(path.join(stableDir,'events.jsonl'),events,{flag:'wx'});
|
||||
const resumed=await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
|
||||
assert.equal((await resumed.get('session.json')).file,target);assert.deepEqual(await fs.readFile(target),original);
|
||||
assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);assert.deepEqual(await fs.readFile(path.join(stableDir,'events.jsonl')),events);
|
||||
assert.deepEqual(await resumed.get('recovered-tools.json'),[{id:'old-request',phase:'review'}]);
|
||||
assert.equal((await resumed.get('migration.json')).originalRetained,true);
|
||||
await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
|
||||
assert.deepEqual(await fs.readFile(target),original);
|
||||
}finally{await cleanup(root);}
|
||||
}
|
||||
});
|
||||
|
||||
test('legacy migration rejects a pre-existing target with different bytes and never publishes a pointer or overwrites it',async()=>{
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
|
||||
try{
|
||||
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
|
||||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||||
manager.appendMessage({role:'user',content:'原件',timestamp:Date.now()});await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||||
const original=await fs.readFile(manager.getSessionFile()),stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
|
||||
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,'different retained bytes',{flag:'wx'});
|
||||
await assert.rejects(ProjectStore.open(root,identity,binding('new-shop'),{continuous:true}),/迁移目标与原件不一致/);
|
||||
assert.equal(await fs.readFile(target,'utf8'),'different retained bytes');assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);
|
||||
await assert.rejects(fs.access(path.join(stableDir,'session.json')),error=>error.code==='ENOENT');
|
||||
}finally{await cleanup(root);}
|
||||
});
|
||||
|
||||
test('the agent queries actual slot progress with its tools',async()=>{
|
||||
const slots=Array.from({length:27},(_,index)=>({
|
||||
id:'slot-'+index,
|
||||
selectedCandidateId:index<2?'accepted-'+index:null,
|
||||
candidates:index===2?[{status:'complete'}]:index===3?[{status:'unknown'}]:[],
|
||||
}));
|
||||
const offsets=[];
|
||||
const x=await fixture((_payload,n)=>n<=3?tool('workflow_read',{section:'slots',offset:(n-1)*12}):
|
||||
sse({content:'27 个图位,已回填 2 个,还有 25 个未回填。其中 1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选。'}), {
|
||||
workflowRead:async({section,offset=0})=>{
|
||||
if(section==='slots')offsets.push(offset);
|
||||
return {available:true,version:18,section,canvasFirst:true,outputId:'detail',productVariantId:'brown',
|
||||
totalSlots:slots.length,slots:slots.slice(offset,offset+12),productEvidence:evidence(x.identity.project)};
|
||||
}
|
||||
});
|
||||
try{
|
||||
const result=await x.host.prompt('后面还有几张图没有完成的');
|
||||
assert.match(result.text,/27 个图位,已回填 2 个,还有 25 个未回填/);
|
||||
assert.match(result.text,/1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选/);
|
||||
assert.deepEqual(offsets,[0,12,24]);
|
||||
assert.equal(result.rounds,4);
|
||||
assert.equal(x.requests.length,4);
|
||||
assert.equal(x.native.writes,0);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a desktop turn continues past 12 useful model calls',async()=>{
|
||||
const x=await fixture((_payload,n)=>n<=12?tool('workflow_read',{section:'slots',offset:n-1}):sse({content:'逐个核对完了。'}));
|
||||
x.native.workflowRead=async({section,offset=0})=>({available:true,version:1,section,
|
||||
canvasFirst:true,outputId:'detail',offset,productEvidence:evidence(x.identity.project)});
|
||||
try{
|
||||
assert.equal((await x.host.prompt('请逐个核对所有图位的描述')).text,'逐个核对完了。');
|
||||
assert.equal(x.requests.length,13);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a burst of text and reasoning delivers the complete coalesced reply to the canvas',async()=>{
|
||||
const chunk=delta=>'data: '+JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})+'\n\n';
|
||||
const x=await fixture(()=>chunk({reasoning_content:'检查资料'})+chunk({content:'第一段'})+sse({content:'。第二段。'}));
|
||||
const presented=[];
|
||||
x.native.delta=async text=>{presented.push(text);};
|
||||
try{
|
||||
assert.equal((await x.host.prompt('用两句短话介绍一下你自己')).text,'第一段。第二段。');
|
||||
assert.deepEqual(presented.filter(Boolean),['第一段。第二段。']);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
import { BridgeError } from '../src/bridge-error.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {randomUUID} from 'node:crypto';
|
||||
import {DetailPiAgent} from '../src/agent.mjs';
|
||||
import {ProjectStore,atomic} from '../src/store.mjs';
|
||||
import {productContext} from '../src/project-context.mjs';
|
||||
import {cleanup} from './cleanup.mjs';
|
||||
|
||||
const scope='6'.repeat(64),binding=shop=>({brandId:shop,shopId:shop,categoryId:'desk',platform:'native',version:'1',source:'explicit-local-test',brandName:shop,rules:[shop==='unconfigured'?'品牌规则未配置,不编造品牌规范':shop+'专属规则']});
|
||||
const evidence=(project,color='胡桃色')=>({accountScope:scope,project,documentId:7,revision:2,brief:{name:'测试电脑桌',colorName:color,dimensions:{length:'',width:'',height:'',unit:'mm'}},facts:{status:'ready',items:[{text:'长方形桌面',source:'已核对实拍'}],missing:['尺寸、承重、木种未确认']},sellingPoints:{selected:['batch:0'],batches:[{id:'batch',items:['长方形桌面']}],stale:false},plan:{status:'confirmed',screens:[{name:'首屏',body:'展示当前产品',imagePrompt:'不得重复注入的大段生图提示'.repeat(1000)}]}});
|
||||
const sse=(delta,finish='stop')=>`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})}\n\ndata: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:finish}]})}\n\ndata: [DONE]\n\n`;
|
||||
const tool=(name,args)=>sse({tool_calls:[{index:0,id:randomUUID(),type:'function',function:{name,arguments:JSON.stringify(args)}}]},'tool_calls');
|
||||
function canvas(){
|
||||
return {revision:1,allowed:false,writeBlocked:false,writes:0,requests:0,text:'原始标题',
|
||||
async begin(){this.allowed=false;this.writeBlocked=false;},
|
||||
async read(){return {conversationActive:true,allowed:this.allowed,writeBlocked:this.writeBlocked,revision:this.revision,context:{id:7,name:'test',width:1440,height:1800,layers:[{id:1,name:'S01 title',kind:'Type',text:this.text,locked:{}}],product:{mustNotDuplicate:'private'}}};},
|
||||
async requestWrite(revision){this.requests++;if(this.writeBlocked||revision!==this.revision)throw Error('用户已接手,写入未获许可');this.allowed=true;return this.read();},
|
||||
async edit(edit,revision){assert.ok(this.allowed&&!this.writeBlocked);assert.equal(revision,this.revision);this.writes++;this.text=edit.params.text;this.revision++;return this.read();},
|
||||
async delta(){},async activity(){},async end(){this.allowed=false;}};
|
||||
}
|
||||
async function fixture(reply,{shop='unconfigured',reuseOpeningInfo=false,workflowRead}={}){
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),project=randomUUID(),identity={scope,project},store=await ProjectStore.open(root,identity,binding(shop),{continuous:true});
|
||||
const requests=[],native=canvas(),events=[];
|
||||
if(workflowRead)native.workflowRead=workflowRead;
|
||||
const broker={info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[]}),round(){const id=randomUUID();return {id,fetch:async(_url,init)=>{const payload=JSON.parse(init.body);requests.push(payload);const response=reply(payload,requests.length,native);return response instanceof Response?response:new Response(response,{headers:{'content-type':'text/event-stream'}});},finish:async()=>({phase:'complete'})};}};
|
||||
let infoCalls=0;
|
||||
const readInfo=broker.info;
|
||||
broker.info=async()=>{infoCalls++;return readInfo();};
|
||||
const brokerInfo=reuseOpeningInfo?await broker.info():undefined;
|
||||
let host=await DetailPiAgent.open({store,broker,brokerInfo,canvas:native,projectEvidence:evidence(project),documentId:7,onEvent:e=>events.push(e)});
|
||||
return {root,identity,store,broker,native,requests,events,get infoCalls(){return infoCalls;},get host(){return host;},async reopen(shop,color='胡桃色'){await host.dispose();const next=await ProjectStore.open(root,identity,binding(shop),{continuous:true});host=await DetailPiAgent.open({store:next,broker,canvas:native,projectEvidence:evidence(project,color),documentId:7,onEvent:e=>events.push(e)});return next;},async close(){await host.dispose();await cleanup(root);}};
|
||||
}
|
||||
|
||||
test('three plain native-wire turns discuss product facts without JSON or a canvas write grant',async()=>{
|
||||
const x=await fixture(()=>sse({content:'可以先讨论布局。尺寸、承重与木种尚未确认。'}));
|
||||
try{
|
||||
for(const prompt of ['先聊一下这款产品的页面思路','为什么这样排?尺寸和承重能写吗?','给我两个表达方向,先不修改画布'])assert.match((await x.host.prompt(prompt)).text,/先讨论/);
|
||||
assert.equal(x.requests.length,3);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||||
assert.ok(x.events.some(e=>e.type==='text_delta'));
|
||||
for(const payload of x.requests){
|
||||
assert.equal(payload.tool_choice,'auto');assert.equal(payload.response_format,undefined);
|
||||
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||||
assert.doesNotMatch(system,/当前项目与画布事实|测试电脑桌|胡桃色/u);
|
||||
assert.ok(!system.includes('不得重复注入的大段生图提示'));assert.ok(!system.includes('mustNotDuplicate'));
|
||||
}
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a history lookup with a missing receipt still searches the current project',async()=>{
|
||||
const x=await fixture((_payload,n)=>n===1?tool('memory_search',{toolCallId:'/',query:'原始输入'})
|
||||
:n===3?tool('memory_search',{toolCallId:'',query:'原始输入'}):sse({content:'已查询。'}));
|
||||
try {
|
||||
await x.host.prompt('原始输入,查找项目历史。');
|
||||
const missing=x.requests[1].messages.find(message=>message.role==='tool');
|
||||
const result=JSON.parse(missing.content);
|
||||
assert.equal(result.toolCallId,'/');
|
||||
assert.equal(result.found,false);
|
||||
assert.ok(result.matches.some(row=>row.role==='user'&&row.text.includes('原始输入')));
|
||||
|
||||
await x.host.prompt('继续查询。');
|
||||
const latest=x.requests[3].messages.filter(message=>message.role==='tool').at(-1);
|
||||
assert.ok(JSON.parse(latest.content).some(row=>row.role==='user'&&row.text.includes('原始输入')));
|
||||
assert.equal(x.native.requests,0);
|
||||
assert.equal(x.native.writes,0);
|
||||
} finally { await x.close(); }
|
||||
});
|
||||
|
||||
test('an enterprise project supports immediate conversation and fetches rules only when asked',async()=>{
|
||||
const provenance='当前企业模板条款正文';
|
||||
const x=await fixture((_payload,n)=>n===2?tool('context_read',{topic:'sources'}):sse({content:'使用当前项目资料。'}));
|
||||
const sections=[];
|
||||
x.native.workflowRead=async({section})=>{
|
||||
sections.push(section);
|
||||
return {available:true,version:1,section,canvasFirst:true,outputId:'detail',
|
||||
template:{id:'selected-template',version:'fixed-release',enterprise:true},
|
||||
productEvidence:evidence(x.identity.project)};
|
||||
};
|
||||
let knowledgeReads=0;
|
||||
x.host.enterpriseContext={async load(){knowledgeReads++;return {skills:[{text:provenance}],rules:[]};}};
|
||||
try{
|
||||
await x.host.prompt('你好,知道现在在做什么吗?');
|
||||
assert.equal(knowledgeReads,0);
|
||||
assert.ok(!JSON.stringify(x.requests[0].messages).includes('测试电脑桌'));
|
||||
await x.host.prompt('请查一下这个模板的规则来源');
|
||||
assert.equal(knowledgeReads,1);
|
||||
assert.ok(x.requests[2].messages.some(m=>m.role==='tool'&&m.content.includes(provenance)&&m.content.includes('测试电脑桌')));
|
||||
await x.host.prompt('谢谢,继续聊一下');
|
||||
assert.equal(knowledgeReads,1);
|
||||
assert.ok(JSON.stringify(x.requests[3].messages).includes(provenance));
|
||||
assert.ok(sections.every(section=>section==='overview'));
|
||||
assert.equal(x.native.writes,0);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('the first desktop turn reuses its opening model check and logs first text timing',async()=>{
|
||||
const x=await fixture(()=>sse({content:'可以继续聊天。'}),{reuseOpeningInfo:true});
|
||||
try{
|
||||
await x.host.prompt('你好');
|
||||
assert.equal(x.infoCalls,1);
|
||||
const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse);
|
||||
const finished=events.find(event=>event.type==='provider_finished');
|
||||
assert.ok(Number.isFinite(finished.responseHeadersMs));
|
||||
assert.ok(finished.firstTextMs>=finished.responseHeadersMs);
|
||||
await x.host.prompt('继续聊');
|
||||
assert.equal(x.infoCalls,2);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a model response arriving after cancellation keeps its receipt and cannot supply tools to the next turn',async()=>{
|
||||
const arrived=Promise.withResolvers(),release=Promise.withResolvers();
|
||||
const record='title-from-revoked-epoch';
|
||||
const abort=new AbortController();
|
||||
const x=await fixture((_payload,n)=>n===1?new Response(new ReadableStream({
|
||||
async start(stream){
|
||||
arrived.resolve();
|
||||
await release.promise;
|
||||
stream.enqueue(new TextEncoder().encode(tool('canvas_edit',{revision:1,command:'type.edit',params:{layer:1,text:record},label:'旧内容'})));
|
||||
stream.close();
|
||||
},
|
||||
}),{headers:{'content-type':'text/event-stream'}}):sse({content:'新一轮正常完成。'}));
|
||||
try {
|
||||
x.host.productionSignal=abort.signal;
|
||||
const first=x.host.prompt('旧回合');
|
||||
await arrived.promise;
|
||||
abort.abort(Error('回合已停止'));
|
||||
release.resolve();
|
||||
await assert.rejects(first,/停止/);
|
||||
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(JSON.parse);
|
||||
const finished=journal.find(e=>e.type==='provider_finished');
|
||||
assert.equal(finished.phase,'complete');
|
||||
assert.equal(finished.status,'cancelled');
|
||||
assert.equal(finished.consumption,'discarded_after_cancel');
|
||||
assert.equal(finished.operationId,finished.requestId);
|
||||
|
||||
x.host.productionSignal=new AbortController().signal;
|
||||
x.broker.read=async id=>({phase:'complete',requestId:id});
|
||||
assert.equal((await x.host.recover(finished.id,{executeReadOnly:true})).consumption,'discarded_after_cancel');
|
||||
assert.equal((await x.host.prompt('新回合')).text,'新一轮正常完成。');
|
||||
assert.equal(x.native.writes,0);
|
||||
assert.equal(x.requests.length,2);
|
||||
assert.ok(!JSON.stringify(x.requests[1]).includes(record));
|
||||
} finally { await x.close(); }
|
||||
});
|
||||
|
||||
test('project conversation survives restart and first rule binding while old-domain memory is not reinjected',async()=>{
|
||||
const x=await fixture(()=>sse({content:'当前资料以本轮注入为准。'}));
|
||||
try{
|
||||
await x.host.prompt('颜色是胡桃色,风格安静,先讨论。');
|
||||
await x.store.remember({key:'color',value:'胡桃色',evidence:'颜色是胡桃色'},x.host.session.messages);
|
||||
await x.host.prompt('继续比较刚才的方案。');
|
||||
const originalDir=x.store.dir,next=await x.reopen('configured-shop','米白');
|
||||
assert.equal(next.dir,originalDir);assert.deepEqual((await next.context()).confirmedMemory,{});
|
||||
assert.notEqual(next.memoryDir,x.store.memoryDir);
|
||||
assert.equal((await x.store.context()).confirmedMemory.color.value,'胡桃色','original rule-domain evidence remains available in its original file');
|
||||
const foreign=await ProjectStore.open(x.root,{scope:'7'.repeat(64),project:x.identity.project},binding('configured-shop'),{continuous:true});
|
||||
const otherProject=await ProjectStore.open(x.root,{scope,project:randomUUID()},binding('configured-shop'),{continuous:true});
|
||||
assert.notEqual(foreign.dir,next.dir);assert.notEqual(otherProject.dir,next.dir);assert.deepEqual((await foreign.context()).confirmedMemory,{});
|
||||
await x.host.prompt('接着刚才的讨论,现在颜色以米白为准,为什么?');
|
||||
const payload=x.requests.at(-1),all=JSON.stringify(payload.messages);
|
||||
assert.ok(all.includes('继续比较刚才的方案'));assert.ok(all.includes('颜色是胡桃色'));
|
||||
const system=payload.messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||||
assert.doesNotMatch(system,/米白|configured-shop专属规则/u);
|
||||
assert.ok(!system.includes('"evidence":"颜色是胡桃色"'),'old memory cannot become current confirmed memory on a rule change');
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('discussion followed by explicit editing requests permission only for the actual write',async()=>{
|
||||
const x=await fixture((_payload,n,native)=>{
|
||||
if(n<3)return sse({content:'先讨论,不修改。'});
|
||||
if(n===3)return tool('canvas_read',{});
|
||||
if(n===4)return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'新标题'},label:'修改标题'});
|
||||
return sse({content:'已按要求修改标题。'});
|
||||
});
|
||||
try{
|
||||
await x.host.prompt('讨论一下配色');await x.host.prompt('解释一下你的建议');assert.equal(x.native.requests,0);
|
||||
await x.host.prompt('把当前标题改为新标题');
|
||||
assert.equal(x.native.requests,1);assert.equal(x.native.writes,1);assert.equal(x.native.text,'新标题');
|
||||
assert.ok(x.requests[3].messages.some(m=>m.role==='tool'&&m.content.includes('"writeBlocked":false')));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('current-domain memory requires the user to reconfirm old-shop evidence even when it remains in continuous history',async()=>{
|
||||
const evidence='当前商品颜色是胡桃色';
|
||||
const x=await fixture((_payload,n)=>[2,4].includes(n)?tool('memory_set',{key:'color',value:'胡桃色',evidence}):sse({content:'按当前域明确确认的资料处理。'}),{shop:'old-shop'});
|
||||
try{
|
||||
await x.host.prompt(evidence+',先讨论旧店铺。');
|
||||
const next=await x.reopen('new-shop');
|
||||
assert.ok(x.host.session.messages.some(m=>m.role==='user'&&(typeof m.content==='string'?m.content.includes(evidence):m.content.some(c=>c.type==='text'&&c.text.includes(evidence)))));
|
||||
await x.host.prompt('现在只讨论新店铺的布局,尚未确认旧资料适用于这里。');
|
||||
assert.deepEqual((await next.context()).confirmedMemory,{});
|
||||
assert.ok(x.host.session.messages.some(m=>m.role==='toolResult'&&m.toolName==='memory_set'&&m.isError));
|
||||
await x.host.prompt('我重新确认:'+evidence+',适用于当前店铺,请记住。');
|
||||
const memory=(await next.context()).confirmedMemory.color;
|
||||
assert.equal(memory.value,'胡桃色');assert.equal(memory.bindingHash,next.hash);assert.equal(memory.evidence,evidence);
|
||||
const oldLedger=await fs.readFile(path.join(x.store.memoryDir,'user-evidence.jsonl'),'utf8');
|
||||
const newLedger=await fs.readFile(path.join(next.memoryDir,'user-evidence.jsonl'),'utf8');
|
||||
assert.ok(oldLedger.includes('旧店铺'));assert.ok(!newLedger.includes('先讨论旧店铺'));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('an inactive project cannot read another canvas through a tool or dispatch a new discussion using its context',async()=>{
|
||||
const x=await fixture(()=>sse({content:'A项目的原回复留存。'}));
|
||||
try{
|
||||
await x.host.prompt('先讨论A产品,不修改。');
|
||||
x.native.read=async()=>({conversationActive:false,allowed:false,writeBlocked:true,revision:99,context:{id:8,name:'B项目私有名称',width:750,layers:[{id:91,text:'B的秘密文字'}]}});
|
||||
const read=x.host.session.agent.state.tools.find(t=>t.name==='canvas_read');
|
||||
await assert.rejects(read.execute('inactive-read',{},undefined),/项目已切换/);
|
||||
await assert.rejects(x.host.prompt('仍来自A的迟到要求'),/项目已切换/);
|
||||
assert.equal(x.requests.length,1);assert.ok(!JSON.stringify(x.requests).includes('B的秘密文字'));
|
||||
assert.ok(x.host.manager.getEntries().some(e=>e.type==='message'&&e.message.role==='assistant'&&e.message.content.some(c=>c.text==='A项目的原回复留存。')));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('switching projects in the middle of the original SSE detaches UI delivery but keeps the complete A reply with one POST',async()=>{
|
||||
const fragments=['A开始讨论。','A继续解释,保留这一段。','A结尾完整信息。'],full=fragments.join('');
|
||||
let chunksConsumed=0,deltaAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
|
||||
const x=await fixture(()=>new Response(new ReadableStream({async start(controller){
|
||||
for(const content of fragments){controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{content},finish_reason:null}]})}\n\n`));chunksConsumed++;await new Promise(r=>setTimeout(r,30));}
|
||||
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta:{},finish_reason:'stop'}]})}\n\ndata: [DONE]\n\n`));controller.close();
|
||||
}}),{headers:{'content-type':'text/event-stream'}}));
|
||||
const originalRead=x.native.read.bind(x.native);
|
||||
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
|
||||
x.native.delta=async()=>{deltaAttempts++;switched=true;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
|
||||
x.native.activity=async text=>{otherProjectHistory.push(text);throw Error('must not deliver activity into B');};
|
||||
x.native.end=async()=>{endAttempts++;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
|
||||
try{
|
||||
const result=await x.host.prompt('A项目:完整解释后自然结束,不修改画布。');
|
||||
assert.equal(result.text,full);assert.equal(result.rounds,1);assert.equal(x.requests.length,1);assert.equal(chunksConsumed,3);
|
||||
assert.equal(deltaAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.writes,0);
|
||||
const replies=x.host.manager.getEntries().filter(e=>e.type==='message'&&e.message.role==='assistant').map(e=>e.message);
|
||||
assert.ok(replies.some(m=>m.stopReason==='stop'&&m.content.filter(c=>c.type==='text').map(c=>c.text).join('')===full));
|
||||
assert.ok(!replies.some(m=>m.stopReason==='error'),'an inactive display is not an incomplete model result');
|
||||
const journal=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).split('\n').filter(Boolean).map(JSON.parse);
|
||||
assert.equal(journal.filter(e=>e.type==='provider_prepared').length,1);assert.ok(journal.some(e=>e.type==='provider_finished'&&e.phase==='complete'));
|
||||
assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='delta'));assert.ok(journal.some(e=>e.type==='inactive_ui_delivery'&&e.method==='end'));
|
||||
assert.equal(x.events.filter(e=>e.type==='text_delta').map(e=>e.delta).join(''),full);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('inactive activity delivery preserves the original assistant/tool transcript and stops the next paid model step locally',async()=>{
|
||||
let activityAttempts=0,endAttempts=0,switched=false;const otherProjectHistory=[];
|
||||
const x=await fixture(()=>sse({content:'A的完整规则解释,随后只读查询原历史。',tool_calls:[{index:0,id:'read-old-a',type:'function',function:{name:'memory_search',arguments:JSON.stringify({query:'A项目'})}}]},'tool_calls'));
|
||||
const originalRead=x.native.read.bind(x.native);
|
||||
x.native.read=async()=>switched?{conversationActive:false,allowed:false,writeBlocked:true,context:null}:originalRead();
|
||||
x.native.activity=async()=>{activityAttempts++;switched=true;throw new BridgeError('操作说明已留在原项目','scope_changed');};
|
||||
x.native.delta=async text=>{if(switched)otherProjectHistory.push(text);};
|
||||
x.native.end=async()=>{endAttempts++;throw new BridgeError('原项目已切换,回复保留在原项目会话,未写入当前项目','scope_changed');};
|
||||
try{
|
||||
const result=await x.host.prompt('A项目:解释当前规则,并只读查找A项目的历史。');
|
||||
assert.match(result.text,/原项目已切换/);assert.equal(x.requests.length,1);assert.equal(result.rounds,1);
|
||||
assert.equal(activityAttempts,1);assert.equal(endAttempts,1);assert.deepEqual(otherProjectHistory,[]);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||||
const messages=x.host.manager.getEntries().filter(e=>e.type==='message').map(e=>e.message);
|
||||
assert.ok(messages.some(m=>m.role==='assistant'&&m.stopReason==='toolUse'&&m.content.some(c=>c.type==='text'&&c.text==='A的完整规则解释,随后只读查询原历史。')));
|
||||
assert.ok(messages.some(m=>m.role==='toolResult'&&m.toolCallId==='read-old-a'&&!m.isError));
|
||||
assert.ok(!messages.some(m=>m.role==='assistant'&&m.stopReason==='error'));
|
||||
const log=await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8');assert.ok(log.includes('inactive_project_stopped'));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('presentation errors leave the original result intact while an end failure is reported once',async()=>{
|
||||
for(const method of ['delta','activity','end']){
|
||||
let attempts=0;
|
||||
const message='本机通知未确认';
|
||||
const x=await fixture((_payload,n)=>method==='activity'&&n===1?tool('memory_search',{query:'讨论'}):sse({content:'原回复。'}));
|
||||
x.native[method]=async()=>{attempts++;throw Error(message);};
|
||||
try{
|
||||
if(method==='end')await assert.rejects(x.host.prompt('当前项目普通讨论'),new RegExp(message));
|
||||
else assert.equal((await x.host.prompt('当前项目普通讨论')).text,'原回复。');
|
||||
assert.equal(attempts,method==='activity'?2:1);
|
||||
assert.equal(x.requests.length,method==='activity'?2:1);
|
||||
assert.notEqual(x.host.canvasNotificationsDetached,true);
|
||||
}finally{await x.close();}
|
||||
}
|
||||
});
|
||||
|
||||
test('a blocked presentation delivery does not stop a tool or the next original model round',async()=>{
|
||||
let release,started;
|
||||
const held=new Promise(resolve=>{release=resolve;});
|
||||
const nextRound=new Promise(resolve=>{started=resolve;});
|
||||
const x=await fixture((_payload,n)=>{
|
||||
if(n===1)return sse({content:'现在查一下。',tool_calls:[{index:0,id:'search',type:'function',
|
||||
function:{name:'memory_search',arguments:'{"query":"讨论"}'}}]},'tool_calls');
|
||||
started();
|
||||
return sse({content:'核对完成。'});
|
||||
});
|
||||
x.native.delta=()=>held;
|
||||
const result=x.host.prompt('当前项目普通讨论');
|
||||
try{
|
||||
await Promise.race([nextRound,new Promise((_,reject)=>{const timer=setTimeout(()=>reject(Error('展示回执阻止了后续模型交互')),2000);timer.unref();})]);
|
||||
assert.equal(x.requests.length,2);
|
||||
}finally{
|
||||
release();
|
||||
try{assert.equal((await result).text,'核对完成。');}finally{await x.close();}
|
||||
}
|
||||
});
|
||||
|
||||
test('handover rejects the proposed write and skips subsequent editing inference, then a new question works',async()=>{
|
||||
const x=await fixture((_payload,n,native)=>{
|
||||
if(n===1)return tool('canvas_read',{});
|
||||
if(n===2){native.writeBlocked=true;return tool('canvas_edit',{revision:native.revision,command:'type.edit',params:{layer:1,text:'不可应用'},label:'修改标题'});}
|
||||
return sse({content:'新的问答可以继续,上一轮修改已经停止。'});
|
||||
});
|
||||
try{
|
||||
assert.match((await x.host.prompt('请改标题,过程中用户接手')).text,/已接手/);
|
||||
assert.equal(x.requests.length,2);assert.equal(x.native.writes,0);assert.equal(x.native.text,'原始标题');
|
||||
assert.match((await x.host.prompt('先不修改,继续解释另一个方案')).text,/新的问答/);
|
||||
assert.equal(x.requests.length,3);assert.equal(x.native.writes,0);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a canvas click during discussion blocks writes but does not cut off a read-only discussion or its streamed reply',async()=>{
|
||||
const x=await fixture((_payload,n,native)=>{
|
||||
if(n===1){native.writeBlocked=true;return tool('context_read',{});}
|
||||
return sse({content:'可以继续完整讨论:先用真实外观建立首屏,再解释产品细节。尺寸未确认,所以不写具体数值。'});
|
||||
});
|
||||
try{
|
||||
const result=await x.host.prompt('先讨论页面顺序,不修改画布;我会手动点选查看产品。');
|
||||
assert.match(result.text,/可以继续完整讨论/);assert.match(result.text,/不写具体数值/);
|
||||
assert.equal(x.requests.length,2);assert.equal(x.native.requests,0);assert.equal(x.native.writes,0);
|
||||
assert.ok(x.native.writeBlocked);assert.ok(x.events.some(e=>e.type==='text_delta'&&e.delta.includes('完整讨论')));
|
||||
const system=x.requests[1].messages.filter(m=>m.role==='system').map(m=>m.content).join('\n');
|
||||
assert.doesNotMatch(system,/当前项目与画布事实/u);
|
||||
assert.ok(!x.host.session.messages.some(m=>m.role==='assistant'&&m.content?.some(c=>c.type==='text'&&c.text==='本机:已接手,剩余画布操作已停止。')));
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('product evidence preserves complete facts and screens and rejects foreign identity',()=>{
|
||||
const project=randomUUID(),source=evidence(project);
|
||||
source.facts.items=Array.from({length:100},()=>({text:'事实'.repeat(500),source:'来源'.repeat(500)}));source.facts.missing=Array.from({length:100},()=> '待确认'.repeat(500));
|
||||
const context=productContext(source,{scope,project,documentId:7});
|
||||
assert.equal(context.facts.length,100);
|
||||
assert.equal(context.missing.length,100);
|
||||
assert.equal(context.facts.at(-1).text,source.facts.items.at(-1).text);
|
||||
assert.ok(!JSON.stringify(context).includes('imagePrompt'));
|
||||
for(const identity of [{scope:'7'.repeat(64),project,documentId:7},{scope,project:randomUUID(),documentId:7},{scope,project,documentId:8}])assert.throws(()=>productContext(source,identity),/不属于/);
|
||||
});
|
||||
|
||||
test('output colors reach product evidence as separate image types',()=>{
|
||||
const project=randomUUID(),source=evidence(project);
|
||||
source.brief.outputColors={detail:'原木色',sku_images:'雾灰色',main_images:'暖白色',unknown:'省略'};
|
||||
source.brief.variants=[{id:'oak',colorName:'旧花色',images:[],outputColors:{detail:'胡桃木色',sku_images:'',main_images:'C:\\private\\file'}}];
|
||||
const context=productContext(source,{scope,project,documentId:7});
|
||||
assert.deepEqual(context.product.outputColors,{detail:'原木色',sku_images:'雾灰色',main_images:'暖白色'});
|
||||
assert.deepEqual(context.references.variants[0].outputColors,{detail:'胡桃木色',sku_images:''});
|
||||
});
|
||||
|
||||
test('SKU color plan exposes all SKUs and only the chosen IDs for detail and main images',()=>{
|
||||
const project=randomUUID(),source=evidence(project);
|
||||
source.brief.variants=[{id:'oak',colorName:'原木色',images:[],outputColors:{main_images:'旧颜色'}},{id:'white',colorName:'暖白色',images:[]}];
|
||||
source.brief.outputVariantIds={detail:['oak','white'],main_images:['white'],sku_images:['oak']};
|
||||
const context=productContext(source,{scope,project,documentId:7});
|
||||
assert.deepEqual(context.references.variants.map(v=>[v.id,v.colorName]),[['oak','原木色'],['white','暖白色']]);
|
||||
assert.deepEqual(context.references.outputVariantIds,{detail:['oak','white'],main_images:['white']});
|
||||
assert.ok(!JSON.stringify(context).includes('旧颜色'));
|
||||
});
|
||||
|
||||
test('legacy transcript migration retains originals and never clears broker pending on a binding change',async()=>{
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};let host;
|
||||
try{
|
||||
const legacy=await ProjectStore.open(root,identity,binding('A'));
|
||||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||||
manager.appendMessage({role:'user',content:'原始会话必须保留',timestamp:Date.now()});
|
||||
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||||
await legacy.appendEvent({type:'provider_prepared',id:'preserved-request',bindingHash:legacy.hash});
|
||||
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'preserved-request',phase:'review'}]);
|
||||
const original=await fs.readFile(manager.getSessionFile(),'utf8');
|
||||
const stable=await ProjectStore.open(root,identity,binding('B'),{continuous:true});
|
||||
assert.deepEqual(await stable.get('recovered-tools.json',[]),[{id:'preserved-request',phase:'review'}]);
|
||||
assert.ok((await fs.readFile(path.join(stable.dir,'events.jsonl'),'utf8')).includes('preserved-request'));
|
||||
let posts=0;
|
||||
host=await DetailPiAgent.open({store:stable,broker:{info:async()=>({accountScope:scope,model:{id:'qa',protocol:'openai-chat'},pending:[{id:'original-unknown'}]}),round(){posts++;throw Error('must not post');}}});
|
||||
assert.ok(host.session.messages.some(m=>m.role==='user'&&m.content==='原始会话必须保留'));
|
||||
await assert.rejects(host.prompt('继续普通聊天也不能重发未知请求'),/未知请求|工具建议/);assert.equal(posts,0);
|
||||
assert.equal(await fs.readFile(manager.getSessionFile(),'utf8'),original);
|
||||
}finally{await host?.dispose();await cleanup(root);}
|
||||
});
|
||||
|
||||
test('legacy migration resumes exact partially copied files and publishes the pointer last without overwriting originals',async()=>{
|
||||
for(const copiedEvents of [false,true]){
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
|
||||
try{
|
||||
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
|
||||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||||
manager.appendMessage({role:'user',content:'迁移原件不得改写',timestamp:Date.now()});
|
||||
await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||||
await legacy.appendEvent({type:'provider_prepared',id:'old-request',bindingHash:legacy.hash});
|
||||
await atomic(path.join(legacy.dir,'recovered-tools.json'),[{id:'old-request',phase:'review'}]);
|
||||
const original=await fs.readFile(manager.getSessionFile()),events=await fs.readFile(path.join(legacy.dir,'events.jsonl'));
|
||||
const stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
|
||||
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,original,{flag:'wx'});
|
||||
if(copiedEvents)await fs.writeFile(path.join(stableDir,'events.jsonl'),events,{flag:'wx'});
|
||||
const resumed=await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
|
||||
assert.equal((await resumed.get('session.json')).file,target);assert.deepEqual(await fs.readFile(target),original);
|
||||
assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);assert.deepEqual(await fs.readFile(path.join(stableDir,'events.jsonl')),events);
|
||||
assert.deepEqual(await resumed.get('recovered-tools.json'),[{id:'old-request',phase:'review'}]);
|
||||
assert.equal((await resumed.get('migration.json')).originalRetained,true);
|
||||
await ProjectStore.open(root,identity,binding('new-shop'),{continuous:true});
|
||||
assert.deepEqual(await fs.readFile(target),original);
|
||||
}finally{await cleanup(root);}
|
||||
}
|
||||
});
|
||||
|
||||
test('legacy migration rejects a pre-existing target with different bytes and never publishes a pointer or overwrites it',async()=>{
|
||||
const root=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')),identity={scope,project:randomUUID()};
|
||||
try{
|
||||
const legacy=await ProjectStore.open(root,identity,binding('legacy-shop'));
|
||||
const {SessionManager}=await import('@earendil-works/pi-coding-agent');
|
||||
const manager=SessionManager.create(legacy.dir,path.join(legacy.dir,'sessions'));
|
||||
manager.appendMessage({role:'user',content:'原件',timestamp:Date.now()});await atomic(path.join(legacy.dir,'session.json'),{file:manager.getSessionFile()});
|
||||
const original=await fs.readFile(manager.getSessionFile()),stableDir=path.join(legacy.root,'conversation-v1'),target=path.join(stableDir,'sessions','legacy-'+legacy.hash+'.jsonl');
|
||||
await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,'different retained bytes',{flag:'wx'});
|
||||
await assert.rejects(ProjectStore.open(root,identity,binding('new-shop'),{continuous:true}),/迁移目标与原件不一致/);
|
||||
assert.equal(await fs.readFile(target,'utf8'),'different retained bytes');assert.deepEqual(await fs.readFile(manager.getSessionFile()),original);
|
||||
await assert.rejects(fs.access(path.join(stableDir,'session.json')),error=>error.code==='ENOENT');
|
||||
}finally{await cleanup(root);}
|
||||
});
|
||||
|
||||
test('the agent queries actual slot progress with its tools',async()=>{
|
||||
const slots=Array.from({length:27},(_,index)=>({
|
||||
id:'slot-'+index,
|
||||
selectedCandidateId:index<2?'accepted-'+index:null,
|
||||
candidates:index===2?[{status:'complete'}]:index===3?[{status:'unknown'}]:[],
|
||||
}));
|
||||
const offsets=[];
|
||||
const x=await fixture((_payload,n)=>n<=3?tool('workflow_read',{section:'slots',offset:(n-1)*12}):
|
||||
sse({content:'27 个图位,已回填 2 个,还有 25 个未回填。其中 1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选。'}), {
|
||||
workflowRead:async({section,offset=0})=>{
|
||||
if(section==='slots')offsets.push(offset);
|
||||
return {available:true,version:18,section,canvasFirst:true,outputId:'detail',productVariantId:'brown',
|
||||
totalSlots:slots.length,slots:slots.slice(offset,offset+12),productEvidence:evidence(x.identity.project)};
|
||||
}
|
||||
});
|
||||
try{
|
||||
const result=await x.host.prompt('后面还有几张图没有完成的');
|
||||
assert.match(result.text,/27 个图位,已回填 2 个,还有 25 个未回填/);
|
||||
assert.match(result.text,/1 个已有候选,1 个正在生成或待核查,23 个暂无可用候选/);
|
||||
assert.deepEqual(offsets,[0,12,24]);
|
||||
assert.equal(result.rounds,4);
|
||||
assert.equal(x.requests.length,4);
|
||||
assert.equal(x.native.writes,0);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a desktop turn continues past 12 useful model calls',async()=>{
|
||||
const x=await fixture((_payload,n)=>n<=12?tool('workflow_read',{section:'slots',offset:n-1}):sse({content:'逐个核对完了。'}));
|
||||
x.native.workflowRead=async({section,offset=0})=>({available:true,version:1,section,
|
||||
canvasFirst:true,outputId:'detail',offset,productEvidence:evidence(x.identity.project)});
|
||||
try{
|
||||
assert.equal((await x.host.prompt('请逐个核对所有图位的描述')).text,'逐个核对完了。');
|
||||
assert.equal(x.requests.length,13);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
test('a burst of text and reasoning delivers the complete coalesced reply to the canvas',async()=>{
|
||||
const chunk=delta=>'data: '+JSON.stringify({id:'qa',model:'qa',choices:[{index:0,delta,finish_reason:null}]})+'\n\n';
|
||||
const x=await fixture(()=>chunk({reasoning_content:'检查资料'})+chunk({content:'第一段'})+sse({content:'。第二段。'}));
|
||||
const presented=[];
|
||||
x.native.delta=async text=>{presented.push(text);};
|
||||
try{
|
||||
assert.equal((await x.host.prompt('用两句短话介绍一下你自己')).text,'第一段。第二段。');
|
||||
assert.deepEqual(presented.filter(Boolean),['第一段。第二段。']);
|
||||
}finally{await x.close();}
|
||||
});
|
||||
|
||||
@ -1,178 +1,405 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { test } from 'node:test';
|
||||
import { startDaemon } from '../src/desktop-daemon.mjs';
|
||||
import { StdioCanvas } from '../src/stdio-canvas.mjs';
|
||||
|
||||
const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22';
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
function daemonFixture(t, { runSession, parentAlive = () => true } = {}) {
|
||||
const input = new PassThrough();
|
||||
const output = new PassThrough();
|
||||
const frames = [];
|
||||
const exits = [];
|
||||
output.on('data', bytes => frames.push(JSON.parse(bytes.toString())));
|
||||
const daemon = startDaemon({
|
||||
input,
|
||||
output,
|
||||
parentAlive,
|
||||
runSession,
|
||||
brokerFactory: () => ({ close: async () => {} }),
|
||||
exit: code => exits.push(code),
|
||||
});
|
||||
t.after(() => daemon.stop());
|
||||
const send = value => input.write(JSON.stringify(value) + '\n');
|
||||
return { input, frames, exits, send };
|
||||
}
|
||||
|
||||
test('a heartbeat gap before dispatch keeps the original turn alive', async t => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setInterval', 'setTimeout'] });
|
||||
let resumeStartup;
|
||||
const startup = new Promise(resolve => { resumeStartup = resolve; });
|
||||
let dispatches = 0;
|
||||
const { frames, exits, send } = daemonFixture(t, {
|
||||
runSession: async () => {
|
||||
await startup;
|
||||
dispatches++;
|
||||
return { text: '首屏候选已完成', unknown: false };
|
||||
},
|
||||
});
|
||||
|
||||
send({ type: 'heartbeat', id: 1 });
|
||||
send({ type: 'run', runId, config: {} });
|
||||
await tick();
|
||||
t.mock.timers.tick(3000);
|
||||
t.mock.timers.tick(30);
|
||||
await tick();
|
||||
assert.deepEqual(exits, [], 'the owner and the pipe are still alive');
|
||||
assert.equal(dispatches, 0);
|
||||
|
||||
send({ type: 'heartbeat', id: 2 });
|
||||
resumeStartup();
|
||||
await tick();
|
||||
assert.equal(dispatches, 1);
|
||||
assert.deepEqual(frames.filter(frame => frame.type === 'heartbeat_ack').map(frame => frame.id), [1, 2]);
|
||||
assert.equal(frames.filter(frame => frame.type === 'complete').length, 1);
|
||||
assert.deepEqual(frames.at(-1), {
|
||||
type: 'complete', runId, value: { text: '首屏候选已完成', unknown: false },
|
||||
});
|
||||
});
|
||||
|
||||
test('the daemon closes when its owner goes away', async t => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setInterval', 'setTimeout'] });
|
||||
let alive = true;
|
||||
const { exits } = daemonFixture(t, { parentAlive: () => alive });
|
||||
alive = false;
|
||||
t.mock.timers.tick(200);
|
||||
t.mock.timers.tick(30);
|
||||
await tick();
|
||||
assert.deepEqual(exits, [0]);
|
||||
});
|
||||
|
||||
test('the daemon closes on EOF even while its owner is alive', async t => {
|
||||
const { input, exits } = daemonFixture(t);
|
||||
input.end();
|
||||
await tick();
|
||||
assert.deepEqual(exits, [0]);
|
||||
});
|
||||
|
||||
|
||||
test('a production deadline aborts a waiting canvas call and retains original requests', async t => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: 10_000 });
|
||||
let entered = 0;
|
||||
const { frames, send } = daemonFixture(t, {
|
||||
runSession: async (config, call, _broker, _recovery, signal) => {
|
||||
entered++;
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /达到时限/);
|
||||
assert.equal(signal.aborted, true);
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /达到时限/);
|
||||
return { pending: ['original-1'], unknown: true, reposted: false };
|
||||
},
|
||||
});
|
||||
send({ type: 'run', runId, config: { productProduction: true, productionDeadline: 11 } });
|
||||
await tick();
|
||||
t.mock.timers.tick(999);
|
||||
assert.equal(frames.filter(frame => frame.type === 'complete').length, 0);
|
||||
t.mock.timers.tick(1);
|
||||
await tick();
|
||||
assert.equal(entered, 1);
|
||||
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
|
||||
assert.deepEqual(frames.at(-1), {
|
||||
type: 'complete', runId, value: { pending: ['original-1'], unknown: true, reposted: false },
|
||||
});
|
||||
});
|
||||
|
||||
test('a pause on the bound production stops further tools and leaves the original request for recovery', async t => {
|
||||
let cancelled = false;
|
||||
const config = { productProduction: true, documentId: 27, project: 'desk', scope: 'account-a' };
|
||||
const { frames, send } = daemonFixture(t, {
|
||||
runSession: async (_, call, _broker, _recovery, signal) => {
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), {category:'cancelled',dispatched:true});
|
||||
cancelled = signal.aborted;
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), {category:'cancelled',dispatched:false});
|
||||
return { pending: ['original-1'], unknown: true, reposted: false };
|
||||
},
|
||||
});
|
||||
send({ type: 'run', runId, config });
|
||||
await tick();
|
||||
send({ ...config, type: 'production_pause', scope: 'account-b' });
|
||||
await tick();
|
||||
assert.equal(cancelled, false);
|
||||
send({ ...config, type: 'production_pause' });
|
||||
await tick();
|
||||
assert.equal(cancelled, true);
|
||||
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
|
||||
assert.deepEqual(frames.at(-1), {
|
||||
type: 'complete', runId, value: { pending: ['original-1'], unknown: true, reposted: false },
|
||||
});
|
||||
});
|
||||
|
||||
test('presentation notifications do not wait for replies and the terminal command still does', async t => {
|
||||
const {frames,send}=daemonFixture(t,{
|
||||
runSession:async(_config,call)=>{
|
||||
await call('pi-delta',{text:'正在写'});
|
||||
await call('pi-activity',{text:'读取画布'});
|
||||
await call('pi-end',{text:'写完'});
|
||||
return {text:'写完'};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config:{}});
|
||||
await tick();
|
||||
assert.deepEqual(frames.slice(1).map(({type,action})=>[type,action]),[
|
||||
['presentation','pi-delta'],['presentation','pi-activity'],['canvas','pi-end'],
|
||||
]);
|
||||
const {id}=frames.at(-1);
|
||||
send({type:'canvas_result',runId,id,value:null});
|
||||
await tick();
|
||||
assert.equal(frames.at(-1).type,'complete');
|
||||
});
|
||||
|
||||
test('the stdio canvas settles save, cancel and state replies ahead of a pending render', async t => {
|
||||
const observed=[];
|
||||
const {frames,send}=daemonFixture(t,{
|
||||
runSession:async(_config,call)=>{
|
||||
const canvas=new StdioCanvas(call,27);
|
||||
const screen=canvas.detailRender({page:0}).then(receipt=>observed.push(receipt));
|
||||
await Promise.all([
|
||||
canvas.nativeCall({method:'engine.execute',revision:7,params:{command:'file.save',params:{}}}),
|
||||
canvas.uiCancel('pending-interaction'),
|
||||
canvas.read(),
|
||||
].map(promise=>promise.then(receipt=>observed.push(receipt))));
|
||||
await screen;
|
||||
return {};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config:{}});
|
||||
await tick();
|
||||
const requests=frames.filter(frame=>frame.type==='canvas');
|
||||
assert.deepEqual(requests.map(frame=>frame.action),['pi-product-screen','pi-native-call','pi-ui-cancel','pi-state']);
|
||||
for(const {id,action} of requests.slice(1))send({type:'canvas_result',runId,id,value:action});
|
||||
await tick();
|
||||
assert.deepEqual(observed,['pi-native-call','pi-ui-cancel','pi-state']);
|
||||
assert.equal(frames.some(frame=>frame.type==='complete'),false);
|
||||
send({type:'canvas_result',runId,id:requests[0].id,value:{revision:7}});
|
||||
await tick();
|
||||
assert.deepEqual(observed.at(-1),{revision:7});
|
||||
assert.equal(frames.at(-1).type,'complete');
|
||||
});
|
||||
import assert from 'node:assert/strict';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { once } from 'node:events';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createInterface } from 'node:readline';
|
||||
import { test } from 'node:test';
|
||||
import { startDaemon } from '../src/desktop-daemon.mjs';
|
||||
import { ProjectRepository } from '../src/project-repository.mjs';
|
||||
import { StdioCanvas } from '../src/stdio-canvas.mjs';
|
||||
import { observeCanvasCalls } from '../src/desktop-host.mjs';
|
||||
import { executionEvent } from '../src/activity-event.mjs';
|
||||
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()=>{
|
||||
const records=[];
|
||||
const executionScope={projectId:'project',runId,outputId:'detail',variantId:'oak',revision:7,documentKey:{variantId:'oak'}};
|
||||
const executionHealth={};
|
||||
const store={executionScope,executionHealth,async appendEvent(event){records.push(executionEvent(event,executionScope,executionHealth));}};
|
||||
const visible={outputId:'sku_images',variantId:'stone'};
|
||||
const call=observeCanvasCalls(store,async(_action,_input,accepted)=>{
|
||||
accepted();
|
||||
return {revision:8,viewing:visible};
|
||||
});
|
||||
await call('pi-detail-copy-apply',{operationId:'copy-1',revision:7});
|
||||
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],
|
||||
]);
|
||||
for(const event of records){
|
||||
assert.equal(event.projectId,'project');
|
||||
assert.equal(event.runId,runId);
|
||||
assert.equal(event.operationId,'copy-1');
|
||||
assert.equal(event.attempt,1);
|
||||
assert.equal(event.outputId,'detail');
|
||||
assert.equal(event.variantId,'oak');
|
||||
assert.deepEqual(event.documentKey,{variantId:'oak'});
|
||||
assert.ok(Number.isFinite(event.agentHeartbeat));
|
||||
assert.equal(event.jobProgress,null);
|
||||
assert.equal(event.recentDurableCommit,null);
|
||||
}
|
||||
assert.equal(records[0].uiHeartbeat,null);
|
||||
assert.ok(Number.isFinite(records[1].uiHeartbeat));
|
||||
});
|
||||
|
||||
test('a retried canvas read keeps its operation ID and records the next attempt',async()=>{
|
||||
const attempts=[];
|
||||
const canvas=new StdioCanvas(async(action,_input,execution)=>{
|
||||
assert.equal(action,'pi-product-screen');
|
||||
attempts.push(execution);
|
||||
if(attempts.length===1)throw new BridgeError('原读屏回执等待超时','transport_interrupted');
|
||||
return {revision:7};
|
||||
},27);
|
||||
assert.deepEqual(await canvas.detailRender({page:0}),{revision:7});
|
||||
assert.deepEqual(attempts.map(row=>row.attempt),[1,2]);
|
||||
assert.equal(attempts[0].operationId,attempts[1].operationId);
|
||||
});
|
||||
|
||||
function daemonFixture(t, { runSession, parentAlive = () => true } = {}) {
|
||||
const input = new PassThrough();
|
||||
const output = new PassThrough();
|
||||
const frames = [];
|
||||
const exits = [];
|
||||
output.on('data', bytes => frames.push(JSON.parse(bytes.toString())));
|
||||
const daemon = startDaemon({
|
||||
input,
|
||||
output,
|
||||
parentAlive,
|
||||
runSession,
|
||||
brokerFactory: () => ({ close: async () => {} }),
|
||||
exit: code => exits.push(code),
|
||||
});
|
||||
t.after(() => daemon.stop());
|
||||
const send = value => input.write(JSON.stringify(value) + '\n');
|
||||
return { input, frames, exits, send };
|
||||
}
|
||||
|
||||
test('a heartbeat gap before dispatch keeps the original turn alive', async t => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setInterval', 'setTimeout'] });
|
||||
let resumeStartup;
|
||||
const startup = new Promise(resolve => { resumeStartup = resolve; });
|
||||
let dispatches = 0;
|
||||
const { frames, exits, send } = daemonFixture(t, {
|
||||
runSession: async () => {
|
||||
await startup;
|
||||
dispatches++;
|
||||
return { text: '首屏候选已完成', unknown: false };
|
||||
},
|
||||
});
|
||||
|
||||
send({ type: 'heartbeat', id: 1 });
|
||||
send({ type: 'run', runId, config: {} });
|
||||
await tick();
|
||||
t.mock.timers.tick(3000);
|
||||
t.mock.timers.tick(30);
|
||||
await tick();
|
||||
assert.deepEqual(exits, [], 'the owner and the pipe are still alive');
|
||||
assert.equal(dispatches, 0);
|
||||
|
||||
send({ type: 'heartbeat', id: 2 });
|
||||
resumeStartup();
|
||||
await tick();
|
||||
assert.equal(dispatches, 1);
|
||||
assert.deepEqual(frames.filter(frame => frame.type === 'heartbeat_ack').map(frame => frame.id), [1, 2]);
|
||||
assert.equal(frames.filter(frame => frame.type === 'complete').length, 1);
|
||||
assert.deepEqual(frames.at(-1), {
|
||||
type: 'complete', runId, value: { text: '首屏候选已完成', unknown: false },
|
||||
});
|
||||
});
|
||||
|
||||
test('the daemon closes when its owner goes away', async t => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setInterval', 'setTimeout'] });
|
||||
let alive = true;
|
||||
const { exits } = daemonFixture(t, { parentAlive: () => alive });
|
||||
alive = false;
|
||||
t.mock.timers.tick(200);
|
||||
t.mock.timers.tick(30);
|
||||
await tick();
|
||||
assert.deepEqual(exits, [0]);
|
||||
});
|
||||
|
||||
test('the daemon closes on EOF even while its owner is alive', async t => {
|
||||
const { input, exits } = daemonFixture(t);
|
||||
input.end();
|
||||
await tick();
|
||||
assert.deepEqual(exits, [0]);
|
||||
});
|
||||
|
||||
|
||||
test('a production deadline aborts a waiting canvas call and retains original requests', async t => {
|
||||
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: 10_000 });
|
||||
let entered = 0;
|
||||
const { frames, send } = daemonFixture(t, {
|
||||
runSession: async (config, call, _broker, _recovery, signal) => {
|
||||
entered++;
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /达到时限/);
|
||||
assert.equal(signal.aborted, true);
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), /达到时限/);
|
||||
return { pending: ['original-1'], unknown: true, reposted: false };
|
||||
},
|
||||
});
|
||||
send({ type: 'run', runId, config: { productProduction: true, productionDeadline: 11 } });
|
||||
await tick();
|
||||
t.mock.timers.tick(999);
|
||||
assert.equal(frames.filter(frame => frame.type === 'complete').length, 0);
|
||||
t.mock.timers.tick(1);
|
||||
await tick();
|
||||
assert.equal(entered, 1);
|
||||
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
|
||||
assert.deepEqual(frames.at(-1), {
|
||||
type: 'complete', runId, value: { pending: ['original-1'], unknown: true, reposted: false },
|
||||
});
|
||||
});
|
||||
|
||||
test('a pause on the bound production stops further tools and leaves the original request for recovery', async t => {
|
||||
let cancelled = false;
|
||||
const config = { productProduction: true, documentId: 27, project: 'desk', scope: 'account-a' };
|
||||
const { frames, send } = daemonFixture(t, {
|
||||
runSession: async (_, call, _broker, _recovery, signal) => {
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), {category:'cancelled',dispatched:true});
|
||||
cancelled = signal.aborted;
|
||||
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), {category:'cancelled',dispatched:false});
|
||||
return { pending: ['original-1'], unknown: true, reposted: false };
|
||||
},
|
||||
});
|
||||
send({ type: 'run', runId, config });
|
||||
await tick();
|
||||
send({ ...config, type: 'production_pause', scope: 'account-b' });
|
||||
await tick();
|
||||
assert.equal(cancelled, false);
|
||||
send({ ...config, type: 'production_pause' });
|
||||
await tick();
|
||||
assert.equal(cancelled, true);
|
||||
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
|
||||
assert.deepEqual(frames.at(-1), {
|
||||
type: 'complete', runId, value: { pending: ['original-1'], unknown: true, reposted: false },
|
||||
});
|
||||
});
|
||||
|
||||
test('explicit exit closes admission immediately and acknowledges only after the run drains', async t => {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), 'xiaoyi-graceful-exit-'));
|
||||
t.after(() => rm(dir, {recursive:true,force:true}));
|
||||
const repository = () => new ProjectRepository(path.join(dir, 'project-repository.sqlite'),
|
||||
{accountId:'account',projectId:'project',outputId:'detail',variantId:'oak'});
|
||||
let release;
|
||||
const durable = new Promise(resolve => { release = resolve; });
|
||||
let runs = 0;
|
||||
const {frames,send,input,exits} = daemonFixture(t, {
|
||||
runSession: async (_, call, _broker, _recovery, signal) => {
|
||||
runs++;
|
||||
await assert.rejects(call('pi-detail-images', {original: 'original-image'}), {category:'cancelled',dispatched:true});
|
||||
assert.equal(signal.aborted, true);
|
||||
await assert.rejects(call('pi-edit', {}), {category:'cancelled',dispatched:false});
|
||||
await durable;
|
||||
repository().replaceLedger({binding:'template',items:{front:{state:'unknown',
|
||||
pendingOperation:{operationId:'original-operation',requestId:'original-image'}}}});
|
||||
return {pending:['original-image'], unknown:true, reposted:false};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config:{}});
|
||||
await tick();
|
||||
send({type:'prepare_exit'});
|
||||
const later = '775ac3bd-50da-476c-9051-627e7f26e53b';
|
||||
send({type:'run',runId:later,config:{}});
|
||||
await tick();
|
||||
assert.equal(runs, 1);
|
||||
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
|
||||
assert.equal(frames.some(frame => frame.type === 'exit_ready'), false);
|
||||
assert.equal(repository().readLedger(), null);
|
||||
assert.match(frames.find(frame => frame.runId === later).value.error, /未派发/);
|
||||
release();
|
||||
await tick();
|
||||
assert.deepEqual(frames.at(-2).value.pending, ['original-image']);
|
||||
assert.deepEqual(frames.at(-1), {type:'exit_ready'});
|
||||
input.end();
|
||||
await tick();
|
||||
assert.deepEqual(exits, [0]);
|
||||
assert.deepEqual(repository().readLedger().items.front.pendingOperation,
|
||||
{operationId:'original-operation',requestId:'original-image'});
|
||||
});
|
||||
|
||||
test('a killed daemon reopens the original ledger without accepting a missing save receipt', {timeout: 15_000}, async t => {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), 'xiaoyi-exit-'));
|
||||
t.after(() => rm(dir, {recursive:true,force:true}));
|
||||
const canvas = path.join(dir, 'canvas.txt');
|
||||
const script = `
|
||||
import {startDaemon} from ${JSON.stringify(new URL('../src/desktop-daemon.mjs', import.meta.url).href)};
|
||||
import {ProjectRepository} from ${JSON.stringify(new URL('../src/project-repository.mjs', import.meta.url).href)};
|
||||
import {writeFileSync} from 'node:fs';
|
||||
import {createHash} from 'node:crypto';
|
||||
const dir = process.argv[1];
|
||||
const id = 'same-operation';
|
||||
const requestId = 'same-request';
|
||||
const file = dir + '/canvas.txt';
|
||||
const repository = new ProjectRepository(dir + '/project-repository.sqlite',
|
||||
{accountId:'account',projectId:'project',outputId:'detail',variantId:'oak'});
|
||||
startDaemon({brokerFactory:()=>({close:async()=>{}}),runSession:async(config,call)=>{
|
||||
if(config.mode==='first'){
|
||||
writeFileSync(file,'saved baseline');
|
||||
const hash=createHash('sha256').update('edited canvas').digest('hex');
|
||||
repository.replaceLedger({binding:'template',items:{front:{state:'unknown',
|
||||
pendingAdoption:{operationId:id,requestId,hash}}}});
|
||||
await call('save-canvas',{operationId:id,requestId});
|
||||
return {saved:true};
|
||||
}
|
||||
const original=repository.readLedger().items.front.pendingAdoption;
|
||||
return await call('reconcile-original',original);
|
||||
}});
|
||||
`;
|
||||
async function start(mode) {
|
||||
const child = spawn(process.execPath, ['--input-type=module','-e',script,dir], {windowsHide:true});
|
||||
const ended = once(child, 'exit');
|
||||
const lines = createInterface({input:child.stdout});
|
||||
const frames = lines[Symbol.asyncIterator]();
|
||||
const next = async () => JSON.parse((await frames.next()).value);
|
||||
const send = value => child.stdin.write(JSON.stringify(value)+'\n');
|
||||
t.after(async () => { child.kill(); await ended; });
|
||||
assert.equal((await next()).type, 'ready');
|
||||
send({type:'run', runId, config:{mode}});
|
||||
return {child,ended,send,next};
|
||||
}
|
||||
const first = await start('first');
|
||||
const write = await first.next();
|
||||
assert.equal(write.action, 'save-canvas');
|
||||
first.child.kill('SIGKILL');
|
||||
await first.ended;
|
||||
assert.equal(await readFile(canvas,'utf8'), 'saved baseline');
|
||||
const reopened = await start('reopen');
|
||||
const original = await reopened.next();
|
||||
assert.equal(original.action, 'reconcile-original');
|
||||
assert.equal(original.input.operationId, write.input.operationId);
|
||||
assert.equal(original.input.requestId, write.input.requestId);
|
||||
const diskHash = createHash('sha256').update(await readFile(canvas)).digest('hex');
|
||||
assert.notEqual(diskHash, original.input.hash);
|
||||
reopened.send({type:'canvas_result',runId,id:original.id,value:{saved:false,phase:'unknown'}});
|
||||
assert.deepEqual((await reopened.next()).value, {saved:false,phase:'unknown'});
|
||||
reopened.child.stdin.end();
|
||||
await reopened.ended;
|
||||
});
|
||||
|
||||
test('presentation notifications do not wait for replies and the terminal command still does', async t => {
|
||||
const {frames,send}=daemonFixture(t,{
|
||||
runSession:async(_config,call)=>{
|
||||
await call('pi-delta',{text:'正在写'});
|
||||
await call('pi-activity',{text:'读取画布'});
|
||||
await call('pi-end',{text:'写完'});
|
||||
return {text:'写完'};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config:{}});
|
||||
await tick();
|
||||
assert.deepEqual(frames.slice(1).map(({type,action})=>[type,action]),[
|
||||
['presentation','pi-delta'],['presentation','pi-activity'],['canvas','pi-end'],
|
||||
]);
|
||||
const {id}=frames.at(-1);
|
||||
send({type:'canvas_result',runId,id,value:null});
|
||||
await tick();
|
||||
assert.equal(frames.at(-1).type,'complete');
|
||||
});
|
||||
|
||||
test('cancellation retains the paid image receipt and rejects an old canvas reply or an old pause', async t => {
|
||||
const nextRunId='9a1ba294-f2c4-4e5f-91e0-ef6002f50e23';
|
||||
const config={productProduction:true,documentId:27,project:'desk',scope:'account-a',writeEpoch:4};
|
||||
const accepted=[];
|
||||
const {frames,send}=daemonFixture(t,{
|
||||
runSession:async(config,call,_broker,_recovery,signal)=>{
|
||||
if(config.writeEpoch===5){
|
||||
const next=await call('pi-state',{});
|
||||
assert.equal(signal.aborted,false);
|
||||
return next;
|
||||
}
|
||||
const image=call('pi-image-request',{action:'dispatch',request:{requestId:'original-image'}},()=>accepted.push('image'));
|
||||
await assert.rejects(call('pi-detail-copy-apply',{}), {category:'cancelled'});
|
||||
assert.equal(signal.aborted,true);
|
||||
return {archived:await image};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config});
|
||||
await tick();
|
||||
const [image,write]=frames.filter(frame=>frame.type==='canvas');
|
||||
send({type:'canvas_accepted',runId,id:image.id});
|
||||
send({...config,type:'production_pause'});
|
||||
send({type:'canvas_result',runId,id:write.id,value:{applied:1}});
|
||||
await tick();
|
||||
assert.deepEqual(accepted,['image']);
|
||||
assert.equal(frames.some(frame=>frame.type==='complete'),false);
|
||||
const original={requestId:'original-image',status:'complete'};
|
||||
send({type:'canvas_result',runId,id:image.id,value:original});
|
||||
await tick();
|
||||
assert.deepEqual(frames.at(-1).value,{archived:original});
|
||||
|
||||
send({type:'run',runId:nextRunId,config:{...config,writeEpoch:5}});
|
||||
await tick();
|
||||
const next=frames.at(-1);
|
||||
send({...config,type:'production_pause'});
|
||||
send({type:'canvas_result',runId,id:next.id,value:{revision:99}});
|
||||
send({type:'canvas_result',runId:nextRunId,id:next.id,value:{revision:7}});
|
||||
await tick();
|
||||
assert.deepEqual(frames.at(-1).value,{revision:7});
|
||||
});
|
||||
|
||||
test('the stdio canvas settles save, cancel and state replies ahead of a pending render', async t => {
|
||||
const observed=[];
|
||||
const {frames,send}=daemonFixture(t,{
|
||||
runSession:async(_config,call)=>{
|
||||
const canvas=new StdioCanvas(call,27);
|
||||
const screen=canvas.detailRender({page:0}).then(receipt=>observed.push(receipt));
|
||||
await Promise.all([
|
||||
canvas.nativeCall({method:'engine.execute',revision:7,params:{command:'file.save',params:{}}}),
|
||||
canvas.uiCancel('pending-interaction'),
|
||||
canvas.read(),
|
||||
].map(promise=>promise.then(receipt=>observed.push(receipt))));
|
||||
await screen;
|
||||
return {};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config:{}});
|
||||
await tick();
|
||||
const requests=frames.filter(frame=>frame.type==='canvas');
|
||||
assert.deepEqual(requests.map(frame=>frame.action),['pi-product-screen','pi-native-call','pi-ui-cancel','pi-state']);
|
||||
for(const {id,action} of requests.slice(1))send({type:'canvas_result',runId,id,value:action});
|
||||
await tick();
|
||||
assert.deepEqual(observed,['pi-native-call','pi-ui-cancel','pi-state']);
|
||||
assert.equal(frames.some(frame=>frame.type==='complete'),false);
|
||||
send({type:'canvas_result',runId,id:requests[0].id,value:{revision:7}});
|
||||
await tick();
|
||||
assert.deepEqual(observed.at(-1),{revision:7});
|
||||
assert.equal(frames.at(-1).type,'complete');
|
||||
});
|
||||
|
||||
test('account revocation rejects a pending write and ignores its late result after a new scope opens', async t => {
|
||||
const oldScope = 'account-a', newScope = 'account-b';
|
||||
const nextRun = '170ff5d1-43ad-4f24-b9cb-b0c540e01bc3';
|
||||
const {frames,send} = daemonFixture(t,{
|
||||
runSession:async (config,call) => {
|
||||
if (config.scope === newScope) return {activeScope:config.scope};
|
||||
await assert.rejects(call('pi-edit', {text:'original edit'}), {category:'scope_changed',dispatched:true});
|
||||
await assert.rejects(call('pi-image-request', {}), {category:'scope_changed',dispatched:false});
|
||||
return {phase:'paused'};
|
||||
},
|
||||
});
|
||||
send({type:'run',runId,config:{scope:oldScope}});
|
||||
await tick();
|
||||
const edit = frames.find(frame=>frame.action==='pi-edit');
|
||||
assert.ok(edit);
|
||||
send({type:'auth_revoke',scope:newScope,category:'scope_changed'});
|
||||
await tick();
|
||||
assert.equal(frames.some(frame=>frame.type==='complete'),false);
|
||||
send({type:'auth_revoke',scope:oldScope,category:'scope_changed'});
|
||||
await tick();
|
||||
send({type:'run',runId:nextRun,config:{scope:newScope}});
|
||||
send({type:'canvas_result',runId,id:edit.id,value:{completed:true}});
|
||||
await tick();
|
||||
assert.deepEqual(frames.filter(frame=>frame.type==='complete').map(frame=>frame.value), [
|
||||
{phase:'paused'}, {activeScope:newScope},
|
||||
]);
|
||||
assert.equal(frames.filter(frame=>frame.type==='canvas').length,1);
|
||||
assert.equal(frames.some(frame=>frame.type==='fatal'),false);
|
||||
});
|
||||
|
||||
@ -130,6 +130,56 @@ test('parallel production brokers inherit the native turn selection without reva
|
||||
assert.equal(parent.forDetailSlot('new-turn').selectionId,undefined);
|
||||
});
|
||||
|
||||
test('an exit signal during native broker startup prevents the original request from being sent', async () => {
|
||||
let admit, enter;
|
||||
const startup = new Promise(resolve => { admit = resolve; });
|
||||
const entered = new Promise(resolve => { enter = resolve; });
|
||||
const broker = new Native98kBroker({project:randomUUID()});
|
||||
const abort = new AbortController();
|
||||
const requests = [];
|
||||
broker.scope = 'fixture';
|
||||
broker.open = async () => {
|
||||
enter();
|
||||
await startup;
|
||||
broker.child = {stdin:{write:bytes => requests.push(bytes)},kill(){}};
|
||||
};
|
||||
const pending = broker.round().fetch('https://api.vip98k.com/v1/chat/completions',
|
||||
{method:'POST',body:'{}',signal:abort.signal});
|
||||
await entered;
|
||||
abort.abort(Error('退出已停止接单'));
|
||||
admit();
|
||||
await assert.rejects(pending, /退出已停止接单/);
|
||||
assert.deepEqual(requests, []);
|
||||
assert.equal(broker.hasUnconfirmedRequest, false);
|
||||
});
|
||||
|
||||
test('forcing the daemon model bridge closed also closes its goal and slot processes', async t => {
|
||||
const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-wire-'));
|
||||
t.after(() => cleanup(profile));
|
||||
const killed = [];
|
||||
let serial = 0;
|
||||
const parent = new Native98kBroker({project:randomUUID(),profile,spawnProcess:() => {
|
||||
const pid = ++serial;
|
||||
const child = new EventEmitter();
|
||||
child.stdin = new PassThrough();
|
||||
child.stdout = new PassThrough();
|
||||
child.stderr = new PassThrough();
|
||||
child.kill = () => {
|
||||
killed.push(pid);
|
||||
child.stdout.end();
|
||||
child.stderr.end();
|
||||
child.emit('close',0);
|
||||
};
|
||||
return child;
|
||||
}});
|
||||
await parent.open();
|
||||
await parent.forDetailSlot('goal').open();
|
||||
await parent.forDetailSlot('cover').open();
|
||||
await parent.close({force:true});
|
||||
assert.deepEqual(killed.sort(), [1,2,3]);
|
||||
await assert.rejects(parent.forDetailSlot('late').open(), /模型桥已关闭/);
|
||||
});
|
||||
|
||||
test('Pi sends an inline image and decodes a streamed function on both OpenAI APIs', async () => {
|
||||
const pixel = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jNHsAAAAASUVORK5CYII=';
|
||||
const tool = {name:'record_color',description:'Record the observed color',parameters:{type:'object',properties:{color:{type:'string'}},required:['color']}};
|
||||
|
||||
@ -46,6 +46,45 @@ async function generateAndWait(actions, {source,...request}) {
|
||||
return generation[0];
|
||||
}
|
||||
|
||||
test('a late image settles its original request after cancellation without selecting or adopting it',async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-cancelled-image-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const store=productionStore(dir);
|
||||
const ledger=store.ledger('detail','oak');
|
||||
const started=Promise.withResolvers(),done=Promise.withResolvers();
|
||||
const abort=new AbortController();
|
||||
const events=[];
|
||||
store.appendEvent=async event=>events.push(event);
|
||||
const host={store,productionSignal:abort.signal,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{
|
||||
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
|
||||
template:{contentHash:'studio'},totalSlots:1,slots:[{id:'photo',fieldId:'cover'}]}),
|
||||
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
|
||||
workflowExecute:async()=>assert.fail('a cancelled candidate cannot be adopted'),
|
||||
}};
|
||||
imageBridge(host,async(_args,id)=>{started.resolve();await done.promise;return {id,status:'complete'};});
|
||||
const old=await openProductionOperations(host);
|
||||
const prepared=await old.prepare_image_request({slotId:'photo',prompt:'保留桌面轮廓'});
|
||||
assert.equal((await old.dispatch_image_request(approve(prepared),abort.signal)).phase,'accepted');
|
||||
await started.promise;
|
||||
abort.abort();
|
||||
done.resolve();
|
||||
await old.close();
|
||||
const receipt=ledger.repository.readImageRequest(prepared.requestId);
|
||||
assert.equal(receipt.state,'complete');
|
||||
assert.equal(receipt.operationId,prepared.operationId);
|
||||
assert.equal(receipt.receipt.consumption,'archived_after_cancel');
|
||||
assert.equal(ledger.read().items.photo.candidateId,undefined);
|
||||
assert.equal(ledger.read().items.photo.pendingAdoption,undefined);
|
||||
assert.deepEqual(events.find(event=>event.type==='image_request_receipt'),{
|
||||
type:'image_request_receipt',operationId:prepared.operationId,requestId:prepared.requestId,
|
||||
outputId:'detail',variantId:'oak',slotId:'photo',category:'remote_image',phase:'archive',
|
||||
status:'cancelled',consumption:'archived_after_cancel',
|
||||
});
|
||||
const fresh=await openProductionOperations({...host,productionSignal:new AbortController().signal});
|
||||
assert.equal((await fresh.plan_production()).outputId,'detail');
|
||||
await fresh.close();
|
||||
});
|
||||
|
||||
test('P07 waits for both original images and persists the automatic adoption decision',async t=>{
|
||||
for(const scenario of [
|
||||
{verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true},
|
||||
|
||||
46
apps/detail-photocraft/Cargo.lock
generated
46
apps/detail-photocraft/Cargo.lock
generated
@ -3304,7 +3304,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -4009,6 +4009,25 @@ dependencies = [
|
||||
"pxfm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.20.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"dpi",
|
||||
"keyboard-types",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"once_cell",
|
||||
"png 0.18.1",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "muda"
|
||||
version = "0.21.2"
|
||||
@ -4993,13 +5012,13 @@ dependencies = [
|
||||
"dispatch2",
|
||||
"eframe",
|
||||
"egui",
|
||||
"flate2",
|
||||
"fmv-macos-events",
|
||||
"futures-lite",
|
||||
"image",
|
||||
"keyring",
|
||||
"flate2",
|
||||
"log",
|
||||
"muda",
|
||||
"muda 0.21.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
@ -5031,6 +5050,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tray-icon",
|
||||
"url",
|
||||
"uuid",
|
||||
"winit",
|
||||
@ -5471,6 +5491,7 @@ dependencies = [
|
||||
"unicode-bidi",
|
||||
"unicode-general-category",
|
||||
"unicode-segmentation",
|
||||
"uuid",
|
||||
"web-time",
|
||||
"winsafe",
|
||||
]
|
||||
@ -7797,6 +7818,25 @@ dependencies = [
|
||||
"strength_reduce",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tray-icon"
|
||||
version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"muda 0.20.0",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"objc2-foundation 0.3.2",
|
||||
"once_cell",
|
||||
"png 0.18.1",
|
||||
"thiserror 2.0.21",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree_magic_mini"
|
||||
version = "3.2.2"
|
||||
|
||||
@ -117,6 +117,7 @@ winit = { version = "=0.30.13", default-features = false, features = ["x11"] }
|
||||
# Safe Windows screen-capture bindings; Linux uses the pure-Rust X11 client/portal.
|
||||
xcap = "=0.9.8"
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["user"] }
|
||||
tray-icon = { version = "=0.25.1", default-features = false }
|
||||
|
||||
# tests/mac_menu_appkit.rs: reads AppKit's menu bar back and sends it real key events.
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
|
||||
@ -0,0 +1,40 @@
|
||||
//! Opens an isolated Windows window and saves a real canvas while it is parked.
|
||||
#[cfg(target_os = "windows")]
|
||||
#[path = "../src/app_icon.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod app_icon;
|
||||
#[cfg(target_os = "windows")]
|
||||
#[path = "../src/app_tray.rs"]
|
||||
mod app_tray;
|
||||
#[cfg(target_os = "windows")]
|
||||
#[path = "../../../crates/ui-egui/examples/xiaoyi_production_exit.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod production_exit;
|
||||
|
||||
fn main() {
|
||||
#[cfg(target_os = "windows")]
|
||||
production_exit::windows::run(
|
||||
std::env::args_os().nth(1).expect("an isolated project directory").into(),
|
||||
"tray".into(),
|
||||
Some(production_exit::windows::TrayProbe {
|
||||
create: |ctx| Box::new(app_tray::WindowsTray::new(ctx)),
|
||||
hidden: root_hidden,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn root_hidden(frame: &eframe::Frame) -> bool {
|
||||
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
|
||||
let Ok(handle) = frame.window_handle() else { return false };
|
||||
let RawWindowHandle::Win32(handle) = handle.as_raw() else { return false };
|
||||
let mut hidden = false;
|
||||
let _ = winsafe::EnumWindows(|window| {
|
||||
if window.ptr() as isize == handle.hwnd.get() {
|
||||
hidden = !window.IsWindowVisible();
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
hidden
|
||||
}
|
||||
73
apps/detail-photocraft/apps/photocraft/src/app_tray.rs
Normal file
73
apps/detail-photocraft/apps/photocraft/src/app_tray.rs
Normal file
@ -0,0 +1,73 @@
|
||||
use std::sync::mpsc;
|
||||
|
||||
use photocraft_ui_egui::{AppTray, TrayAction};
|
||||
use tray_icon::menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem};
|
||||
use tray_icon::{Icon, TrayIcon, TrayIconBuilder};
|
||||
|
||||
pub struct WindowsTray {
|
||||
actions: mpsc::Receiver<TrayAction>,
|
||||
icon: Option<(TrayIcon, MenuItem, String)>,
|
||||
}
|
||||
|
||||
impl WindowsTray {
|
||||
pub fn new(ctx: &egui::Context) -> Self {
|
||||
let (send, actions) = mpsc::channel();
|
||||
let ctx = ctx.clone();
|
||||
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
|
||||
let action = match event.id().as_ref() {
|
||||
"xiaoyi-tray-restore" => TrayAction::Restore,
|
||||
"xiaoyi-tray-exit" => TrayAction::Exit,
|
||||
_ => return,
|
||||
};
|
||||
if send.send(action).is_ok() {
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
}));
|
||||
Self { actions, icon: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl AppTray for WindowsTray {
|
||||
fn visible(&self) -> bool {
|
||||
self.icon.is_some()
|
||||
}
|
||||
|
||||
fn show(&mut self, status: &str) -> Result<(), String> {
|
||||
if self.icon.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let menu = Menu::new();
|
||||
let restore = MenuItem::with_id("xiaoyi-tray-restore", "显示主窗口", true, None);
|
||||
let summary = MenuItem::new(status, false, None);
|
||||
let exit = MenuItem::with_id("xiaoyi-tray-exit", "保存并退出小壹", true, None);
|
||||
menu.append_items(&[&restore, &summary, &PredefinedMenuItem::separator(), &exit])
|
||||
.map_err(|error| error.to_string())?;
|
||||
let brand = super::app_icon::window_icon();
|
||||
let icon = Icon::from_rgba(brand.rgba, brand.width, brand.height)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let tray = TrayIconBuilder::new().with_menu(Box::new(menu))
|
||||
.with_icon(icon).build().map_err(|error| error.to_string())?;
|
||||
// A tray window can exist while Explorer has yet to register the icon.
|
||||
tray.set_tooltip(Some(format!("小壹 · {status}"))).map_err(|error| error.to_string())?;
|
||||
self.icon = Some((tray, summary, status.to_owned()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn take_action(&mut self) -> Option<TrayAction> {
|
||||
let action = self.actions.try_iter().last()?;
|
||||
self.icon = None;
|
||||
Some(action)
|
||||
}
|
||||
|
||||
fn set_status(&mut self, status: &str) {
|
||||
if let Some((tray, item, previous)) = &mut self.icon
|
||||
&& previous != status
|
||||
{
|
||||
item.set_text(status);
|
||||
if let Err(error) = tray.set_tooltip(Some(format!("小壹 · {status}"))) {
|
||||
log::warn!("小壹托盘状态更新失败:{error}");
|
||||
}
|
||||
*previous = status.to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,373 +1,439 @@
|
||||
//! A single GUI-owned Node daemon. Messages remain scoped to one run.
|
||||
use photocraft_ui_egui::jiansun::BridgeFailure;
|
||||
use super::{json, R, Value, PathBuf, Arc, Path};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::{Mutex, OnceLock, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
enum KnowledgeEvent { Progress(Value), Result(R<Value>) }
|
||||
struct State {
|
||||
alive: bool,
|
||||
ready: bool,
|
||||
active: Option<(String, mpsc::Sender<Result<Value, BridgeFailure>>)>,
|
||||
knowledge: std::collections::HashMap<String, mpsc::Sender<KnowledgeEvent>>,
|
||||
broker_pid: Option<u32>,
|
||||
last_ack: Option<Instant>,
|
||||
last_sent: u64,
|
||||
last_acked: u64,
|
||||
}
|
||||
pub(super) struct Daemon {
|
||||
identity: (PathBuf, PathBuf, PathBuf, PathBuf, u32),
|
||||
child: Mutex<Child>,
|
||||
outbound: Mutex<Option<mpsc::Sender<Value>>>,
|
||||
state: Mutex<State>,
|
||||
pid: u32,
|
||||
}
|
||||
struct Registry { service: Option<Arc<Daemon>>, shutting_down: bool, spawn_count: u64 }
|
||||
impl Registry {
|
||||
fn new() -> Self { Self { service: None, shutting_down: false, spawn_count: 0 } }
|
||||
fn ensure_start_allowed(&self) -> R<()> {
|
||||
if self.shutting_down { return Err("本机Agent正在关闭,未启动新进程".into()); }
|
||||
Ok(())
|
||||
}
|
||||
fn mark_shutdown(&mut self) { self.shutting_down = true; }
|
||||
}
|
||||
static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
|
||||
fn registry() -> &'static Mutex<Registry> {
|
||||
REGISTRY.get_or_init(|| Mutex::new(Registry::new()))
|
||||
}
|
||||
impl Daemon {
|
||||
fn send(&self, value: &Value) -> R<()> {
|
||||
let output = self.outbound.lock().map_err(|_| "本机Agent连接不可用")?;
|
||||
output.as_ref().ok_or("本机Agent连接已关闭")?.send(value.clone()).map_err(|_| "本机Agent连接中断,原请求需核查".into())
|
||||
}
|
||||
pub(super) fn fail(&self) {
|
||||
if let Ok(mut state) = self.state.lock() {
|
||||
if !state.alive { return; }
|
||||
state.alive = false;
|
||||
for (_, sender) in state.knowledge.drain() { let _ = sender.send(KnowledgeEvent::Result(Err("企业知识库连接中断".into()))); }
|
||||
if let Some((_, sender)) = state.active.take() { let _ = sender.send(Err(BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true))); }
|
||||
}
|
||||
if let Ok(mut output) = self.outbound.lock() { output.take(); }
|
||||
if let Ok(mut child) = self.child.lock() {
|
||||
// Give the owned daemon its EOF cleanup path before killing it;
|
||||
// its cleanup also closes its own RPC child.
|
||||
let deadline = Instant::now() + Duration::from_millis(2500);
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(25)),
|
||||
_ => { let _ = child.kill(); let _ = child.wait(); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn handle(&self, value: Value) -> R<()> {
|
||||
let mut state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
match value["type"].as_str() {
|
||||
Some("ready") if !state.ready => {
|
||||
state.ready = true;
|
||||
state.last_ack = Some(Instant::now());
|
||||
}
|
||||
Some("heartbeat_ack") => {
|
||||
let id = value["id"].as_u64().ok_or("心跳响应无效")?;
|
||||
if id > state.last_sent || id <= state.last_acked { return Err("心跳身份无效".into()); }
|
||||
state.last_acked = id;
|
||||
state.last_ack = Some(Instant::now());
|
||||
state.broker_pid = match &value["brokerPid"] {
|
||||
Value::Null => None,
|
||||
number => Some(u32::try_from(number.as_u64().ok_or("模型桥身份无效")?).map_err(|_| "模型桥身份无效")?),
|
||||
};
|
||||
}
|
||||
Some("canvas" | "presentation" | "complete") if state.ready => {
|
||||
let (run, sender) = state.active.as_ref().ok_or("本机Agent收到无主回合消息")?;
|
||||
if value["runId"].as_str() != Some(run.as_str()) { return Err("本机Agent回合身份不一致".into()); }
|
||||
sender.send(Ok(value)).map_err(|_| "原回合已关闭")?;
|
||||
}
|
||||
Some("knowledge_progress") if state.ready => {
|
||||
if let Some(sender) = value["id"].as_str().and_then(|id| state.knowledge.get(id)) {
|
||||
let _ = sender.send(KnowledgeEvent::Progress(value["value"].clone()));
|
||||
}
|
||||
}
|
||||
Some("knowledge_result") if state.ready => {
|
||||
if let Some(sender) = value["id"].as_str().and_then(|id| state.knowledge.remove(id)) {
|
||||
let result = value["error"].as_str().map_or_else(|| Ok(value["value"].clone()), |error| Err(error.to_owned()));
|
||||
let _ = sender.send(KnowledgeEvent::Result(result));
|
||||
}
|
||||
}
|
||||
_ => return Err("本机Agent帧无效".into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn wait_ready(&self) -> R<()> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
if !state.alive { return Err("本机Agent启动失败,未派发模型".into()); }
|
||||
if state.ready { return Ok(()); }
|
||||
drop(state);
|
||||
if start.elapsed() >= Duration::from_secs(5) { self.fail(); return Err("本机Agent启动超时,未派发模型".into()); }
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
pub(super) fn begin(&self, run: &str, config: &Value) -> Result<mpsc::Receiver<Result<Value, BridgeFailure>>, BridgeFailure> {
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
{
|
||||
let mut state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
if !state.alive || !state.ready { return Err(BridgeFailure::interrupted("本机Agent不可用,未重发", false)); }
|
||||
if state.active.is_some() { return Err("原Agent回合仍在处理".into()); }
|
||||
state.active = Some((run.to_owned(), sender));
|
||||
}
|
||||
if let Err(error) = self.send(&json!({"type":"run","runId":run,"config":config})) { self.fail(); return Err(BridgeFailure::interrupted(error, false)); }
|
||||
Ok(receiver)
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(super) fn knowledge(&self, input: Value) -> R<Value> {
|
||||
self.knowledge_with_progress(input, |_| {})
|
||||
}
|
||||
pub(super) fn knowledge_with_progress(&self, input: Value, mut progress: impl FnMut(Value)) -> R<Value> {
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
{
|
||||
let mut state = self.state.lock().map_err(|_| "企业知识库连接不可用")?;
|
||||
if !state.alive || !state.ready { return Err("企业知识库连接已关闭".into()); }
|
||||
state.knowledge.insert(id.clone(), sender);
|
||||
}
|
||||
let result = self.send(&json!({"type":"knowledge","id":id,"input":input})).and_then(|_| {
|
||||
progress(json!({"jobId":id,"phase":"metadata"}));
|
||||
let mut deadline = Instant::now() + Duration::from_secs(300);
|
||||
loop {
|
||||
match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
|
||||
Ok(KnowledgeEvent::Progress(mut value)) => {
|
||||
let retry = value["retryAfterSeconds"].as_u64().unwrap_or(0).min(86_400);
|
||||
deadline = Instant::now() + Duration::from_secs(retry + 300);
|
||||
value["jobId"] = json!(id);
|
||||
progress(value);
|
||||
}
|
||||
Ok(KnowledgeEvent::Result(result)) => break result,
|
||||
Err(_) => { let _ = self.cancel_knowledge(&id); break Err("模板读取超时,请重试;已下载内容保留".into()); }
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Ok(mut state) = self.state.lock() { state.knowledge.remove(&id); }
|
||||
result
|
||||
}
|
||||
fn cancel_knowledge(&self, id: &str) -> R<()> {
|
||||
let sender = self.state.lock().map_err(|_| "企业知识库连接不可用")?.knowledge.remove(id);
|
||||
if let Some(sender) = sender {
|
||||
self.send(&json!({"type":"knowledge_cancel","id":id}))?;
|
||||
let _ = sender.send(KnowledgeEvent::Result(Err("已取消模板读取,已下载内容保留".into())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn reply(&self, run: &str, id: &Value, reply: &Value) -> R<()> {
|
||||
let state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
if !state.alive || state.active.as_ref().is_none_or(|(current, _)| current != run) { return Err("原Agent回合已关闭".into()); }
|
||||
drop(state);
|
||||
let mut frame = json!({"type":"canvas_result","runId":run,"id":id});
|
||||
if let Some(error) = reply.get("error") { frame["error"] = error.clone(); } else { frame["value"] = reply["value"].clone(); }
|
||||
if let Err(error) = self.send(&frame) { self.fail(); return Err(error); }
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn end(&self, run: &str) {
|
||||
if let Ok(mut state) = self.state.lock() && state.active.as_ref().is_some_and(|(current, _)| current == run) { state.active = None; }
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cancel_knowledge(id: &str) -> R<()> {
|
||||
uuid::Uuid::parse_str(id).map_err(|_| "模板读取编号无效")?;
|
||||
let service = registry().lock().map_err(|_| "企业知识库连接不可用")?.service.clone();
|
||||
if let Some(service) = service { service.cancel_knowledge(id)?; }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_writer(daemon: &Arc<Daemon>, mut input: ChildStdin, messages: mpsc::Receiver<Value>) {
|
||||
let owner = Arc::downgrade(daemon);
|
||||
std::thread::spawn(move || {
|
||||
let mut write_failed = false;
|
||||
while let Ok(value) = messages.recv() {
|
||||
if owner.upgrade().is_none_or(|daemon| daemon.state.lock().map_or(true, |state| !state.alive)) { break; }
|
||||
if writeln!(input, "{value}").and_then(|_| input.flush()).is_err() {
|
||||
write_failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Deliver EOF before waiting for the daemon's own child cleanup.
|
||||
drop(input);
|
||||
if write_failed && let Some(owner) = owner.upgrade() { owner.fail(); }
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path) -> Result<Arc<Daemon>, BridgeFailure> {
|
||||
let identity = (node.to_owned(), script.to_owned(), binary.to_owned(), profile.to_owned(), std::process::id());
|
||||
let mut registry = registry().lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
registry.ensure_start_allowed()?;
|
||||
if let Some(existing) = registry.service.clone() {
|
||||
if existing.identity != identity { return Err("本机Agent运行身份已改变".into()); }
|
||||
let alive = existing.state.lock().map_err(|_| "本机Agent状态不可用")?.alive;
|
||||
if alive { drop(registry); existing.wait_ready()?; return Ok(existing); }
|
||||
if existing.child.lock().map_err(|_| "本机Agent状态不可用")?
|
||||
.try_wait().map_err(|_| "本机Agent退出状态不可用")?.is_none()
|
||||
{
|
||||
return Err(BridgeFailure::interrupted("本机Agent正在退出,稍后接续", false));
|
||||
}
|
||||
registry.service = None;
|
||||
}
|
||||
let mut command = Command::new(node);
|
||||
command.arg(script).arg("--daemon").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).env_remove("NODE_OPTIONS").env_remove("NODE_PATH");
|
||||
#[cfg(windows)]
|
||||
{ use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); }
|
||||
let mut child = command.spawn().map_err(|_| "本机Agent无法启动,未派发模型")?;
|
||||
registry.spawn_count += 1;
|
||||
let pid = child.id();
|
||||
let Some(stdin) = child.stdin.take() else {
|
||||
let _ = child.kill(); let _ = child.wait();
|
||||
return Err("本机Agent输入不可用".into());
|
||||
};
|
||||
let Some(stdout) = child.stdout.take() else {
|
||||
drop(stdin); let _ = child.kill(); let _ = child.wait();
|
||||
return Err("本机Agent输出不可用".into());
|
||||
};
|
||||
let (output, messages) = mpsc::channel();
|
||||
let daemon = Arc::new(Daemon { identity, child: Mutex::new(child), outbound: Mutex::new(Some(output)), pid,
|
||||
state: Mutex::new(State { alive:true, ready:false, active:None, knowledge:Default::default(), broker_pid:None, last_ack:None, last_sent:0, last_acked:0 }) });
|
||||
spawn_writer(&daemon, stdin, messages);
|
||||
let reader_daemon = daemon.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut reader = BufReader::new(stdout);
|
||||
loop {
|
||||
let mut line = Vec::new();
|
||||
let read = reader.by_ref().take(2_000_001).read_until(b'\n', &mut line);
|
||||
if !matches!(read, Ok(n) if n > 0 && n <= 2_000_000 && line.last() == Some(&b'\n')) { break; }
|
||||
let Ok(value) = serde_json::from_slice::<Value>(&line) else { break };
|
||||
if let Err(reason) = reader_daemon.handle(value) {
|
||||
log::warn!("本机Agent消息处理停止:{reason}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
reader_daemon.fail();
|
||||
});
|
||||
let heartbeat = daemon.clone();
|
||||
std::thread::spawn(move || loop {
|
||||
let next = match heartbeat.state.lock() {
|
||||
Ok(state) if !state.alive => break,
|
||||
Ok(state) if state.last_ack.is_some_and(|last| last.elapsed() >= Duration::from_secs(10)) => None,
|
||||
Ok(mut state) => { state.last_sent += 1; Some(state.last_sent) },
|
||||
Err(_) => break,
|
||||
};
|
||||
let Some(id) = next else { heartbeat.fail(); break; };
|
||||
if heartbeat.send(&json!({"type":"heartbeat","id":id})).is_err() { heartbeat.fail(); break; }
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
});
|
||||
registry.service = Some(daemon.clone());
|
||||
drop(registry);
|
||||
daemon.wait_ready()?;
|
||||
Ok(daemon)
|
||||
}
|
||||
pub(super) fn status() -> Value {
|
||||
let Ok(registry) = registry().lock() else { return json!({"available":false}) };
|
||||
let Some(service) = ®istry.service else { return json!({"available":false,"pid":null,"brokerPid":null,"spawnCount":registry.spawn_count,"activeRun":null,"heartbeatAgeMs":null}) };
|
||||
let Ok(state) = service.state.lock() else { return json!({"available":false}) };
|
||||
json!({"available":state.alive && state.ready,"pid":service.pid,"brokerPid":state.broker_pid,"spawnCount":registry.spawn_count,
|
||||
"activeRun":state.active.as_ref().map(|(run,_)|run),"heartbeatAgeMs":state.last_ack.map(|at|at.elapsed().as_millis().min(u64::MAX as u128) as u64)})
|
||||
}
|
||||
|
||||
pub(super) fn pause_production(doc: u64, project_identity: &str) {
|
||||
let Some((account_identity, project)) = project_identity.rsplit_once('|') else { return; };
|
||||
let service = registry().lock().ok().and_then(|registry| registry.service.clone());
|
||||
if let Some(service) = service {
|
||||
let _ = service.send(&json!({"type":"production_pause","documentId":doc,"project":project,
|
||||
"scope":super::hash(account_identity)}));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn shutdown() {
|
||||
if let Ok(mut registry) = registry().lock() {
|
||||
registry.mark_shutdown();
|
||||
if let Some(service) = ®istry.service {
|
||||
if let Ok(mut state) = service.state.lock() {
|
||||
state.alive = false;
|
||||
for (_, sender) in state.knowledge.drain() { let _ = sender.send(KnowledgeEvent::Result(Err("客户端已关闭".into()))); }
|
||||
if let Some((_, sender)) = state.active.take() { let _ = sender.send(Err("本机Agent已关闭,原请求需核查".into())); }
|
||||
}
|
||||
if let Ok(mut output) = service.outbound.lock() { output.take(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shutdown_before_start_is_terminal_without_global_registry() {
|
||||
let mut local = Registry::new();
|
||||
assert!(local.ensure_start_allowed().is_ok());
|
||||
local.mark_shutdown();
|
||||
assert!(local.ensure_start_allowed().is_err());
|
||||
assert!(local.service.is_none());
|
||||
assert_eq!(local.spawn_count, 0);
|
||||
local.mark_shutdown();
|
||||
assert!(local.ensure_start_allowed().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_daemon_reuses_one_child_and_rejects_foreign_frames() {
|
||||
let script = r#"const rl=require('node:readline').createInterface({input:process.stdin});
|
||||
console.log(JSON.stringify({type:'ready'}));
|
||||
rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON.stringify({type:'presentation',runId:x.runId,action:'pi-delta'}));console.log(JSON.stringify({type:'complete',runId:x.runId,value:{ok:true}}));}if(x.type==='knowledge'){console.log(JSON.stringify({type:'knowledge_progress',id:x.id,value:{phase:'download',completed:1,fileCount:2}}));if(!x.input.slow)console.log(JSON.stringify({type:'knowledge_result',id:x.id,value:{ok:true}}));}});"#;
|
||||
let mut command = Command::new("node");
|
||||
command.args(["-e", script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{ use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); }
|
||||
let mut child = command.spawn().expect("synthetic Node fixture must be available");
|
||||
let pid = child.id();
|
||||
let stdin = child.stdin.take().unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (output, messages) = mpsc::channel();
|
||||
let daemon = Arc::new(Daemon { identity:(PathBuf::new(),PathBuf::new(),PathBuf::new(),PathBuf::new(),0),
|
||||
child:Mutex::new(child),outbound:Mutex::new(Some(output)),pid,
|
||||
state:Mutex::new(State { alive:true,ready:false,active:None,knowledge:Default::default(),broker_pid:None,last_ack:None,last_sent:0,last_acked:0 }) });
|
||||
spawn_writer(&daemon, stdin, messages);
|
||||
let handle = daemon.clone();
|
||||
let reader = std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let Ok(value) = serde_json::from_str::<Value>(&line) else { break };
|
||||
if handle.handle(value).is_err() { break; }
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !daemon.state.lock().unwrap().ready && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(10)); }
|
||||
assert!(daemon.state.lock().unwrap().ready);
|
||||
daemon.state.lock().unwrap().last_sent = 1;
|
||||
daemon.handle(json!({"type":"heartbeat_ack","id":1,"brokerPid":null})).unwrap();
|
||||
assert!(daemon.state.lock().unwrap().last_ack.is_some());
|
||||
assert!(daemon.handle(json!({"type":"heartbeat_ack","id":1,"brokerPid":null})).is_err());
|
||||
for run in ["run-one", "run-two"] {
|
||||
let receiver = daemon.begin(run, &json!({"mode":"fixture"})).unwrap();
|
||||
assert!(daemon.begin("overlap", &json!({})).is_err());
|
||||
assert!(daemon.handle(json!({"type":"complete","runId":"foreign","value":{}})).is_err());
|
||||
let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap();
|
||||
assert_eq!((frame["type"].as_str(), frame["runId"].as_str()), (Some("presentation"), Some(run)));
|
||||
let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap();
|
||||
assert_eq!((frame["type"].as_str(), frame["runId"].as_str()), (Some("complete"), Some(run)));
|
||||
assert_eq!(daemon.pid, pid);
|
||||
daemon.end(run);
|
||||
}
|
||||
let mut progress = Vec::new();
|
||||
assert_eq!(daemon.knowledge_with_progress(json!({}), |value| progress.push(value)).unwrap()["ok"], true);
|
||||
assert_eq!(progress.len(), 2);
|
||||
assert_eq!(progress[1]["completed"], 1);
|
||||
assert_eq!(progress[0]["jobId"], progress[1]["jobId"]);
|
||||
let result = daemon.knowledge_with_progress(json!({"slow":true}), |value| {
|
||||
if value["phase"] == "download" { daemon.cancel_knowledge(value["jobId"].as_str().unwrap()).unwrap(); }
|
||||
});
|
||||
assert!(result.unwrap_err().contains("已取消"));
|
||||
assert!(daemon.state.lock().unwrap().knowledge.is_empty());
|
||||
assert!(daemon.knowledge(json!({})).unwrap()["ok"] == true);
|
||||
daemon.fail();
|
||||
reader.join().unwrap();
|
||||
}
|
||||
}
|
||||
//! A single GUI-owned Node daemon. Messages remain scoped to one run.
|
||||
use photocraft_ui_egui::jiansun::BridgeFailure;
|
||||
use super::{json, R, Value, PathBuf, Arc, Path};
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::{Mutex, OnceLock, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
enum KnowledgeEvent { Progress(Value), Result(R<Value>) }
|
||||
type ExitReceipt = Box<dyn FnOnce(R<()>) + Send>;
|
||||
|
||||
struct State {
|
||||
alive: bool,
|
||||
ready: bool,
|
||||
active: Option<(String, mpsc::Sender<Result<Value, BridgeFailure>>)>,
|
||||
knowledge: std::collections::HashMap<String, mpsc::Sender<KnowledgeEvent>>,
|
||||
broker_pid: Option<u32>,
|
||||
last_ack: Option<Instant>,
|
||||
last_sent: u64,
|
||||
last_acked: u64,
|
||||
exiting: bool,
|
||||
exit_receipt: Option<ExitReceipt>,
|
||||
}
|
||||
pub(super) struct Daemon {
|
||||
identity: (PathBuf, PathBuf, PathBuf, PathBuf, u32),
|
||||
child: Mutex<Child>,
|
||||
outbound: Mutex<Option<mpsc::Sender<Value>>>,
|
||||
state: Mutex<State>,
|
||||
pid: u32,
|
||||
}
|
||||
struct Registry { service: Option<Arc<Daemon>>, shutting_down: bool, spawn_count: u64 }
|
||||
impl Registry {
|
||||
fn new() -> Self { Self { service: None, shutting_down: false, spawn_count: 0 } }
|
||||
fn ensure_start_allowed(&self) -> R<()> {
|
||||
if self.shutting_down { return Err("本机Agent正在关闭,未启动新进程".into()); }
|
||||
Ok(())
|
||||
}
|
||||
fn mark_shutdown(&mut self) { self.shutting_down = true; }
|
||||
}
|
||||
static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
|
||||
fn registry() -> &'static Mutex<Registry> {
|
||||
REGISTRY.get_or_init(|| Mutex::new(Registry::new()))
|
||||
}
|
||||
impl Daemon {
|
||||
fn send(&self, value: &Value) -> R<()> {
|
||||
let output = self.outbound.lock().map_err(|_| "本机Agent连接不可用")?;
|
||||
output.as_ref().ok_or("本机Agent连接已关闭")?.send(value.clone()).map_err(|_| "本机Agent连接中断,原请求需核查".into())
|
||||
}
|
||||
pub(super) fn fail(&self) {
|
||||
if let Ok(mut state) = self.state.lock() {
|
||||
if !state.alive { return; }
|
||||
state.alive = false;
|
||||
if let Some(receipt) = state.exit_receipt.take() { receipt(Err("本机Agent退出回执未确认".into())); }
|
||||
for (_, sender) in state.knowledge.drain() { let _ = sender.send(KnowledgeEvent::Result(Err("企业知识库连接中断".into()))); }
|
||||
if let Some((_, sender)) = state.active.take() { let _ = sender.send(Err(BridgeFailure::interrupted("本机Agent连接中断,原请求需核查", true))); }
|
||||
}
|
||||
if let Ok(mut output) = self.outbound.lock() { output.take(); }
|
||||
self.wait_for_exit();
|
||||
}
|
||||
fn wait_for_exit(&self) {
|
||||
if let Ok(mut child) = self.child.lock() {
|
||||
// Give the owned daemon its EOF cleanup path before killing it;
|
||||
// its cleanup also closes its own RPC child.
|
||||
let deadline = Instant::now() + Duration::from_millis(2500);
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => break,
|
||||
Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(25)),
|
||||
_ => { let _ = child.kill(); let _ = child.wait(); break; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn handle(&self, value: Value) -> R<()> {
|
||||
let mut state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
match value["type"].as_str() {
|
||||
Some("ready") if !state.ready => {
|
||||
state.ready = true;
|
||||
state.last_ack = Some(Instant::now());
|
||||
}
|
||||
Some("heartbeat_ack") => {
|
||||
let id = value["id"].as_u64().ok_or("心跳响应无效")?;
|
||||
if id > state.last_sent || id <= state.last_acked { return Err("心跳身份无效".into()); }
|
||||
state.last_acked = id;
|
||||
state.last_ack = Some(Instant::now());
|
||||
state.broker_pid = match &value["brokerPid"] {
|
||||
Value::Null => None,
|
||||
number => Some(u32::try_from(number.as_u64().ok_or("模型桥身份无效")?).map_err(|_| "模型桥身份无效")?),
|
||||
};
|
||||
}
|
||||
Some("exit_ready") if state.exiting => {
|
||||
if let Some(receipt) = state.exit_receipt.take() { receipt(Ok(())); }
|
||||
}
|
||||
Some("canvas" | "presentation" | "complete" | "auth_failure") if state.ready => {
|
||||
if state.exiting && state.active.is_none() { return Ok(()); }
|
||||
let (run, sender) = state.active.as_ref().ok_or("本机Agent收到无主回合消息")?;
|
||||
if value["runId"].as_str() != Some(run.as_str()) { return Err("本机Agent回合身份不一致".into()); }
|
||||
if sender.send(Ok(value)).is_err() && !state.exiting { return Err("原回合已关闭".into()); }
|
||||
}
|
||||
Some("knowledge_progress") if state.ready => {
|
||||
if let Some(sender) = value["id"].as_str().and_then(|id| state.knowledge.get(id)) {
|
||||
let _ = sender.send(KnowledgeEvent::Progress(value["value"].clone()));
|
||||
}
|
||||
}
|
||||
Some("knowledge_result") if state.ready => {
|
||||
if let Some(sender) = value["id"].as_str().and_then(|id| state.knowledge.remove(id)) {
|
||||
let result = value["error"].as_str().map_or_else(|| Ok(value["value"].clone()), |error| Err(error.to_owned()));
|
||||
let _ = sender.send(KnowledgeEvent::Result(result));
|
||||
}
|
||||
}
|
||||
_ => return Err("本机Agent帧无效".into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn wait_ready(&self) -> R<()> {
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
let state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
if !state.alive { return Err("本机Agent启动失败,未派发模型".into()); }
|
||||
if state.ready { return Ok(()); }
|
||||
drop(state);
|
||||
if start.elapsed() >= Duration::from_secs(5) { self.fail(); return Err("本机Agent启动超时,未派发模型".into()); }
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
pub(super) fn begin(&self, run: &str, config: &Value) -> Result<mpsc::Receiver<Result<Value, BridgeFailure>>, BridgeFailure> {
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let sent = {
|
||||
let mut state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
if state.exiting { return Err(BridgeFailure::new("cancelled", false, false, "客户端正在退出,未派发新任务")); }
|
||||
if !state.alive || !state.ready { return Err(BridgeFailure::interrupted("本机Agent不可用,未重发", false)); }
|
||||
if state.active.is_some() { return Err("原Agent回合仍在处理".into()); }
|
||||
state.active = Some((run.to_owned(), sender));
|
||||
self.send(&json!({"type":"run","runId":run,"config":config}))
|
||||
};
|
||||
if let Err(error) = sent { self.fail(); return Err(BridgeFailure::interrupted(error, false)); }
|
||||
Ok(receiver)
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(super) fn knowledge(&self, input: Value) -> R<Value> {
|
||||
self.knowledge_with_progress(input, |_| {})
|
||||
}
|
||||
pub(super) fn knowledge_with_progress(&self, input: Value, mut progress: impl FnMut(Value)) -> R<Value> {
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
{
|
||||
let mut state = self.state.lock().map_err(|_| "企业知识库连接不可用")?;
|
||||
if !state.alive || !state.ready || state.exiting { return Err("企业知识库连接已关闭".into()); }
|
||||
state.knowledge.insert(id.clone(), sender);
|
||||
if let Err(error) = self.send(&json!({"type":"knowledge","id":id,"input":input})) {
|
||||
state.knowledge.remove(&id);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
let result = {
|
||||
progress(json!({"jobId":id,"phase":"metadata"}));
|
||||
let mut deadline = Instant::now() + Duration::from_secs(300);
|
||||
loop {
|
||||
match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
|
||||
Ok(KnowledgeEvent::Progress(mut value)) => {
|
||||
let retry = value["retryAfterSeconds"].as_u64().unwrap_or(0).min(86_400);
|
||||
deadline = Instant::now() + Duration::from_secs(retry + 300);
|
||||
value["jobId"] = json!(id);
|
||||
progress(value);
|
||||
}
|
||||
Ok(KnowledgeEvent::Result(result)) => break result,
|
||||
Err(_) => { let _ = self.cancel_knowledge(&id); break Err("模板读取超时,请重试;已下载内容保留".into()); }
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Ok(mut state) = self.state.lock() { state.knowledge.remove(&id); }
|
||||
result
|
||||
}
|
||||
fn cancel_knowledge(&self, id: &str) -> R<()> {
|
||||
let sender = self.state.lock().map_err(|_| "企业知识库连接不可用")?.knowledge.remove(id);
|
||||
if let Some(sender) = sender {
|
||||
self.send(&json!({"type":"knowledge_cancel","id":id}))?;
|
||||
let _ = sender.send(KnowledgeEvent::Result(Err("已取消模板读取,已下载内容保留".into())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn canvas_accepted(&self, run: &str, id: &Value) -> R<()> {
|
||||
self.send(&json!({"type":"canvas_accepted","runId":run,"id":id}))
|
||||
}
|
||||
|
||||
pub(super) fn reply(&self, run: &str, id: &Value, reply: &Value) -> R<()> {
|
||||
let state = self.state.lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
if !state.alive || state.active.as_ref().is_none_or(|(current, _)| current != run) { return Err("原Agent回合已关闭".into()); }
|
||||
drop(state);
|
||||
let mut frame = json!({"type":"canvas_result","runId":run,"id":id});
|
||||
if let Some(error) = reply.get("error") { frame["error"] = error.clone(); } else { frame["value"] = reply["value"].clone(); }
|
||||
if let Err(error) = self.send(&frame) { self.fail(); return Err(error); }
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn end(&self, run: &str) {
|
||||
if let Ok(mut state) = self.state.lock() && state.active.as_ref().is_some_and(|(current, _)| current == run) { state.active = None; }
|
||||
}
|
||||
|
||||
fn prepare_exit(&self, receipt: ExitReceipt) {
|
||||
match self.state.lock() {
|
||||
Ok(mut state) if state.alive => {
|
||||
state.exiting = true;
|
||||
match self.send(&json!({"type":"prepare_exit"})) {
|
||||
Ok(()) => state.exit_receipt = Some(receipt),
|
||||
Err(error) => receipt(Err(error)),
|
||||
}
|
||||
}
|
||||
// A dead daemon cannot admit work. Recovery reads its persistent journals.
|
||||
Ok(_) => receipt(Ok(())),
|
||||
Err(_) => receipt(Err("本机Agent状态不可用".into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cancel_knowledge(id: &str) -> R<()> {
|
||||
uuid::Uuid::parse_str(id).map_err(|_| "模板读取编号无效")?;
|
||||
let service = registry().lock().map_err(|_| "企业知识库连接不可用")?.service.clone();
|
||||
if let Some(service) = service { service.cancel_knowledge(id)?; }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_writer(daemon: &Arc<Daemon>, mut input: ChildStdin, messages: mpsc::Receiver<Value>) {
|
||||
let owner = Arc::downgrade(daemon);
|
||||
std::thread::spawn(move || {
|
||||
let mut write_failed = false;
|
||||
while let Ok(value) = messages.recv() {
|
||||
if owner.upgrade().is_none_or(|daemon| daemon.state.lock().map_or(true, |state| !state.alive)) { break; }
|
||||
if writeln!(input, "{value}").and_then(|_| input.flush()).is_err() {
|
||||
write_failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Deliver EOF before waiting for the daemon's own child cleanup.
|
||||
drop(input);
|
||||
if write_failed && let Some(owner) = owner.upgrade() { owner.fail(); }
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn service(node: &Path, script: &Path, binary: &Path, profile: &Path) -> Result<Arc<Daemon>, BridgeFailure> {
|
||||
let identity = (node.to_owned(), script.to_owned(), binary.to_owned(), profile.to_owned(), std::process::id());
|
||||
let mut registry = registry().lock().map_err(|_| "本机Agent状态不可用")?;
|
||||
registry.ensure_start_allowed()?;
|
||||
if let Some(existing) = registry.service.clone() {
|
||||
if existing.identity != identity { return Err("本机Agent运行身份已改变".into()); }
|
||||
let alive = existing.state.lock().map_err(|_| "本机Agent状态不可用")?.alive;
|
||||
if alive { drop(registry); existing.wait_ready()?; return Ok(existing); }
|
||||
if existing.child.lock().map_err(|_| "本机Agent状态不可用")?
|
||||
.try_wait().map_err(|_| "本机Agent退出状态不可用")?.is_none()
|
||||
{
|
||||
return Err(BridgeFailure::interrupted("本机Agent正在退出,稍后接续", false));
|
||||
}
|
||||
registry.service = None;
|
||||
}
|
||||
let mut command = Command::new(node);
|
||||
command.arg(script).arg("--daemon").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).env_remove("NODE_OPTIONS").env_remove("NODE_PATH");
|
||||
#[cfg(windows)]
|
||||
{ use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); }
|
||||
let mut child = command.spawn().map_err(|_| "本机Agent无法启动,未派发模型")?;
|
||||
registry.spawn_count += 1;
|
||||
let pid = child.id();
|
||||
let Some(stdin) = child.stdin.take() else {
|
||||
let _ = child.kill(); let _ = child.wait();
|
||||
return Err("本机Agent输入不可用".into());
|
||||
};
|
||||
let Some(stdout) = child.stdout.take() else {
|
||||
drop(stdin); let _ = child.kill(); let _ = child.wait();
|
||||
return Err("本机Agent输出不可用".into());
|
||||
};
|
||||
let (output, messages) = mpsc::channel();
|
||||
let daemon = Arc::new(Daemon { identity, child: Mutex::new(child), outbound: Mutex::new(Some(output)), pid,
|
||||
state: Mutex::new(State { alive:true, ready:false, active:None, knowledge:Default::default(), broker_pid:None, last_ack:None, last_sent:0, last_acked:0,
|
||||
exiting:false, exit_receipt:None }) });
|
||||
spawn_writer(&daemon, stdin, messages);
|
||||
let reader_daemon = daemon.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut reader = BufReader::new(stdout);
|
||||
loop {
|
||||
let mut line = Vec::new();
|
||||
let read = reader.by_ref().take(2_000_001).read_until(b'\n', &mut line);
|
||||
if !matches!(read, Ok(n) if n > 0 && n <= 2_000_000 && line.last() == Some(&b'\n')) { break; }
|
||||
let Ok(value) = serde_json::from_slice::<Value>(&line) else { break };
|
||||
if let Err(reason) = reader_daemon.handle(value) {
|
||||
log::warn!("本机Agent消息处理停止:{reason}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
reader_daemon.fail();
|
||||
});
|
||||
let heartbeat = daemon.clone();
|
||||
std::thread::spawn(move || loop {
|
||||
let next = match heartbeat.state.lock() {
|
||||
Ok(state) if !state.alive => break,
|
||||
Ok(state) if state.last_ack.is_some_and(|last| last.elapsed() >= Duration::from_secs(10)) => None,
|
||||
Ok(mut state) => { state.last_sent += 1; Some(state.last_sent) },
|
||||
Err(_) => break,
|
||||
};
|
||||
let Some(id) = next else { heartbeat.fail(); break; };
|
||||
if heartbeat.send(&json!({"type":"heartbeat","id":id})).is_err() { heartbeat.fail(); break; }
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
});
|
||||
registry.service = Some(daemon.clone());
|
||||
drop(registry);
|
||||
daemon.wait_ready()?;
|
||||
Ok(daemon)
|
||||
}
|
||||
pub(super) fn status() -> Value {
|
||||
let Ok(registry) = registry().lock() else { return json!({"available":false}) };
|
||||
let Some(service) = ®istry.service else { return json!({"available":false,"pid":null,"brokerPid":null,"spawnCount":registry.spawn_count,"activeRun":null,"heartbeatAgeMs":null}) };
|
||||
let Ok(state) = service.state.lock() else { return json!({"available":false}) };
|
||||
json!({"available":state.alive && state.ready,"pid":service.pid,"brokerPid":state.broker_pid,"spawnCount":registry.spawn_count,
|
||||
"activeRun":state.active.as_ref().map(|(run,_)|run),"heartbeatAgeMs":state.last_ack.map(|at|at.elapsed().as_millis().min(u64::MAX as u128) as u64)})
|
||||
}
|
||||
|
||||
pub(super) fn pause_production(doc: u64, project_identity: &str, write_epoch: Option<u64>) {
|
||||
let Some((account_identity, project)) = project_identity.rsplit_once('|') else { return; };
|
||||
let service = registry().lock().ok().and_then(|registry| registry.service.clone());
|
||||
if let Some(service) = service {
|
||||
let _ = service.send(&json!({"type":"production_pause","documentId":doc,"project":project,
|
||||
"scope":super::hash(account_identity),"writeEpoch":write_epoch}));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prepare_exit(receipt: ExitReceipt) {
|
||||
let Ok(mut registry) = registry().lock() else { receipt(Err("本机Agent状态不可用".into())); return };
|
||||
registry.mark_shutdown();
|
||||
if let Some(service) = ®istry.service { service.prepare_exit(receipt); }
|
||||
else { receipt(Ok(())); }
|
||||
}
|
||||
|
||||
pub(super) fn cancel_exit() {
|
||||
let service = registry().lock().ok().and_then(|mut registry| {
|
||||
registry.shutting_down = false;
|
||||
registry.service.take()
|
||||
});
|
||||
if let Some(service) = service {
|
||||
std::thread::spawn(move || service.fail());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn revoke_scope(scope: &str, category: &str) {
|
||||
let service = registry().lock().ok().and_then(|registry| registry.service.clone());
|
||||
if let Some(service) = service {
|
||||
let _ = service.send(&json!({"type":"auth_revoke","scope":scope,"category":category}));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn shutdown() {
|
||||
let service = registry().lock().ok().and_then(|mut registry| {
|
||||
registry.mark_shutdown();
|
||||
registry.service.take()
|
||||
});
|
||||
if let Some(service) = service {
|
||||
service.fail();
|
||||
service.wait_for_exit();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shutdown_before_start_is_terminal_without_global_registry() {
|
||||
let mut local = Registry::new();
|
||||
assert!(local.ensure_start_allowed().is_ok());
|
||||
local.mark_shutdown();
|
||||
assert!(local.ensure_start_allowed().is_err());
|
||||
assert!(local.service.is_none());
|
||||
assert_eq!(local.spawn_count, 0);
|
||||
local.mark_shutdown();
|
||||
assert!(local.ensure_start_allowed().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_daemon_reuses_one_child_and_rejects_foreign_frames() {
|
||||
let script = r#"const rl=require('node:readline').createInterface({input:process.stdin});
|
||||
console.log(JSON.stringify({type:'ready'}));
|
||||
rl.on('line',line=>{if(JSON.parse(line).type==='prepare_exit')console.log(JSON.stringify({type:'exit_ready'}));});
|
||||
rl.on('line',line=>{const x=JSON.parse(line);if(x.type==='run'){console.log(JSON.stringify({type:'presentation',runId:x.runId,action:'pi-delta'}));console.log(JSON.stringify({type:'complete',runId:x.runId,value:{ok:true}}));}if(x.type==='knowledge'){console.log(JSON.stringify({type:'knowledge_progress',id:x.id,value:{phase:'download',completed:1,fileCount:2}}));if(!x.input.slow)console.log(JSON.stringify({type:'knowledge_result',id:x.id,value:{ok:true}}));}});"#;
|
||||
let mut command = Command::new("node");
|
||||
command.args(["-e", script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{ use std::os::windows::process::CommandExt; command.creation_flags(0x08000000); }
|
||||
let mut child = command.spawn().expect("synthetic Node fixture must be available");
|
||||
let pid = child.id();
|
||||
let stdin = child.stdin.take().unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (output, messages) = mpsc::channel();
|
||||
let daemon = Arc::new(Daemon { identity:(PathBuf::new(),PathBuf::new(),PathBuf::new(),PathBuf::new(),0),
|
||||
child:Mutex::new(child),outbound:Mutex::new(Some(output)),pid,
|
||||
state:Mutex::new(State { alive:true,ready:false,active:None,knowledge:Default::default(),broker_pid:None,last_ack:None,last_sent:0,last_acked:0,
|
||||
exiting:false,exit_receipt:None }) });
|
||||
spawn_writer(&daemon, stdin, messages);
|
||||
let handle = daemon.clone();
|
||||
let reader = std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let Ok(value) = serde_json::from_str::<Value>(&line) else { break };
|
||||
if handle.handle(value).is_err() { break; }
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !daemon.state.lock().unwrap().ready && Instant::now() < deadline { std::thread::sleep(Duration::from_millis(10)); }
|
||||
assert!(daemon.state.lock().unwrap().ready);
|
||||
daemon.state.lock().unwrap().last_sent = 1;
|
||||
daemon.handle(json!({"type":"heartbeat_ack","id":1,"brokerPid":null})).unwrap();
|
||||
assert!(daemon.state.lock().unwrap().last_ack.is_some());
|
||||
assert!(daemon.handle(json!({"type":"heartbeat_ack","id":1,"brokerPid":null})).is_err());
|
||||
for run in ["run-one", "run-two"] {
|
||||
let receiver = daemon.begin(run, &json!({"mode":"fixture"})).unwrap();
|
||||
assert!(daemon.begin("overlap", &json!({})).is_err());
|
||||
assert!(daemon.handle(json!({"type":"complete","runId":"foreign","value":{}})).is_err());
|
||||
let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap();
|
||||
assert_eq!((frame["type"].as_str(), frame["runId"].as_str()), (Some("presentation"), Some(run)));
|
||||
let frame = receiver.recv_timeout(Duration::from_secs(5)).unwrap().unwrap();
|
||||
assert_eq!((frame["type"].as_str(), frame["runId"].as_str()), (Some("complete"), Some(run)));
|
||||
assert_eq!(daemon.pid, pid);
|
||||
daemon.end(run);
|
||||
}
|
||||
let mut progress = Vec::new();
|
||||
assert_eq!(daemon.knowledge_with_progress(json!({}), |value| progress.push(value)).unwrap()["ok"], true);
|
||||
assert_eq!(progress.len(), 2);
|
||||
assert_eq!(progress[1]["completed"], 1);
|
||||
assert_eq!(progress[0]["jobId"], progress[1]["jobId"]);
|
||||
let result = daemon.knowledge_with_progress(json!({"slow":true}), |value| {
|
||||
if value["phase"] == "download" { daemon.cancel_knowledge(value["jobId"].as_str().unwrap()).unwrap(); }
|
||||
});
|
||||
assert!(result.unwrap_err().contains("已取消"));
|
||||
assert!(daemon.state.lock().unwrap().knowledge.is_empty());
|
||||
assert!(daemon.knowledge(json!({})).unwrap()["ok"] == true);
|
||||
let (send, receipt) = mpsc::channel();
|
||||
daemon.prepare_exit(Box::new(move |result| { send.send(result).unwrap(); }));
|
||||
assert!(!daemon.begin("after-exit", &json!({})).unwrap_err().dispatched);
|
||||
assert!(daemon.knowledge(json!({})).is_err());
|
||||
receipt.recv_timeout(Duration::from_secs(5)).unwrap().unwrap();
|
||||
daemon.fail();
|
||||
reader.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@ -86,8 +86,12 @@ pub fn start_agent_daemon() -> R<Value> {
|
||||
mod context_usage;
|
||||
#[path = "jiansun_prompt_library.rs"]
|
||||
mod prompt_library;
|
||||
#[path = "jiansun_delivery.rs"]
|
||||
mod delivery;
|
||||
#[path = "jiansun_project_file.rs"]
|
||||
mod project_file;
|
||||
#[path = "jiansun_transfer.rs"]
|
||||
pub(crate) mod transfer;
|
||||
#[path = "jiansun_projects.rs"]
|
||||
mod projects;
|
||||
#[path = "jiansun_reads.rs"]
|
||||
@ -261,6 +265,14 @@ fn write_json(path: &Path, v: &Value) -> R<()> {
|
||||
let bytes = serde_json::to_vec(v).map_err(|_| "项目记录无法保存")?;
|
||||
photocraft_format::atomic_write(path, &bytes).map_err(|_| "本机保存失败,请检查磁盘空间和目录权限".into())
|
||||
}
|
||||
|
||||
fn bind_execution_epoch(result: R<Value>, epoch: &Value) -> R<Value> {
|
||||
if !epoch.is_u64() { return result; }
|
||||
let mut value = result.unwrap_or_else(|error| json!({"executionError":error}));
|
||||
if value.is_null() { value = json!({}); }
|
||||
value["writeEpoch"] = epoch.clone();
|
||||
Ok(value)
|
||||
}
|
||||
fn project_not_trashed(dir: &Path) -> R<()> {
|
||||
if let (Some(account), Some(local)) = (dir.parent().and_then(Path::parent), dir.file_name())
|
||||
&& account.join("trash").join(local).exists()
|
||||
@ -391,6 +403,7 @@ struct Backend {
|
||||
http: NetworkClient,
|
||||
origin: String,
|
||||
auth: Value,
|
||||
access: AccountAccess,
|
||||
models: Vec<Value>,
|
||||
model: String,
|
||||
copy_models: Vec<Value>,
|
||||
@ -400,11 +413,58 @@ struct Backend {
|
||||
owners: HashMap<u64, String>,
|
||||
locations: HashMap<u64, String>,
|
||||
superseded_docs: Arc<std::sync::Mutex<std::collections::HashSet<u64>>>,
|
||||
last_saved: HashMap<u64, u64>,
|
||||
last_saved: HashMap<u64, (Value, u64)>,
|
||||
draft_zip_writer: Arc<std::sync::Mutex<Option<photocraft_format::PcraftWriter>>>,
|
||||
recovery_attempts: Arc<std::sync::Mutex<std::collections::HashSet<String>>>,
|
||||
recovery_serial: Arc<std::sync::Mutex<()>>,
|
||||
composer_store: Arc<draft_store::Store>,
|
||||
exit_admission_closed: Arc<std::sync::atomic::AtomicBool>,
|
||||
}
|
||||
|
||||
const AUTH_REVOKED: &str = "授权已失效,制作已暂停;请重新登录";
|
||||
const ACCOUNT_CHANGED: &str = "账户已改变,原项目和原请求已保留;请切回原账户";
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct AccountAccess {
|
||||
epoch: u64,
|
||||
current: Arc<std::sync::atomic::AtomicU64>,
|
||||
notifications: Option<(mpsc::Sender<Event>, egui::Context)>,
|
||||
dispatch_dir: Option<Arc<tempfile::TempDir>>,
|
||||
}
|
||||
|
||||
impl AccountAccess {
|
||||
fn check(&self) -> R<()> {
|
||||
use std::sync::atomic::Ordering::Acquire;
|
||||
if self.current.load(Acquire) == self.epoch && self.dispatch_path().is_none_or(|path| path.is_file()) {
|
||||
Ok(())
|
||||
} else { Err(AUTH_REVOKED.into()) }
|
||||
}
|
||||
|
||||
fn invalidate(&self) -> bool {
|
||||
use std::sync::atomic::Ordering::{AcqRel, Acquire};
|
||||
let changed = self.current.compare_exchange(self.epoch, self.epoch + 1, AcqRel, Acquire).is_ok();
|
||||
if changed && let Some(path) = self.dispatch_path() && fs::remove_file(path).is_err() {
|
||||
log::error!("无法清理已撤销的模型派发许可");
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn renew(&mut self) -> R<()> {
|
||||
use std::sync::atomic::Ordering::AcqRel;
|
||||
self.epoch = self.current.fetch_add(1, AcqRel) + 1;
|
||||
self.publish_dispatch()
|
||||
}
|
||||
|
||||
fn dispatch_path(&self) -> Option<PathBuf> {
|
||||
self.dispatch_dir.as_ref().map(|dir| dir.path().join(self.epoch.to_string()))
|
||||
}
|
||||
|
||||
fn publish_dispatch(&self) -> R<()> {
|
||||
if let Some(path) = self.dispatch_path() {
|
||||
fs::File::create_new(path).map_err(|_| "无法建立模型派发许可")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct PortalFailure {
|
||||
@ -444,6 +504,7 @@ impl Backend {
|
||||
http,
|
||||
origin,
|
||||
auth,
|
||||
access: Default::default(),
|
||||
models: vec![],
|
||||
model: String::new(),
|
||||
copy_models: vec![],
|
||||
@ -458,13 +519,53 @@ impl Backend {
|
||||
recovery_attempts: Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
|
||||
recovery_serial: Arc::new(std::sync::Mutex::new(())),
|
||||
composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
};
|
||||
backend.composer_store.activate(Some(backend.scope()))?;
|
||||
Ok(backend)
|
||||
}
|
||||
fn exiting(&self) -> bool {
|
||||
self.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
fn scope(&self) -> String {
|
||||
self.auth["account"]["id"].as_str().map(|id| hash(&format!("{}|{}", self.origin, id))).unwrap_or("guest".into())
|
||||
}
|
||||
fn revoke_access(&self, category: &str) {
|
||||
if self.access.invalidate() {
|
||||
let scope = self.scope();
|
||||
agent_daemon::revoke_scope(&scope, category);
|
||||
if let Some((events, ctx)) = &self.access.notifications {
|
||||
let _ = events.send(Event::Json("auth-fence".into(), Ok(json!({
|
||||
"accountId":self.auth["account"]["id"],"origin":self.origin,"category":category
|
||||
}))));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
fn check_dispatch(&self) -> R<()> { self.access.check() }
|
||||
|
||||
fn renew_portal_session(&mut self) -> Result<(), PortalFailure> {
|
||||
// Desktop grants are reissued through browser OAuth. Revalidate any
|
||||
// grant already renewed in the system vault under the same account.
|
||||
let account = self.auth["account"]["id"].clone();
|
||||
let renewed = vault(&format!("account:{}", hash(&self.origin))).ok()
|
||||
.and_then(|entry| entry.get_password().ok()).and_then(|text| serde_json::from_str::<Value>(&text).ok());
|
||||
let Some(renewed) = renewed.filter(|grant| !account.is_null() && grant["account"]["id"] == account
|
||||
&& grant["access_token"].is_string() && grant["access_token"] != self.auth["access_token"]) else {
|
||||
return Err(PortalFailure::http(401, None));
|
||||
};
|
||||
let previous = std::mem::replace(&mut self.auth, renewed);
|
||||
match self.portal_json("session") {
|
||||
Ok(value) if value["account"]["id"] == account => {
|
||||
self.auth["account"] = value["account"].clone();
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
self.auth = previous;
|
||||
Err(PortalFailure::http(401, None))
|
||||
}
|
||||
}
|
||||
}
|
||||
fn bind_composer_draft(&self, doc: u64, dir: &Path, meta: &mut Value) -> R<()> {
|
||||
let project = self.locations.get(&doc).ok_or("项目身份尚未绑定")?;
|
||||
let account = dir.parent().and_then(Path::parent).ok_or("项目路径无效")?;
|
||||
@ -500,6 +601,7 @@ impl Backend {
|
||||
.send()
|
||||
.map_err(|_| PortalFailure::local("unavailable", "素材库暂时无法连接,本机草稿已保留"))?;
|
||||
let status = r.status().as_u16();
|
||||
if status == 401 { self.revoke_access("auth_revoked"); }
|
||||
let (code, v) = body(r, MAX_JSON).map_err(|error| {
|
||||
if status != 200 {
|
||||
PortalFailure::http(status, None)
|
||||
@ -516,22 +618,36 @@ impl Backend {
|
||||
self.portal_json(path).map_err(|failure| failure.message)
|
||||
}
|
||||
fn validate_connection(&mut self) -> Result<(), PortalFailure> {
|
||||
let v = self.portal_json("session")?;
|
||||
let v = match self.portal_json("session") {
|
||||
Ok(value) => value,
|
||||
Err(failure) if failure.http_status == Some(401) => {
|
||||
self.revoke_access("auth_revoked");
|
||||
return self.renew_portal_session();
|
||||
}
|
||||
Err(failure) => return Err(failure),
|
||||
};
|
||||
if v["account"]["id"] != self.auth["account"]["id"] {
|
||||
self.revoke_access("scope_changed");
|
||||
return Err(PortalFailure::local("sign_in_required", "账户状态不一致,请重新授权"));
|
||||
}
|
||||
self.auth["account"] = v["account"].clone();
|
||||
Ok(())
|
||||
}
|
||||
fn validate(&mut self) -> R<()> {
|
||||
self.validate_connection().map_err(|failure| failure.message)
|
||||
self.check_dispatch()?;
|
||||
self.validate_connection().map_err(|failure| match failure.state {
|
||||
"sign_in_required" if failure.http_status == Some(401) => AUTH_REVOKED.into(),
|
||||
"sign_in_required" if failure.message == "账户状态不一致,请重新授权" => ACCOUNT_CHANGED.into(),
|
||||
_ => failure.message,
|
||||
})?;
|
||||
self.check_dispatch()
|
||||
}
|
||||
fn project_operation(&mut self, input: Value, busy: Arc<std::sync::atomic::AtomicBool>, events: &mpsc::Sender<Event>, ctx: &egui::Context) {
|
||||
use std::sync::atomic::Ordering;
|
||||
let operation = input["operation"].clone();
|
||||
if busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
|
||||
let _ = events.send(Event::Json("project-operation".into(), Ok(json!({"operation":operation,"error":"项目操作仍在处理,请稍后再试"}))));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return;
|
||||
}
|
||||
if let Some(id) = input["doc"].as_u64() { self.bind_new(id); }
|
||||
@ -555,7 +671,7 @@ impl Backend {
|
||||
};
|
||||
let _ = events.send(Event::Json("project-operation".into(), Ok(reply)));
|
||||
busy.store(false, Ordering::Release);
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
fn settings(&self) -> R<Value> {
|
||||
@ -750,12 +866,24 @@ impl Backend {
|
||||
}
|
||||
fn key_catalog(&self, key: &str) -> R<Vec<String>> {
|
||||
let response = self.http.get(format!("{UPSTREAM}/v1/models")).bearer_auth(key).send().map_err(|error| catalog_transport_error(&error))?;
|
||||
if response.status().as_u16() == 401 { return Err("个人Key校验失败(HTTP 401)".into()); }
|
||||
let (status, value) = body(response, MAX_JSON).map_err(|error| format!("98k模型目录读取失败:{error}"))?;
|
||||
if status != 200 {
|
||||
return Err(format!("个人Key校验失败(HTTP {status})"));
|
||||
}
|
||||
crate::jiansun_models::key_models(&value)
|
||||
}
|
||||
fn check_model_authority(&self, response: &Response, key: &str) -> R<()> {
|
||||
if response.status().as_u16() != 401 { return Ok(()); }
|
||||
self.revoke_access("auth_revoked");
|
||||
self.refresh_model_authority(key);
|
||||
Err(AUTH_REVOKED.into())
|
||||
}
|
||||
fn refresh_model_authority(&self, previous: &str) {
|
||||
let settings = self.settings().ok();
|
||||
let key = settings.as_ref().and_then(|value| value["key"].as_str()).unwrap_or(previous);
|
||||
let _ = self.key_catalog(key);
|
||||
}
|
||||
fn connection_data(&self, saved: &Value, available: Option<&[String]>) -> Value {
|
||||
let key_saved = saved["key"].as_str().is_some_and(|k| (12..=500).contains(&k.len()));
|
||||
let ready = |chosen: &Value, items: &[Value]| {
|
||||
@ -780,6 +908,7 @@ impl Backend {
|
||||
if !self.auth.is_null() {
|
||||
match self.validate_connection() {
|
||||
Ok(()) => {
|
||||
if self.check_dispatch().is_err() { self.access.renew()?; }
|
||||
library_status = "connected";
|
||||
library_http_status = Some(200);
|
||||
}
|
||||
@ -851,6 +980,7 @@ impl Backend {
|
||||
};
|
||||
let mut result = self.connection_data(&saved, available.as_deref());
|
||||
result["account"] = self.auth["account"].clone();
|
||||
result["accountEpoch"] = json!(self.access.epoch);
|
||||
result["origin"] = json!(self.origin);
|
||||
result["libraryStatus"] = json!(library_status);
|
||||
result["libraryHttpStatus"] = json!(library_http_status);
|
||||
@ -889,7 +1019,7 @@ impl Backend {
|
||||
("code_challenge_method", "S256"),
|
||||
]);
|
||||
let _ = tx.send(Event::Json("login-url".into(), Ok(json!(url.as_str()))));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
let deadline = Instant::now() + Duration::from_secs(300);
|
||||
while Instant::now() < deadline {
|
||||
match listener.accept() {
|
||||
@ -920,6 +1050,12 @@ impl Backend {
|
||||
return Err("素材库授权未完成".into());
|
||||
}
|
||||
vault(&format!("account:{}", hash(&origin)))?.set_password(&auth.to_string()).map_err(|_| "授权无法写入系统凭据库")?;
|
||||
if self.auth["access_token"] != auth["access_token"] || self.origin != origin {
|
||||
self.revoke_access(if self.origin != origin || self.auth["account"]["id"] != auth["account"]["id"] {
|
||||
"scope_changed"
|
||||
} else { "auth_revoked" });
|
||||
self.access.renew()?;
|
||||
}
|
||||
write_json(&self.root.join("settings.json"), &json!({"origin":origin}))?;
|
||||
self.origin = origin;
|
||||
self.auth = auth;
|
||||
@ -937,6 +1073,11 @@ impl Backend {
|
||||
fn bytes(&self, path: &str) -> R<Vec<u8>> {
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let r = self.http.get(format!("{}/api/desktop/{path}", self.origin)).bearer_auth(token).send().map_err(|_| "素材下载连接中断")?;
|
||||
if r.status().as_u16() == 401 {
|
||||
self.revoke_access("auth_revoked");
|
||||
let _ = self.clone().renew_portal_session();
|
||||
return Err(AUTH_REVOKED.into());
|
||||
}
|
||||
if !r.status().is_success() {
|
||||
return Err(format!("素材不可读取(HTTP {})", r.status().as_u16()));
|
||||
}
|
||||
@ -995,7 +1136,7 @@ impl Backend {
|
||||
if !canvas_workspace::save_edited_output(&dir, doc, &bytes)? {
|
||||
return Err("当前输出缺少原稿映射,未覆盖编辑稿".into());
|
||||
}
|
||||
Ok(json!({"productViewOnly":true}))
|
||||
Ok(json!({"productViewOnly":true,"documentKey":photocraft_ui_egui::jiansun::product_document_key(doc)}))
|
||||
}
|
||||
|
||||
fn save(&mut self, doc: Arc<Document>, revision: u64, meta: Value) -> R<Value> {
|
||||
@ -1019,10 +1160,11 @@ impl Backend {
|
||||
format!("画布缺少 {first} 至 {last} 的原稿图层,已保留上一次保存的画布")
|
||||
});
|
||||
let mut active_revision = Value::Null;
|
||||
if canvas_problem.is_none() && (activate_view || self.last_saved.get(&doc.id.0) != Some(&revision)) {
|
||||
let saved_identity = (photocraft_ui_egui::jiansun::product_document_key(&doc), revision);
|
||||
if canvas_problem.is_none() && (activate_view || self.last_saved.get(&doc.id.0) != Some(&saved_identity)) {
|
||||
if activate_view && meta["reuseSavedProductView"] == true && canvas_workspace::reuse_saved_product_view(&dir, &doc)? {
|
||||
active_revision = canvas_workspace::activate_edited_output(&dir, &doc)?["revision"].clone();
|
||||
self.last_saved.insert(doc.id.0, revision);
|
||||
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(|_| "草稿保存服务不可用,旧草稿已保留")?
|
||||
@ -1050,7 +1192,7 @@ impl Backend {
|
||||
log::info!("小壹画布保存 doc={} bytes={} serialize_ms={} write_ms={} shared_checkpoint={linked}",
|
||||
doc.id.0, bytes.len(), (write_started - serialize_started).as_millis(), write_started.elapsed().as_millis());
|
||||
}
|
||||
self.last_saved.insert(doc.id.0, revision);
|
||||
self.last_saved.insert(doc.id.0, saved_identity.clone());
|
||||
}
|
||||
}
|
||||
// UI snapshots may lag a completed sync or creation task. Preserve backend-owned
|
||||
@ -1075,12 +1217,19 @@ impl Backend {
|
||||
if !value["status"].is_string() || changed_revision || meta["syncDirty"] == true {
|
||||
value["status"] = json!("draft");
|
||||
}
|
||||
transfer::redact(&mut value);
|
||||
write_json(&dir.join("context.json"), &value)?;
|
||||
self.remember_project(project)?;
|
||||
let current_account = self.owners.get(&doc.id.0) == Some(&self.scope());
|
||||
if current_account { self.remember_project(project)?; }
|
||||
if let Some(reason) = canvas_problem { return Err(reason); }
|
||||
let mut receipt = json!({"time":value["time"],"localId":project,"status":value["status"],"project":value["project"],"cloudLink":value["project"],"syncedRevision":value["syncedRevision"],"syncDirty":value["syncDirty"],"projects":self.native_projects()?,"savedPath":dir.join("canvas.pcraft")});
|
||||
let mut receipt = json!({"time":value["time"],"localId":project,"status":value["status"],"project":value["project"],"cloudLink":value["project"],"syncedRevision":value["syncedRevision"],"syncDirty":value["syncDirty"],"savedPath":dir.join("canvas.pcraft"),
|
||||
"localSave":{"state":"saved","revision":revision,"path":dir.join("canvas.pcraft")}});
|
||||
receipt["documentKey"] = saved_identity.0;
|
||||
if activate_view { receipt["activeProductViewRevision"] = active_revision; }
|
||||
self.bind_composer_draft(doc.id.0, &dir, &mut receipt)?;
|
||||
if current_account {
|
||||
receipt["projects"] = json!(self.native_projects()?);
|
||||
self.bind_composer_draft(doc.id.0, &dir, &mut receipt)?;
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
fn deliver_project(&self, doc: &Document, revision: u64, options: &Value, receipt: &mut Value) -> R<()> {
|
||||
@ -1095,6 +1244,7 @@ impl Backend {
|
||||
let delivery = project_file::save(&dir, doc, options, scope, local, &mut state)?;
|
||||
write_json(&path, &state)?;
|
||||
receipt["projectFile"] = state["projectFile"].clone();
|
||||
if !delivery["localSave"].is_null() { receipt["localSave"] = delivery["localSave"].clone(); }
|
||||
receipt["deliveryError"] = delivery["outputError"].clone();
|
||||
receipt["delivered"] = delivery;
|
||||
Ok(())
|
||||
@ -1195,6 +1345,7 @@ impl Backend {
|
||||
if recover && task["keyFingerprint"].as_str().is_some_and(|fingerprint| fingerprint != hash(key)) {
|
||||
return Err("原请求属于另一把Key;请切回原Key只读核查,不会重发".into());
|
||||
}
|
||||
if !recover { transfer::redact(&mut task); }
|
||||
let response = if recover {
|
||||
let id = task["requestId"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("原请求没有可公开查询的编号;保持待核查,不会重发")?;
|
||||
self.http.get(format!("{UPSTREAM}/api/external/requests/{id}/result")).bearer_auth(key).send()
|
||||
@ -1210,6 +1361,8 @@ impl Backend {
|
||||
json!({"model":task["model"]["id"],"messages":[{"role":"system","content":system},{"role":"user","content":task["text"]}],"max_tokens":4096,"stream":true})
|
||||
};
|
||||
let invocation = pi_runtime::invocation(self, &task["model"])?;
|
||||
if self.exiting() { return Err("客户端正在退出,未派发新请求".into()); }
|
||||
self.check_dispatch()?;
|
||||
task["phase"] = json!("dispatched");
|
||||
write_json(&file, &task)?;
|
||||
let mut r = self
|
||||
@ -1225,6 +1378,7 @@ impl Backend {
|
||||
if task["model"]["protocol"] == "anthropic-messages" {
|
||||
r = r.header("Anthropic-Version", "2023-06-01");
|
||||
}
|
||||
if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); }
|
||||
r.send()
|
||||
};
|
||||
let result = (|| -> R<Value> {
|
||||
@ -1234,6 +1388,7 @@ impl Backend {
|
||||
write_json(&file, &task)?;
|
||||
}
|
||||
let status = response.status().as_u16();
|
||||
self.check_model_authority(&response, key)?;
|
||||
if status != 200 {
|
||||
return Err(format!("98k未返回可恢复的结果(HTTP {status}),不会重发"));
|
||||
}
|
||||
@ -1250,13 +1405,13 @@ impl Backend {
|
||||
let anthropic = task["model"]["protocol"] == "anthropic-messages";
|
||||
let mut v = if is_stream {
|
||||
let result = stream::read(response, anthropic, |content| {
|
||||
let text = stream::partial_reply(content);
|
||||
let text = transfer::redact_text(&stream::partial_reply(content));
|
||||
if !text.is_empty() && text != last_text {
|
||||
task["partialReply"] = json!(text);
|
||||
if last_emit.elapsed() >= Duration::from_millis(45) {
|
||||
let value = json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"taskId":task["id"],"text":text});
|
||||
let _ = tx.send(Event::Json("agent-stream".into(), Ok(value)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
updates = updates.saturating_add(1);
|
||||
last_text = text;
|
||||
last_emit = Instant::now();
|
||||
@ -1274,6 +1429,7 @@ impl Backend {
|
||||
} else {
|
||||
body(response, MAX_JSON)?.1
|
||||
};
|
||||
transfer::redact(&mut v);
|
||||
// Persist the actual completed response for this request before interpreting edits.
|
||||
task["response"] = v.clone();
|
||||
if recover {
|
||||
@ -1330,13 +1486,15 @@ impl Backend {
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.map_err(|_| "素材库暂时无法连接;尚未退出,原草稿已保留")?;
|
||||
if !r.status().is_success() {
|
||||
if !r.status().is_success() && r.status().as_u16() != 401 {
|
||||
return Err("授权撤销未完成,请稍后再试".into());
|
||||
}
|
||||
}
|
||||
self.revoke_access("scope_changed");
|
||||
vault(&format!("account:{}", hash(&self.origin)))?.delete_credential().map_err(|_| "本机授权清理未完成")?;
|
||||
self.composer_store.activate(None)?;
|
||||
self.auth = Value::Null;
|
||||
self.access.renew()?;
|
||||
self.models.clear();
|
||||
self.state()
|
||||
}
|
||||
@ -1404,12 +1562,26 @@ impl Backend {
|
||||
"draft" => self.draft(input["doc"].as_u64().ok_or("项目编号无效")?),
|
||||
"product-run-checkpoint" | "product-exit-checkpoint" => {
|
||||
let doc = input["doc"].as_u64().ok_or("项目编号无效")?;
|
||||
self.ensure_owner(doc)?;
|
||||
let checkpoint = &input["checkpoint"];
|
||||
if checkpoint["active"] == true {
|
||||
self.ensure_owner(doc)?;
|
||||
self.check_dispatch()?;
|
||||
}
|
||||
if self.locations.get(&doc).is_none_or(|project| checkpoint["project"] != *project) {
|
||||
return Err("制作任务属于其他项目".into());
|
||||
}
|
||||
write_json(&self.project_dir(doc)?.join("production-run.json"), checkpoint)?;
|
||||
let mut checkpoint = checkpoint.clone();
|
||||
transfer::redact(&mut checkpoint);
|
||||
let path = self.project_dir(doc)?.join("production-run.json");
|
||||
if method == "product-exit-checkpoint" && checkpoint["active"].is_null() {
|
||||
let mut saved = if path.is_file() { read_json(&path)? }
|
||||
else { json!({"active":false,"project":checkpoint["project"]}) };
|
||||
if saved["project"] != checkpoint["project"] { return Err("制作记录属于其他项目".into()); }
|
||||
saved["status"] = checkpoint["status"].clone();
|
||||
write_json(&path, &saved)?;
|
||||
} else {
|
||||
write_json(&path, &checkpoint)?;
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"pi-rules" => pi_runtime::rules(self, input),
|
||||
@ -1474,7 +1646,7 @@ impl Backend {
|
||||
&& meta["templateLayersRestored"].is_null() && meta["templateLayerProblem"].is_null()
|
||||
&& let Some(revision) = meta["revision"].as_u64()
|
||||
{
|
||||
self.last_saved.insert(doc.id.0, revision);
|
||||
self.last_saved.insert(doc.id.0, (photocraft_ui_egui::jiansun::product_document_key(&doc), revision));
|
||||
}
|
||||
meta["localId"] = json!(local);
|
||||
meta["autoResume"] = binding["autoResume"].clone();
|
||||
@ -1514,7 +1686,7 @@ impl Backend {
|
||||
progress["accountId"] = self.auth["account"]["id"].clone();
|
||||
progress["origin"] = json!(self.origin);
|
||||
let _ = tx.send(Event::Json("template-progress".into(), Ok(progress)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
let _guard = sync::context_guard();
|
||||
if sync::opened_copy_identity(&dir)? != open_identity {
|
||||
@ -1599,19 +1771,45 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let internal_requests = tx.clone();
|
||||
let composer_store = Arc::new(draft_store::Store::default());
|
||||
let backend_store = composer_store.clone();
|
||||
let account_epoch = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
let backend_epoch = account_epoch.clone();
|
||||
let mut workspace = Workspace::new(tx, results);
|
||||
workspace.account_epoch = Some(account_epoch);
|
||||
let exit_admission = workspace.exit_admission_closed.clone();
|
||||
let exit_ctx = ctx.clone();
|
||||
workspace.prepare_daemon_exit = Some(Box::new(move || {
|
||||
let (send, receive) = mpsc::channel();
|
||||
let exit_ctx = exit_ctx.clone();
|
||||
agent_daemon::prepare_exit(Box::new(move |result| {
|
||||
let _ = send.send(result);
|
||||
exit_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}));
|
||||
receive
|
||||
}));
|
||||
workspace.cancel_daemon_exit = Some(agent_daemon::cancel_exit);
|
||||
std::thread::spawn(move || {
|
||||
let mut backend = match Backend::new(root.join("jiansun")) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
let _ = events.send(Event::Json("restore".into(), Err(e)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let lease = tempfile::Builder::new().prefix("xiaoyi-account-").tempdir().map_err(|_| "无法建立模型派发目录".to_owned())
|
||||
.and_then(|dir| { backend.access.dispatch_dir = Some(Arc::new(dir)); backend.access.publish_dispatch() });
|
||||
if let Err(error) = lease {
|
||||
let _ = events.send(Event::Json("restore".into(), Err(error)));
|
||||
ctx.request_repaint();
|
||||
return;
|
||||
}
|
||||
backend.access.notifications = Some((events.clone(), ctx.clone()));
|
||||
backend.access.current = backend_epoch;
|
||||
backend.composer_store = backend_store;
|
||||
backend.exit_admission_closed = exit_admission;
|
||||
if let Err(error) = backend.composer_store.activate(Some(backend.scope())) {
|
||||
let _ = events.send(Event::Json("restore".into(), Err(error)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return;
|
||||
}
|
||||
let model_busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
@ -1629,7 +1827,26 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
std::thread::spawn(move || b.scan_recovery(&tx, &ctx));
|
||||
}
|
||||
for request in rx {
|
||||
if backend.exiting() && !matches!(&request, Request::Save(..) | Request::DeliverProductionBundle(..))
|
||||
&& !matches!(&request, Request::Action(method, _) if matches!(method.as_str(),
|
||||
"product-run-checkpoint" | "product-exit-checkpoint" | "slot-adopted"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match request {
|
||||
Request::DeliverProductionBundle(input, cancellation) => {
|
||||
let worker = backend.clone();
|
||||
let events = events.clone();
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let receipt = worker.deliver_bundle(&input, &cancellation)
|
||||
.unwrap_or_else(|error| json!({"state":"failed","error":transfer::redact_text(&error)}));
|
||||
let event = json!({"doc":input["doc"],"deliveryId":input["deliveryId"],
|
||||
"accountEpoch":input["accountEpoch"],"writeEpoch":input["writeEpoch"],"productionDelivery":receipt});
|
||||
let _ = events.send(Event::Json("production-deliver-bundle".into(), Ok(event)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
Request::OpenedResult { binding, result } => {
|
||||
let label = if binding["autoResume"] == true { "startup-open" } else { "open" };
|
||||
let adopted = result.and_then(|(doc, meta)| backend.accept_opened(&binding, doc, meta));
|
||||
@ -1654,7 +1871,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
std::thread::spawn(move || {
|
||||
let preview = worker.provisional_slot(doc, &input).ok().map(Box::new);
|
||||
let _ = events.send(Event::SlotPreview(input, preview));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
Request::Generate(doc, input) => {
|
||||
@ -1671,7 +1888,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let result = b.image_job(Some(doc), &input, false, &events, &ctx);
|
||||
let _ = events.send(Event::Json("image".into(), result));
|
||||
busy.store(false, Ordering::Release);
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -1686,30 +1903,43 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
Err(error) => Event::Json("slot-product-view-save".into(), Ok(json!({"doc":id,"revision":revision,"error":error}))),
|
||||
};
|
||||
let _ = task_events.send(event);
|
||||
task_ctx.request_repaint();
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
Request::Save(doc, revision, meta) => {
|
||||
let id = doc.id.0;
|
||||
let view_save = meta["activateProductView"] == true;
|
||||
let deliver = meta["deliverProject"].clone();
|
||||
let export = meta["exportProduct"].clone();
|
||||
let mut export = meta["exportProduct"].clone();
|
||||
pi_runtime::record_export_event(&backend, id, &export, "disk_persist", "save", "running", Value::Null);
|
||||
let event = match backend.save(doc.clone(), revision, meta) {
|
||||
Ok(mut value) if (export.is_object() || deliver.is_object()) && backend.exiting() => {
|
||||
let error = "客户端正在退出,未开始导出";
|
||||
if export.is_object() {
|
||||
let _ = events.send(Event::Json("slot-product-export".into(), Err(error.into())));
|
||||
} else {
|
||||
value["deliveryError"] = json!(error);
|
||||
}
|
||||
Event::Saved(id, revision, value)
|
||||
}
|
||||
Ok(value) if export.is_object() => {
|
||||
pi_runtime::record_export_event(&backend, id, &export, "disk_persist", "save", "completed", Value::Null);
|
||||
export["execution"]["recentDurableCommit"] = json!({"at":chrono::Utc::now().timestamp_millis(),"revision":revision});
|
||||
let _ = events.send(Event::Saved(id, revision, value));
|
||||
let worker = backend.clone();
|
||||
let events = events.clone();
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let result = worker.export_product_snapshot(&doc, &export);
|
||||
let result = bind_execution_epoch(worker.export_product_snapshot(&doc, &export), &export["writeEpoch"]);
|
||||
let _ = events.send(Event::Json("slot-product-export".into(), result));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Err(error) if export.is_object() => {
|
||||
pi_runtime::record_export_event(&backend, id, &export, "disk_persist", "save", "failed", Value::Null);
|
||||
let _ = events.send(Event::Json("save".into(), Err(error.clone())));
|
||||
Event::Json("slot-product-export".into(), Err(error))
|
||||
Event::Json("slot-product-export".into(), bind_execution_epoch(Err(error), &export["writeEpoch"]))
|
||||
}
|
||||
Ok(mut value) if deliver.is_object() => {
|
||||
let worker = backend.clone();
|
||||
@ -1720,7 +1950,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
value["deliveryError"] = json!(error);
|
||||
}
|
||||
let _ = events.send(Event::Saved(id, revision, value));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@ -1740,7 +1970,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let result = input["jobId"].as_str().ok_or_else(|| "模板读取编号缺失".to_owned())
|
||||
.and_then(agent_daemon::cancel_knowledge).map(|_| json!({"cancelled":true}));
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return true;
|
||||
}
|
||||
let handled_read = if matches!(method.as_str(), "prompt-library-list" | "prompt-library-edit" | "prompt-library-sync" | "project-list") {
|
||||
@ -1759,11 +1989,11 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
Ok(json!({"accountId":task_input["accountId"],"origin":task_input["origin"],"readId":task_input["readId"],"error":error}))
|
||||
});
|
||||
let _ = task_events.send(Event::Json(task_method, result));
|
||||
task_ctx.request_repaint();
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}).is_err() {
|
||||
let value = json!({"accountId":input["accountId"],"origin":input["origin"],"readId":input["readId"],"error":"提示库操作繁忙,请稍后再试;本机内容未更改"});
|
||||
let _ = events.send(Event::Json(method, Ok(value)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -1776,10 +2006,10 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
if let Err(error) = project_reads.submit(move || {
|
||||
let result = bound_material_read(reader.project_list(&input), &task_reference);
|
||||
let _ = task_events.send(Event::Json("project-list".into(), Ok(result)));
|
||||
task_ctx.request_repaint();
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}) {
|
||||
let _ = events.send(Event::Json("project-list".into(), Ok(bound_material_read(Err(error.into()), &reference))));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -1802,13 +2032,14 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
if method == "slot-product-view" {
|
||||
result = result.or_else(|error| Ok(json!({"productViewId":input["productViewId"],"error":error})));
|
||||
}
|
||||
result = bind_execution_epoch(result, &input["writeEpoch"]);
|
||||
let _ = task_events.send(Event::Json(method, result));
|
||||
task_ctx.request_repaint();
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
} else {
|
||||
let result = backend.slot_action(&method, &input, &events, &ctx);
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -1841,7 +2072,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
};
|
||||
let _ = task_events.send(Event::Json(task_method, result));
|
||||
}
|
||||
task_ctx.request_repaint();
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}) {
|
||||
let result = if matches!(method.as_str(), "materials" | "preview") {
|
||||
Ok(bound_material_read(Err(error.into()), &reference))
|
||||
@ -1851,13 +2082,13 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
Ok(value)
|
||||
};
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if matches!(method.as_str(), "project-sync" | "project-state" | "project-delete") && model_busy.load(std::sync::atomic::Ordering::Acquire) {
|
||||
let _ = events.send(Event::Json(method, Err("任务仍在运行,请等待完成或接手后再保存云端状态".into())));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return true;
|
||||
}
|
||||
if method == "slot-adopted" {
|
||||
@ -1868,7 +2099,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
// remain available while the owning Pi model lease is held.
|
||||
let result = backend.slot_action(&method, &input, &events, &ctx);
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
} else if method == "project-sync" {
|
||||
use std::sync::atomic::Ordering;
|
||||
if model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
|
||||
@ -1882,7 +2113,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let result = b.sync_project(&input);
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
busy.store(false, Ordering::Release);
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
} else if method.starts_with("slot-")
|
||||
@ -1923,7 +2154,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
};
|
||||
let _ = task_events.send(Event::Json(method, result));
|
||||
busy.store(false, Ordering::Release);
|
||||
task_ctx.request_repaint();
|
||||
task_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
} else if method.starts_with("creation-") {
|
||||
@ -1948,7 +2179,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
}
|
||||
};
|
||||
let _ = events.send(event);
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
} else if method == "agent-image-preview" {
|
||||
let reference_thumbnail = input["taskId"].as_str().is_some_and(images::reference_preview_id);
|
||||
@ -1973,7 +2204,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let updating = input["updateExisting"] == true;
|
||||
if updating && model_busy.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
|
||||
let _ = events.send(Event::Json(method, Err("任务仍在处理,请先保留原请求后读取新版".into())));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
return true;
|
||||
}
|
||||
let mut b = backend.clone();
|
||||
@ -1986,7 +2217,7 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
binding["openCopyIdentity"] = meta["openCopyIdentity"].clone();
|
||||
(Box::new(doc), meta)
|
||||
});
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
Request::OpenedResult { binding, result }
|
||||
});
|
||||
} else if method == "place" {
|
||||
@ -2008,10 +2239,9 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || b.scan_recovery(&tx, &ctx));
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
});
|
||||
let mut workspace = Workspace::new(tx, results);
|
||||
workspace.draft_flush = Some(Arc::new(move |token, text, primary, secondary, generation| composer_store.flush(token, text, primary, secondary, generation)));
|
||||
workspace.pause_production_agent = Some(agent_daemon::pause_production);
|
||||
workspace
|
||||
@ -2020,6 +2250,92 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn portal_401_revokes_running_workers_and_retains_the_paused_original_draft() {
|
||||
let site = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let origin = format!("http://{}", site.local_addr().unwrap());
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut socket, _) = site.accept().unwrap();
|
||||
let mut request = [0u8; 4096];
|
||||
let count = socket.read(&mut request).unwrap();
|
||||
assert!(String::from_utf8_lossy(&request[..count]).starts_with("GET /api/desktop/session "));
|
||||
let body = r#"{"message":"Authorization: Bearer reflected-test-secret"}"#;
|
||||
write!(socket, "HTTP/1.1 401 Unauthorized\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();
|
||||
});
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut backend = Backend::new(temp.path().to_owned()).unwrap();
|
||||
backend.origin = origin;
|
||||
backend.auth = json!({"account":{"id":"old-account"},"access_token":"original-test-credential"});
|
||||
backend.composer_store.activate(Some(backend.scope())).unwrap();
|
||||
let (events, observed) = mpsc::channel();
|
||||
let ctx = egui::Context::default();
|
||||
backend.access.notifications = Some((events.clone(), ctx.clone()));
|
||||
let mut engine = photocraft_engine::Session::new();
|
||||
engine.execute("file.new", json!({"name":"draft","width":40,"height":30})).unwrap();
|
||||
let doc = engine.active().unwrap().doc.clone();
|
||||
backend.save(doc.clone(), 1, json!({"composer":"未提交编辑"})).unwrap();
|
||||
let dir = backend.project_dir(doc.id.0).unwrap();
|
||||
let before = backend.clone();
|
||||
assert_eq!(backend.validate().unwrap_err(), AUTH_REVOKED);
|
||||
assert_eq!(before.check_dispatch().unwrap_err(), AUTH_REVOKED);
|
||||
assert_eq!(backend.validate().unwrap_err(), AUTH_REVOKED, "revoked lease blocks a second request");
|
||||
let Event::Json(name, Ok(value)) = observed.recv_timeout(Duration::from_secs(2)).unwrap() else { panic!("missing auth event"); };
|
||||
assert_eq!(name, "auth-fence");
|
||||
assert_eq!(value["category"], "auth_revoked");
|
||||
assert!(!value.to_string().contains("test-secret"));
|
||||
backend.action("product-run-checkpoint", &json!({"doc":doc.id.0,"checkpoint":{
|
||||
"project":backend.locations[&doc.id.0],"active":false,"phase":"paused","reason":"auth_revoked",
|
||||
"note":"Cookie: client=reflected-test-secret"
|
||||
}}), &events, &ctx).unwrap();
|
||||
assert_eq!(read_json(&dir.join("context.json")).unwrap()["composer"], "未提交编辑");
|
||||
let paused = read_json(&dir.join("production-run.json")).unwrap();
|
||||
assert_eq!(paused["phase"], "paused");
|
||||
assert!(!paused.to_string().contains("reflected-test-secret"));
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_switch_fences_old_dispatch_and_late_image_receipts_settle_in_the_original_project() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut backend = Backend::new(temp.path().to_owned()).unwrap();
|
||||
backend.auth = json!({"account":{"id":"old"}});
|
||||
backend.access.dispatch_dir = Some(Arc::new(tempfile::tempdir_in(temp.path()).unwrap()));
|
||||
backend.access.publish_dispatch().unwrap();
|
||||
backend.composer_store.activate(Some(backend.scope())).unwrap();
|
||||
let mut engine = photocraft_engine::Session::new();
|
||||
engine.execute("file.new", json!({"width":40,"height":30})).unwrap();
|
||||
let first = engine.active().unwrap().doc.clone();
|
||||
backend.save(first.clone(), 1, json!({"composer":"原账户"})).unwrap();
|
||||
let original = backend.clone();
|
||||
let old_lease = original.access.dispatch_path().unwrap();
|
||||
assert!(old_lease.is_file());
|
||||
let original_dir = original.project_dir(first.id.0).unwrap();
|
||||
let task = Uuid::new_v4().to_string();
|
||||
let artifact = original_dir.join("image-jobs").join(&task).join("generated.png");
|
||||
backend.revoke_access("scope_changed");
|
||||
backend.access.renew().unwrap();
|
||||
backend.auth = json!({"account":{"id":"new"}});
|
||||
backend.composer_store.activate(Some(backend.scope())).unwrap();
|
||||
engine.execute("file.new", json!({"width":40,"height":30})).unwrap();
|
||||
let second = engine.active().unwrap().doc.clone();
|
||||
backend.save(second.clone(), 1, json!({"composer":"新账户"})).unwrap();
|
||||
assert!(original.check_dispatch().is_err());
|
||||
assert!(!old_lease.exists());
|
||||
assert!(backend.access.dispatch_path().unwrap().is_file());
|
||||
assert!(backend.check_dispatch().is_ok());
|
||||
fs::create_dir_all(artifact.parent().unwrap()).unwrap();
|
||||
fs::write(&artifact, b"original candidate").unwrap();
|
||||
images::job_save(&original_dir, &json!({"id":task,"phase":"complete","artifact":artifact,
|
||||
"accountScope":original.scope(),"localProjectId":original.locations[&first.id.0]})).unwrap();
|
||||
backend.save(first, 2, json!({"composer":"迟到的原账户草稿"})).unwrap();
|
||||
let new_dir = backend.project_dir(second.id.0).unwrap();
|
||||
assert!(!new_dir.join("image-jobs").exists());
|
||||
assert_eq!(read_json(&original_dir.join("image-task.json")).unwrap()["accountScope"], original.scope());
|
||||
assert_eq!(read_json(&new_dir.join("context.json")).unwrap()["composer"], "新账户");
|
||||
assert_eq!(read_json(&backend.dir().join("last-project.json")).unwrap()["id"], backend.locations[&second.id.0]);
|
||||
assert_eq!(read_json(&original_dir.join("context.json")).unwrap()["composer"], "迟到的原账户草稿");
|
||||
}
|
||||
#[test]
|
||||
fn context_presence_survives_atomic_saves_and_rejects_removed_projects() {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@ -2319,6 +2635,8 @@ mod tests {
|
||||
recovery_attempts: Default::default(),
|
||||
recovery_serial: Default::default(),
|
||||
composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
access: Default::default(),
|
||||
};
|
||||
let first = b.scope();
|
||||
b.auth = json!({"account":{"id":"account-b"}});
|
||||
@ -2505,6 +2823,8 @@ mod tests {
|
||||
recovery_attempts: Default::default(),
|
||||
recovery_serial: Default::default(),
|
||||
composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
access: Default::default(),
|
||||
};
|
||||
b.composer_store.activate(Some(b.scope())).unwrap();
|
||||
b.bind_new(7);
|
||||
@ -2535,6 +2855,8 @@ mod tests {
|
||||
recovery_attempts: Default::default(),
|
||||
recovery_serial: Default::default(),
|
||||
composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
access: Default::default(),
|
||||
};
|
||||
first.composer_store.activate(Some(first.scope())).unwrap();
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
//! manufacture an AI plan. Original A/B files and image journals stay intact.
|
||||
use super::{json, Path, Value, R, Uuid, PathBuf, hash, original_project_present, read_json, template_slots, Digest, sync, write_json, fs, Sha256, creation, mpsc, Event, template_workflow, now, Document, Backend, production_profile, slot_canvas, Arc};
|
||||
use photocraft_ui_egui::jiansun::BridgeFailure;
|
||||
use super::transfer;
|
||||
|
||||
const FILE: &str = "canvas-workspace.json";
|
||||
const CANDIDATE: &str = "canvas-candidate.json";
|
||||
@ -798,6 +799,13 @@ fn lock_candidate_dispatch(dir: &Path, id: &str) -> R<Option<fs::File>> {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_image_dispatch_cancelled(cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<(), BridgeFailure> {
|
||||
if cancellation.is_some_and(|token| token.load(std::sync::atomic::Ordering::SeqCst)) {
|
||||
return Err(BridgeFailure::new("cancelled", false, false, "原制作回合已停止,生图未派发"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pending_candidate(record: &Value) -> Value {
|
||||
let mut pending = record.clone();
|
||||
pending["phase"] = json!("unknown");
|
||||
@ -1757,7 +1765,7 @@ impl Backend {
|
||||
let record = result?;
|
||||
if doc == source_doc {
|
||||
publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return Ok(candidate_receipt(&record));
|
||||
}
|
||||
@ -1765,7 +1773,7 @@ impl Backend {
|
||||
let receipt = retire_candidate(&dir, target, reason)?;
|
||||
if receipt["status"] == "retired" {
|
||||
publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return Ok(receipt);
|
||||
}
|
||||
@ -1781,7 +1789,7 @@ impl Backend {
|
||||
reference["purpose"] = json!("template-candidate");
|
||||
let _ = events.send(Event::Preview(reference, preview));
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
Ok(candidate_receipt(&record))
|
||||
}
|
||||
|
||||
@ -2158,10 +2166,35 @@ pub(super) fn activate_edited_output(dir: &Path, doc: &Document) -> R<Value> {
|
||||
persist_locked(dir, &mut state, expected)
|
||||
}
|
||||
|
||||
fn receipt_path(dir: &Path, variant: &str, component: &str) -> PathBuf {
|
||||
pub(super) fn receipt_path(dir: &Path, variant: &str, component: &str) -> PathBuf {
|
||||
dir.join("product-exports").join(variant).join(format!("{component}.json"))
|
||||
}
|
||||
|
||||
pub(super) fn manifest_path(generation: &str) -> PathBuf {
|
||||
Path::new("generations").join(generation).join("manifest.json")
|
||||
}
|
||||
|
||||
pub(super) fn published_receipt(path: &Path) -> R<Value> {
|
||||
let pointer = read_json(path)?;
|
||||
if pointer.get("publishedPointer").is_none() {
|
||||
return Ok(pointer);
|
||||
}
|
||||
let id = pointer["generationId"].as_str().ok_or("交付版本缺失")?;
|
||||
let manifest = manifest_path(id);
|
||||
if !id.starts_with("generation-") || Path::new(id).components().count() != 1
|
||||
|| pointer["publishedPointer"] != json!(manifest)
|
||||
{
|
||||
return Err("交付指针无效".into());
|
||||
}
|
||||
let manifest = read_json(&path.parent().ok_or("交付目录缺失")?.join(manifest))?;
|
||||
if ["generationId", "workspaceId", "outputId", "variantId"].iter()
|
||||
.any(|field| manifest[*field] != pointer[*field])
|
||||
{
|
||||
return Err("交付清单与发布指针不一致".into());
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
fn template_screen_regions<'a>(pages: impl IntoIterator<Item = &'a Value>) -> R<Vec<(u64, u64, u64)>> {
|
||||
let mut regions = Vec::new();
|
||||
for page in pages {
|
||||
@ -2308,7 +2341,7 @@ fn artifact_matches(artifact: &Value, verify_hash: bool) -> bool {
|
||||
&& (!verify_hash || file_digest(path).is_ok_and(|actual| actual == expected))
|
||||
}
|
||||
|
||||
fn file_digest(path: &Path) -> std::io::Result<String> {
|
||||
pub(super) fn file_digest(path: &Path) -> std::io::Result<String> {
|
||||
let mut file = fs::File::open(path)?;
|
||||
let mut sha = Sha256::new();
|
||||
std::io::copy(&mut file, &mut sha)?;
|
||||
@ -2381,7 +2414,7 @@ fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_ed
|
||||
production_stages(state).into_iter().filter(|stage| {
|
||||
let (Some(variant), Some(component)) = (stage["variantId"].as_str(), stage["outputId"].as_str()) else { return true };
|
||||
if !state["productTemplateIssues"][component].is_null() { return true; }
|
||||
let receipt = read_json(&receipt_path(dir,variant,component)).unwrap_or(Value::Null);
|
||||
let receipt = published_receipt(&receipt_path(dir,variant,component)).unwrap_or(Value::Null);
|
||||
let pack = &state["productTemplates"][component];
|
||||
let pages = pack["outputs"].as_array().into_iter().flatten().filter(|page| page["component"] == component);
|
||||
let Ok(regions) = product_export_regions(pages.clone(), component) else { return true };
|
||||
@ -2654,10 +2687,25 @@ pub(super) fn read_production_screen(native: &Document, input: &Value) -> R<Valu
|
||||
|
||||
impl Backend {
|
||||
pub(super) fn export_product_snapshot(&self, native: &Document, input: &Value) -> R<Value> {
|
||||
self.check_dispatch()?;
|
||||
self.ensure_owner(native.id.0)?;
|
||||
let dir = self.project_dir(native.id.0)?;
|
||||
let state = load(&dir)?;
|
||||
export_product_stage_snapshot(&dir, native.id.0, &state, input, &self.scope(), Some(native))
|
||||
let doc = native.id.0;
|
||||
super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "running", Value::Null);
|
||||
let result = export_product_stage_snapshot(&dir, doc, &state, input, &self.scope(), Some(native));
|
||||
match &result {
|
||||
Ok(value) if value["publishedPointer"].is_string() => {
|
||||
let progress = json!({"generationId":value["generationId"],"publishedPointer":value["publishedPointer"],
|
||||
"filesVerified":value["validation"]["filesVerified"],"sourceHash":value["sourceDocument"]["sha256"]});
|
||||
super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "completed",
|
||||
json!({"generationId":value["generationId"],"validation":value["validation"]}));
|
||||
super::pi_runtime::record_export_event(self, doc, input, "export", "publish", "completed", progress);
|
||||
}
|
||||
Ok(_) => super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "blocked", Value::Null),
|
||||
Err(_) => super::pi_runtime::record_export_event(self, doc, input, "export", "validate", "failed", Value::Null),
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@ -2665,7 +2713,42 @@ fn export_product_stage(dir: &Path, doc: u64, state: &Value, input: &Value, scop
|
||||
export_product_stage_snapshot(dir, doc, state, input, scope, None)
|
||||
}
|
||||
|
||||
fn publish_product_generation(
|
||||
pub(super) fn layered_format(bytes: &[u8]) -> R<&'static str> {
|
||||
match bytes.get(..6) {
|
||||
Some(b"8BPS\0\x01") => Ok("psd"),
|
||||
Some(b"8BPS\0\x02") => Ok("psb"),
|
||||
_ => Err("PSD / PSB 文件头无效".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn layered_size(name: &str, bytes: &[u8]) -> R<(u32, u32)> {
|
||||
let format = layered_format(bytes)?;
|
||||
if Path::new(name).extension().and_then(|ext| ext.to_str()) != Some(format) {
|
||||
return Err("分层文件扩展名与文件头不一致".into());
|
||||
}
|
||||
let imported = photocraft_io::import(name, bytes)
|
||||
.map_err(|error| format!("无法重开分层文件:{error}"))?;
|
||||
Ok((imported.document.size.width, imported.document.size.height))
|
||||
}
|
||||
|
||||
fn export_layered_document(dir: &Path, component: &str, generation: &str, doc: &Document) -> R<Value> {
|
||||
let exported = photocraft_io::export(doc, "psd", &Default::default())
|
||||
.map_err(|error| format!("分层文件导出失败:{error}"))?;
|
||||
let format = layered_format(&exported.bytes)?;
|
||||
let name = format!("{component}.{format}");
|
||||
let path = dir.join(&name);
|
||||
photocraft_format::atomic_write(&path, &exported.bytes)
|
||||
.map_err(|error| format!("分层文件写入失败:{error}"))?;
|
||||
let saved = fs::read(&path).map_err(|error| format!("分层文件读取失败:{error}"))?;
|
||||
if saved != exported.bytes || layered_size(&name, &saved)? != (doc.size.width, doc.size.height) {
|
||||
return Err("分层文件与本轮画布的内容或尺寸不一致".into());
|
||||
}
|
||||
Ok(json!({"path":path,"format":format,"role":"layered","generationId":generation,
|
||||
"width":doc.size.width,"height":doc.size.height,"sizeBytes":saved.len(),
|
||||
"sha256":format!("{:x}",Sha256::digest(&saved))}))
|
||||
}
|
||||
|
||||
pub(super) fn publish_product_generation(
|
||||
receipt: &Path, native: &Document, document_revision: &Value, result: &mut Value,
|
||||
regions: &[(u64, u64, u64)], screens: &[(u64, u64, u64)],
|
||||
) -> R<()> {
|
||||
@ -2684,6 +2767,8 @@ fn publish_product_generation(
|
||||
|| reopened.layer_count() != native.layer_count() || reopened.metadata.text != native.metadata.text {
|
||||
return Err("成品工程重开后与本轮画布的身份、图层或页面信息不一致".into());
|
||||
}
|
||||
super::transfer::check_pcraft_file(&editable)?;
|
||||
let layered = export_layered_document(generation.path(), component, id, &reopened)?;
|
||||
let exported_mapping = mapping(&reopened);
|
||||
let save_region = |name: &str, role: &str, (top, width, height): (u64, u64, u64), bytes: Vec<u8>| -> R<Value> {
|
||||
let file = generation.path().join(name);
|
||||
@ -2694,6 +2779,10 @@ fn publish_product_generation(
|
||||
{
|
||||
return Err(format!("{name} 内容或尺寸与导出结果不一致"));
|
||||
}
|
||||
#[cfg(test)]
|
||||
if std::env::var_os("PHOTOCRAFT_TEST_CRASH_EXPORT").as_deref() == Some(receipt.as_os_str()) {
|
||||
std::process::exit(81);
|
||||
}
|
||||
let mut artifact = json!({"path":file,"format":"jpg","role":role,"generationId":id,"top":top,"width":width,"height":height,
|
||||
"sizeBytes":saved.len(),"sha256":format!("{:x}",Sha256::digest(&saved))});
|
||||
if role != "detail"
|
||||
@ -2716,6 +2805,9 @@ fn publish_product_generation(
|
||||
photocraft_io::export_jpeg_with_screens(doc, &coordinates, &options)
|
||||
.map_err(|error| format!("长图和分屏导出失败:{error}"))
|
||||
})?;
|
||||
if splits.len() != screens.len() {
|
||||
return Err("导出的分屏数量与模板不一致".into());
|
||||
}
|
||||
let full = save_region("detail.jpg", component, *region, long.bytes)?;
|
||||
let split = screens.iter().zip(splits).enumerate().map(|(index, (®ion, image))|
|
||||
save_region(&format!("detail-S{:02}.jpg", index+1), "detail-screen", region, image.bytes))
|
||||
@ -2730,16 +2822,28 @@ fn publish_product_generation(
|
||||
};
|
||||
let size = fs::metadata(&editable).map_err(|error| format!("无法读取成品工程信息:{error}"))?.len();
|
||||
let sha = file_digest(&editable).map_err(|error| format!("无法核对成品工程内容:{error}"))?;
|
||||
let delivery = json!({"state":"output_exported","outputState":"exported","outputId":component,"generationId":id});
|
||||
result["generationId"] = json!(id);
|
||||
result["sourceDocument"] = json!({"path":editable,"format":"pcraft","role":"editable","generationId":id,
|
||||
"revision":document_revision,"reopened":true,"width":reopened.size.width,"height":reopened.size.height,
|
||||
"sizeBytes":size,"sha256":sha});
|
||||
result["layeredDocument"] = layered;
|
||||
result["files"] = json!(files);
|
||||
if !split.is_empty() { result["screenFiles"] = json!(split); }
|
||||
result["editable"] = json!(editable);
|
||||
let _guard = sync::context_guard();
|
||||
write_json(receipt, result)?;
|
||||
result["productionDelivery"] = delivery;
|
||||
result["validation"] = json!({"mode":"full","editableReopened":true,
|
||||
"filesVerified":2 + regions.len() + screens.len(),"validatedAt":chrono::Utc::now().timestamp_millis()});
|
||||
write_json(&generation.path().join("manifest.json"), result)?;
|
||||
// A replacement can report a directory flush error after the rename.
|
||||
// Keep the complete generation before attempting to publish its pointer.
|
||||
let pointer = manifest_path(id);
|
||||
let _ = generation.keep();
|
||||
use photocraft_format::atomic::{AtomicFs, RealFs};
|
||||
RealFs.sync_dir(&root).map_err(|error| format!("成品版本目录保存未确认:{error}"))?;
|
||||
let _guard = sync::context_guard();
|
||||
result["publishedPointer"] = json!(pointer);
|
||||
write_json(receipt, result)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -2747,12 +2851,31 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
let component = input["outputId"].as_str().filter(|kind| PRODUCTION_OUTPUTS.contains(kind)).ok_or("制作输出缺失")?;
|
||||
let variant_id = uuid(&input["variantId"], "制作款式")?;
|
||||
if !state["productTemplates"].is_object() || input["workspaceId"] != state["id"]
|
||||
|| input["outputId"] != state["activeOutput"] || input["variantId"] != state["activeVariantId"]
|
||||
|| (snapshot.is_none() && read_json(&dir.join("context.json"))?["revision"] != input["baseRevision"]) {
|
||||
|| (snapshot.is_none() && (input["outputId"] != state["activeOutput"]
|
||||
|| input["variantId"] != state["activeVariantId"]
|
||||
|| read_json(&dir.join("context.json"))?["revision"] != input["baseRevision"])) {
|
||||
return Err("已保存画布与制作任务不一致".into());
|
||||
}
|
||||
let scoped;
|
||||
let state = if snapshot.is_some() {
|
||||
let pack = state["productTemplates"].get(component).filter(|pack| pack.is_object())
|
||||
.ok_or("当前产品模板已变化")?;
|
||||
if variant(state, &variant_id).is_err() || !output_uses_variant(&state["brief"], component, &variant_id) {
|
||||
return Err("制作款式不属于当前输出".into());
|
||||
}
|
||||
let mut bound = state.clone();
|
||||
bound["activeOutput"] = json!(component);
|
||||
bound["activeVariantId"] = json!(variant_id);
|
||||
if pack["contentHash"] != state["template"]["contentHash"] {
|
||||
bound["structureHash"] = json!(hash(&json!([pack["contentHash"],state["width"]]).to_string()));
|
||||
}
|
||||
bound["template"] = pack.clone();
|
||||
scoped = bound;
|
||||
&scoped
|
||||
} else { state };
|
||||
let mut result = json!({"doc":doc,"workspaceId":state["id"],"outputId":component,"variantId":variant_id,"files":[]});
|
||||
if input["complete"] != true {
|
||||
result["productionDelivery"] = json!({"state":"pending","outputId":component});
|
||||
result["originals"] = input["originals"].clone();
|
||||
result["canContinue"] = input["canContinue"].clone();
|
||||
result["issues"] = input["issues"].clone();
|
||||
@ -2761,6 +2884,10 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
return Ok(result);
|
||||
}
|
||||
result["exportAttempted"] = json!(true);
|
||||
let blocked = |mut result: Value| {
|
||||
result["productionDelivery"] = json!({"state":"blocked","outputId":component});
|
||||
Ok(result)
|
||||
};
|
||||
let key = mapping_key(&variant_id, component, None);
|
||||
let editable = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
|
||||
let loaded;
|
||||
@ -2772,8 +2899,12 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
}
|
||||
};
|
||||
let meta = mapping(native).ok_or("可编辑画布缺少图层映射")?;
|
||||
if meta["workspaceId"] != state["id"] || meta["templateHash"] != state["template"]["contentHash"]
|
||||
|| meta["component"] != component || meta["variantId"] != variant_id {
|
||||
if snapshot.is_some() && input["canvasRevision"].is_u64()
|
||||
&& (native.id.0 != doc || input["canvasRevision"] != input["baseRevision"])
|
||||
|| meta["workspaceId"] != state["id"] || meta["templateHash"] != state["template"]["contentHash"]
|
||||
|| meta["component"] != component || meta["variantId"] != variant_id
|
||||
|| input["documentKey"].is_object()
|
||||
&& input["documentKey"] != photocraft_ui_egui::jiansun::product_document_key(native) {
|
||||
return Err("可编辑画布属于其他款式或模板".into());
|
||||
}
|
||||
let profile = production_profile::select(&state["template"], component)?;
|
||||
@ -2781,18 +2912,18 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
result["productionProfile"] = production_profile::source(&state["template"], component);
|
||||
if let Some(layer) = production_profile::visible_sample_layer(native, profile) {
|
||||
result["visibleSampleLayer"] = json!(layer.name);
|
||||
return Ok(result);
|
||||
return blocked(result);
|
||||
}
|
||||
let missing_text = production_profile::missing_visible_text(native, &meta, profile);
|
||||
if !missing_text.is_empty() {
|
||||
result["missingVisibleText"] = json!(missing_text);
|
||||
return Ok(result);
|
||||
return blocked(result);
|
||||
}
|
||||
}
|
||||
if production_profile::fixed_text_policy(profile) {
|
||||
if let Some(layer) = production_profile::unapproved_fixed_text(native, &meta) {
|
||||
result["visibleSampleLayer"] = json!(format!("{}(模板未声明可保留此固定文字)", layer.name));
|
||||
return Ok(result);
|
||||
return blocked(result);
|
||||
}
|
||||
} else {
|
||||
result["warnings"] = json!([production_profile::UNPUBLISHED_FIXED_TEXT]);
|
||||
@ -2800,13 +2931,13 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
let (missing, image_sources) = export_image_sources(dir, native, state, &meta, component, &variant_id);
|
||||
if !missing.is_empty() {
|
||||
result["missingImages"] = json!(missing);
|
||||
return Ok(result);
|
||||
return blocked(result);
|
||||
}
|
||||
let journal = production_audit(dir, state, component, &variant_id, scope)?;
|
||||
let unverified_copy = unverified_export_copy(native, &meta, &journal);
|
||||
if !unverified_copy.is_empty() {
|
||||
result["unverifiedCopy"] = json!(unverified_copy);
|
||||
return Ok(result);
|
||||
return blocked(result);
|
||||
}
|
||||
let path = receipt_path(dir, &variant_id, component);
|
||||
let pages = meta["outputs"].as_array().ok_or("没有可导出的画布页面")?;
|
||||
@ -2854,6 +2985,8 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va
|
||||
{
|
||||
result["goalSyncError"] = json!(error);
|
||||
}
|
||||
result["productionDelivery"] = json!({"state":if remaining.is_empty() {"completed"} else {"in_progress"},
|
||||
"outputState":"exported","outputId":component,"generationId":result["generationId"]});
|
||||
result["productionStages"] = json!(runnable_stages(state, remaining));
|
||||
Ok(result)
|
||||
}
|
||||
@ -3095,12 +3228,16 @@ impl Backend {
|
||||
json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"workflow":workflow,"creation":enrich_creation(dir,creation::load(dir)?)?,"pending":workflow["pending"],"canvasFirst":true}),
|
||||
)
|
||||
}
|
||||
pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> Result<Value, BridgeFailure> {
|
||||
pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender<Event>,
|
||||
ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<Value, BridgeFailure> {
|
||||
check_image_dispatch_cancelled(cancellation)?;
|
||||
self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?;
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
original_project_present(&dir)?;
|
||||
let phase = binding["action"].as_str().ok_or("生图请求动作缺失")?;
|
||||
let request = &binding["request"];
|
||||
transfer::no_credentials(request)?;
|
||||
if phase == "prepare" {
|
||||
let mut input = request.clone();
|
||||
input["doc"] = json!(doc);
|
||||
@ -3111,18 +3248,23 @@ impl Backend {
|
||||
return self.canvas_workspace_action("slot-prepare-image", &input, events, ctx).map_err(BridgeFailure::from);
|
||||
}
|
||||
if phase != "dispatch" { return Err("生图请求动作无效".into()); }
|
||||
let receipt = self.dispatch_canvas_image_request(doc, &dir, request, Some(&binding["scope"]), events, ctx)?;
|
||||
if receipt["status"].is_string() {
|
||||
let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir)
|
||||
.map_err(|error| BridgeFailure::new("image_request_failed", false, true, error))?, Some(receipt.clone()), None);
|
||||
let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot)));
|
||||
ctx.request_repaint();
|
||||
let receipt = self.dispatch_canvas_image_request(doc, &dir, request, Some(&binding["scope"]), events, ctx, cancellation)?;
|
||||
if receipt["status"].is_string() && check_image_dispatch_cancelled(cancellation).is_ok() {
|
||||
match self.canvas_workspace_result(doc, &dir) {
|
||||
Ok(workspace) => {
|
||||
let mut snapshot = operation_receipt(workspace, Some(receipt.clone()), None);
|
||||
snapshot["writeEpoch"] = binding["writeEpoch"].clone();
|
||||
let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot)));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
Err(error) => log::warn!("小壹原生图回执已保留,画布状态未刷新:{error}"),
|
||||
}
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
fn dispatch_canvas_image_request(&mut self, doc: u64, dir: &Path, request: &Value, scope: Option<&Value>,
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context) -> Result<Value, BridgeFailure> {
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<Value, BridgeFailure> {
|
||||
let id = uuid(&request["requestId"], "生图请求")?;
|
||||
let (task, _dispatch) = {
|
||||
let _guard = sync::context_guard();
|
||||
@ -3164,8 +3306,9 @@ impl Backend {
|
||||
"outputId":task["outputScope"],"candidate":candidate_receipt(record)});
|
||||
}
|
||||
publish_prepared(events, snapshot)?;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
validate_image_context(dir, Some(slot))?;
|
||||
check_image_dispatch_cancelled(cancellation)?;
|
||||
let call = self.image_job(None, &json!({"doc":doc,"frozenRequestId":id}), false, events, ctx);
|
||||
let dispatch_error = |error, backend: &Self| BridgeFailure::new("image_request_failed", false, backend.image_dispatch_may_have_started(doc, &id), error);
|
||||
let (mut receipt, failure) = self.settle_image_candidate(dir, doc, &id, slot, call, events, ctx)
|
||||
@ -3173,6 +3316,7 @@ impl Backend {
|
||||
if receipt["status"] == "failed" && let Some(message) = failure {
|
||||
receipt["message"] = json!(message);
|
||||
}
|
||||
self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, true, message))?;
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
@ -3195,6 +3339,9 @@ impl Backend {
|
||||
}
|
||||
|
||||
pub(super) fn canvas_workspace_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
if !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted") {
|
||||
self.check_dispatch()?;
|
||||
}
|
||||
let doc = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
@ -3259,7 +3406,11 @@ impl Backend {
|
||||
return Err("当前花色不属于所填产品资料".into());
|
||||
}
|
||||
let c = creation::load(&dir)?;
|
||||
self.creation_action("creation-save", &json!({"doc":doc,"revision":c["revision"],"brief":common,"width":width,"productionBudgetMinutes":input["productionBudgetMinutes"]}), None, events, ctx)?;
|
||||
let mut changes = json!({"doc":doc,"revision":c["revision"],"brief":common,"width":width,"productionBudgetMinutes":input["productionBudgetMinutes"]});
|
||||
if let Some(path) = input.get("deliveryDir") {
|
||||
changes["deliveryDir"] = path.clone();
|
||||
}
|
||||
self.creation_action("creation-save", &changes, None, events, ctx)?;
|
||||
let c = creation::load(&dir)?;
|
||||
let mut next = previous.unwrap_or_else(
|
||||
|| json!({"version":1,"canvasFirst":true,"id":Uuid::new_v4().to_string(),"revision":0,
|
||||
@ -3325,6 +3476,9 @@ impl Backend {
|
||||
.collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>().join("。");
|
||||
return Err(format!("所选模板暂无可制作的输出。{reasons}。请核对模板资源后选用新版本。"));
|
||||
}
|
||||
if input["resumeProduct"] == true && let Some(path) = input.get("deliveryDir") {
|
||||
creation::save_delivery_directory(&dir, path)?;
|
||||
}
|
||||
let mut prepared = self.canvas_workspace_result(doc, &dir)?;
|
||||
prepared["workflow"]["productionStages"] = json!(stages);
|
||||
prepared["productionPreparation"] = json!(true);
|
||||
@ -3363,7 +3517,7 @@ impl Backend {
|
||||
"template-progress"
|
||||
};
|
||||
let _ = events.send(Event::Json(event.into(), Ok(value)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
};
|
||||
let has_edit = edited.is_file();
|
||||
if browsing {
|
||||
@ -3451,6 +3605,7 @@ impl Backend {
|
||||
self.canvas_workspace_result(doc, &dir)?
|
||||
};
|
||||
result["baseRevision"] = input["baseRevision"].clone();
|
||||
result["writeEpoch"] = input["writeEpoch"].clone();
|
||||
result["outputId"] = json!(component);
|
||||
result["documentId"] = json!(document);
|
||||
result["variantId"] = json!(variant_id);
|
||||
@ -3537,7 +3692,7 @@ impl Backend {
|
||||
if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":candidate})) {
|
||||
reference["purpose"] = json!("template-candidate");
|
||||
let _ = events.send(Event::Preview(reference, preview));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None));
|
||||
}
|
||||
@ -3630,7 +3785,7 @@ impl Backend {
|
||||
if preparing { return Ok(draft); }
|
||||
// The native action is already confirmed by the operator.
|
||||
let receipt = self.dispatch_canvas_image_request(doc, &dir, &json!({"requestId":draft["requestId"],
|
||||
"expectedRevision":draft["revision"], "expectedHash":draft["requestSpecHash"], "slotId":id}), None, events, ctx)?;
|
||||
"expectedRevision":draft["revision"], "expectedHash":draft["requestSpecHash"], "slotId":id}), None, events, ctx, None)?;
|
||||
if receipt["status"] == "failed" { operation_error = receipt["message"].as_str().map(str::to_owned); }
|
||||
candidate_result = Some(receipt);
|
||||
} else if method == "slot-reuse" {
|
||||
@ -3638,7 +3793,7 @@ impl Backend {
|
||||
if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":record["id"]})) {
|
||||
reference["purpose"] = json!("template-candidate");
|
||||
let _ = events.send(Event::Preview(reference, preview));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None));
|
||||
} else if method == "slot-recover" {
|
||||
@ -4394,12 +4549,17 @@ mod tests {
|
||||
"requestId":id,"slotId":"other-slot","expectedRevision":1,"expectedHash":task["requestSpecHash"]}});
|
||||
for (field, value) in [("slotId",json!("other-slot")), ("expectedRevision",json!(2)), ("expectedHash",json!("other-hash"))] {
|
||||
let prior = std::mem::replace(&mut approval["request"][field], value);
|
||||
let failure = backend.production_image_request(doc, &approval, &events, &ctx).unwrap_err();
|
||||
let failure = backend.production_image_request(doc, &approval, &events, &ctx, None).unwrap_err();
|
||||
assert!(!failure.dispatched);
|
||||
assert!(read_json(&file).unwrap()["frozenAt"].is_null());
|
||||
approval["request"][field] = if field == "slotId" { json!(slot) } else { prior };
|
||||
}
|
||||
let failure = backend.production_image_request(doc, &approval, &events, &ctx).unwrap_err();
|
||||
let cancelled = std::sync::atomic::AtomicBool::new(true);
|
||||
let stopped = backend.production_image_request(doc, &approval, &events, &ctx, Some(&cancelled)).unwrap_err();
|
||||
assert_eq!(stopped.category, "cancelled");
|
||||
assert!(!stopped.dispatched);
|
||||
assert!(read_json(&file).unwrap()["frozenAt"].is_null());
|
||||
let failure = backend.production_image_request(doc, &approval, &events, &ctx, None).unwrap_err();
|
||||
assert!(!failure.dispatched);
|
||||
assert!(read_json(&file).unwrap()["frozenAt"].is_number());
|
||||
assert_eq!(read_json(&file).unwrap()["phase"], "prepared");
|
||||
@ -4634,6 +4794,7 @@ mod tests {
|
||||
save(&doc);
|
||||
let result = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap();
|
||||
assert_eq!(result["missingImages"], json!(["S01-I01"]));
|
||||
assert_eq!(result["productionDelivery"]["state"], "blocked");
|
||||
assert_eq!(result["files"], json!([]));
|
||||
assert!(!receipt_path(&fixture.dir,variant,"detail").exists());
|
||||
|
||||
@ -4682,6 +4843,8 @@ mod tests {
|
||||
save(&doc);
|
||||
let ready = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap();
|
||||
assert_eq!(ready["warnings"], json!(["该模板未发布固定文字许可"]));
|
||||
assert_eq!(ready["productionDelivery"]["outputState"], "exported");
|
||||
assert!(ready["localSave"].is_null() && ready["cloudSync"].is_null());
|
||||
let written = read_json(&receipt_path(&fixture.dir,variant,"detail")).unwrap();
|
||||
assert_eq!(written["warnings"], ready["warnings"]);
|
||||
assert_eq!(written["blankCopyReasons"][blank_id.to_string()], json!({"field":"S01-T02","reason":"缺少规格时留空"}));
|
||||
@ -4696,7 +4859,12 @@ mod tests {
|
||||
assert_eq!(screen["revision"], 2);
|
||||
assert_eq!(screen["fields"], json!(["S01-I01","S01-T01","S01-T02"]));
|
||||
fs::write(&edited, b"older or unreadable editable file").unwrap();
|
||||
let snapshot = export_product_stage_snapshot(&fixture.dir, 1, &state, &input, "test-account", Some(&doc)).unwrap();
|
||||
let mut viewing = state.clone();
|
||||
viewing["activeOutput"] = json!("sku_images");
|
||||
viewing["activeVariantId"] = json!(Uuid::new_v4());
|
||||
let mut bound = input.clone();
|
||||
bound["documentKey"] = photocraft_ui_egui::jiansun::product_document_key(&doc);
|
||||
let snapshot = export_product_stage_snapshot(&fixture.dir, 1, &viewing, &bound, "test-account", Some(&doc)).unwrap();
|
||||
assert_ne!(snapshot["generationId"], ready["generationId"]);
|
||||
assert_eq!(snapshot["files"][0]["sha256"], ready["files"][0]["sha256"]);
|
||||
assert_eq!(snapshot["screenFiles"][0]["sha256"], ready["screenFiles"][0]["sha256"]);
|
||||
@ -5442,7 +5610,22 @@ mod tests {
|
||||
state["brief"] = creation["brief"].clone();
|
||||
state["variants"] = json!(variants(&dir, &creation["brief"], None).unwrap());
|
||||
state["productTemplates"] = json!({"detail":state["template"]});
|
||||
persist(&dir, state, 0).unwrap();
|
||||
let state = persist(&dir, state, 0).unwrap();
|
||||
for color in [&oak, &white] {
|
||||
let mut canvas = slot_canvas::skeleton(&state["template"], "detail", None, color).unwrap();
|
||||
canvas.id = photocraft_doc::DocId(doc);
|
||||
let mut meta = mapping(&canvas).unwrap();
|
||||
meta["workspaceId"] = state["id"].clone();
|
||||
canvas.metadata.text.retain(|(key, _)| key != MAPPING);
|
||||
canvas.metadata.text.push((MAPPING.into(), meta.to_string()));
|
||||
let key = photocraft_ui_egui::jiansun::product_document_key(&canvas);
|
||||
let saved = backend.save(std::sync::Arc::new(canvas), 4, json!({})).unwrap();
|
||||
assert_eq!(saved["documentKey"], key);
|
||||
let path = dir.join("template-outputs").join(format!("canvas-{}-edited.pcraft",
|
||||
mapping_key(color, "detail", None)));
|
||||
let opened = photocraft_format::load_path(&path).unwrap();
|
||||
assert_eq!(photocraft_ui_egui::jiansun::product_document_key(&opened), key);
|
||||
}
|
||||
|
||||
let mut first = candidate(&dir, "prepared");
|
||||
first["binding"]["detailBatch"] = json!(true);
|
||||
@ -5797,4 +5980,59 @@ mod tests {
|
||||
state["brief"]["images"][0].as_object_mut().unwrap().remove("purpose");
|
||||
assert!(generation_references(&fixture.dir, &state, &variant).is_err(), "the existing native reference contract requires an explicit purpose");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layered_production_export_uses_the_real_psd_and_psb_boundary() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
for (height, expected) in [(30_000, "psd"), (30_001, "psb")] {
|
||||
let doc = Document::new("Layered test", photocraft_doc::Size::new(2, height),
|
||||
photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
|
||||
let artifact = export_layered_document(folder.path(), "detail", "generation-test", &doc).unwrap();
|
||||
assert_eq!(artifact["format"], expected);
|
||||
let name = format!("detail.{expected}");
|
||||
let bytes = fs::read(folder.path().join(&name)).unwrap();
|
||||
assert_eq!(layered_format(&bytes).unwrap(), expected);
|
||||
assert_eq!(layered_size(&name, &bytes).unwrap(), (2, height));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_reexport_keeps_previous_published_generation() {
|
||||
const CRASH: &str = "PHOTOCRAFT_TEST_CRASH_EXPORT";
|
||||
if let Some(path) = std::env::var_os(CRASH) {
|
||||
let path = PathBuf::from(path);
|
||||
let old = published_receipt(&path).unwrap();
|
||||
let doc = photocraft_format::load_path(Path::new(old["editable"].as_str().unwrap())).unwrap();
|
||||
publish_product_generation(&path, &doc, &json!(2), &mut json!({"outputId":"detail"}),
|
||||
&[(0, 8, 8)], &[(0, 8, 4), (4, 8, 4)]).unwrap();
|
||||
panic!("child must stop after writing the long image");
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let receipt = dir.path().join("detail.json");
|
||||
let doc = Document::new("A08", photocraft_doc::Size::new(8, 8),
|
||||
photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
|
||||
let mut old = json!({"outputId":"detail"});
|
||||
publish_product_generation(&receipt, &doc, &json!(1), &mut old,
|
||||
&[(0, 8, 8)], &[(0, 8, 4), (4, 8, 4)]).unwrap();
|
||||
let pointer_bytes = fs::read(&receipt).unwrap();
|
||||
let exit = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", &format!("{}::interrupted_reexport_keeps_previous_published_generation",
|
||||
module_path!().split_once("::").unwrap().1)])
|
||||
.env(CRASH, &receipt).output().unwrap();
|
||||
assert_eq!(exit.status.code(), Some(81), "{}", String::from_utf8_lossy(&exit.stdout));
|
||||
assert_eq!(fs::read(&receipt).unwrap(), pointer_bytes);
|
||||
let current = published_receipt(&receipt).unwrap();
|
||||
assert_eq!(current["sourceDocument"]["revision"], 1);
|
||||
assert!(artifact_matches(¤t["sourceDocument"], true));
|
||||
let layered = ¤t["layeredDocument"];
|
||||
let bytes = fs::read(layered["path"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(layered_size(layered["path"].as_str().unwrap(), &bytes).unwrap(), (8, 8));
|
||||
for file in current["files"].as_array().unwrap().iter().chain(current["screenFiles"].as_array().unwrap()) {
|
||||
assert!(artifact_matches(file, true));
|
||||
}
|
||||
let unfinished = fs::read_dir(dir.path().join("generations")).unwrap().map(Result::unwrap)
|
||||
.find(|entry| entry.file_name().to_str() != old["generationId"].as_str()).unwrap().path();
|
||||
assert!(unfinished.join("detail.jpg").is_file());
|
||||
assert!(!unfinished.join("manifest.json").exists());
|
||||
}
|
||||
}
|
||||
|
||||
@ -45,6 +45,16 @@ pub(super) fn load(dir: &Path) -> R<Value> {
|
||||
pub(super) fn save(dir: &Path, c: &mut Value) -> R<()> {
|
||||
save_with_revision(dir, c, true)
|
||||
}
|
||||
pub(super) fn save_delivery_directory(dir: &Path, value: &Value) -> R<()> {
|
||||
let path = json!(super::project_file::delivery_directory(dir, value)?);
|
||||
let mut creation = load(dir)?;
|
||||
if creation["deliveryDir"] != path {
|
||||
creation["deliveryDir"] = path;
|
||||
save_with_revision(dir, &mut creation, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_with_revision(dir: &Path, c: &mut Value, advance_revision: bool) -> R<()> {
|
||||
let _guard = sync::context_guard();
|
||||
project_not_trashed(dir)?;
|
||||
@ -146,8 +156,10 @@ fn persisted_inputs(c: &Value, input: &Value) -> R<()> {
|
||||
}
|
||||
fn task_save(dir: &Path, t: &Value) -> R<()> {
|
||||
let id = t["id"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("创作请求身份无效")?;
|
||||
write_json(&dir.join("creation-tasks").join(format!("{id}.json")), t)?;
|
||||
write_json(&dir.join("creation-task.json"), t)
|
||||
let mut safe = t.clone();
|
||||
transfer::redact(&mut safe);
|
||||
write_json(&dir.join("creation-tasks").join(format!("{id}.json")), &safe)?;
|
||||
write_json(&dir.join("creation-task.json"), &safe)
|
||||
}
|
||||
pub(super) fn unresolved(dir: &Path) -> R<bool> {
|
||||
let f = dir.join("creation-task.json");
|
||||
@ -506,7 +518,7 @@ impl Backend {
|
||||
value["accountId"]=self.auth["account"]["id"].clone();
|
||||
value["origin"]=json!(self.origin);
|
||||
let _=tx.send(Event::Json("resource-progress".into(), Ok(value)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
})?;
|
||||
let catalog = if matches!(kind, "brands" | "categories") { result["catalog"].take() } else {
|
||||
if kind == "resource-component" && let Some(row) = result["items"].get_mut(0) {
|
||||
@ -611,7 +623,7 @@ impl Backend {
|
||||
};
|
||||
let v = reference.clone();
|
||||
tx.send(Event::Preview(v.clone(), image)).map_err(|_| "工作台已关闭")?;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
Ok(v)
|
||||
})();
|
||||
match outcome {
|
||||
@ -626,6 +638,8 @@ impl Backend {
|
||||
"creation-save" => {
|
||||
let mut c = load(&dir)?;
|
||||
revision(&c, input)?;
|
||||
let delivery_dir = input.get("deliveryDir")
|
||||
.map(|value| super::project_file::delivery_directory(&dir, value)).transpose()?;
|
||||
let before = c.clone();
|
||||
c["brief"] = model::brief(&input["brief"])?;
|
||||
if let Some(w) = input["width"].as_u64() {
|
||||
@ -670,12 +684,15 @@ impl Backend {
|
||||
model::invalidate(&mut c, &before);
|
||||
let budget = input["productionBudgetMinutes"].as_u64().filter(|minutes| *minutes > 0)
|
||||
.filter(|minutes| Some(*minutes) != before["productionBudgetMinutes"].as_u64());
|
||||
let budget_only = budget.is_some() && c == before;
|
||||
let preferences_only = c == before && (budget.is_some() || delivery_dir.is_some());
|
||||
if let Some(path) = delivery_dir {
|
||||
c["deliveryDir"] = json!(path);
|
||||
}
|
||||
if let Some(minutes) = budget {
|
||||
c["productionBudgetMinutes"] = json!(minutes);
|
||||
}
|
||||
save_with_revision(&dir, &mut c, !budget_only)?;
|
||||
if !budget_only {
|
||||
save_with_revision(&dir, &mut c, !preferences_only)?;
|
||||
if !preferences_only {
|
||||
super::canvas_workspace::apply_saved_variant_edits(&dir)?;
|
||||
}
|
||||
self.creation_result(doc, &dir)
|
||||
@ -760,7 +777,7 @@ impl Backend {
|
||||
result["path"] = json!(path.to_string_lossy());
|
||||
result["creation"] = c;
|
||||
tx.send(Event::CreationCanvas(Box::new(document), result.clone())).map_err(|_| "工作台已关闭,结果仍保存在本机")?;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
Ok(result)
|
||||
}
|
||||
_ => Err("创作操作未开放".into()),
|
||||
@ -882,6 +899,7 @@ impl Backend {
|
||||
pi_runtime::apply_invocation_capacity(&mut request_model, &invocation)?;
|
||||
let payload = request_body(&request_model, task["prompt"].as_str().ok_or("任务提示词缺失")?, &pictures)?;
|
||||
self.validate()?;
|
||||
if self.exiting() { return Err("客户端正在退出,未派发新请求".into()); }
|
||||
task["phase"] = json!("dispatched");
|
||||
task["message"] = json!("模型处理中;不会自动重发");
|
||||
task_save(&dir, &task)?;
|
||||
@ -898,6 +916,8 @@ impl Backend {
|
||||
if anthropic {
|
||||
req = req.header("Anthropic-Version", "2023-06-01");
|
||||
}
|
||||
if self.exiting() { return Err("客户端正在退出,保留原任务编号".into()); }
|
||||
self.check_dispatch()?;
|
||||
req.send()
|
||||
};
|
||||
let response = response.map_err(|error| stream::transport_error(&error))?;
|
||||
@ -906,6 +926,7 @@ impl Backend {
|
||||
task_save(&dir, &task)?;
|
||||
}
|
||||
let status = response.status().as_u16();
|
||||
self.check_model_authority(&response, key)?;
|
||||
let sse = response.headers().get("content-type").and_then(|s| s.to_str().ok()).is_some_and(|s| s.starts_with("text/event-stream"));
|
||||
if status != 200 {
|
||||
task["httpStatus"] = json!(status);
|
||||
@ -913,13 +934,14 @@ impl Backend {
|
||||
}
|
||||
let mut raw = if sse {
|
||||
stream::read(response, anthropic, |text| {
|
||||
let text = transfer::redact_text(text);
|
||||
task["partialText"] = json!(text);
|
||||
task_save(&dir, &task)?;
|
||||
let mut event = identity.clone();
|
||||
event["text"] = json!(text);
|
||||
event["stage"] = json!(stage);
|
||||
let _ = tx.send(Event::Json("creation-progress".into(), Ok(event)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
Ok(())
|
||||
})?
|
||||
} else {
|
||||
@ -1240,7 +1262,7 @@ impl Backend {
|
||||
let (reply, rx) = mpsc::channel();
|
||||
let payload = json!({"doc":input["doc"],"accountId":self.auth["account"]["id"],"origin":self.origin,"baseRevision":input["baseRevision"],"run":run,"sequence":sequence});
|
||||
tx.send(Event::PiAction("creation-allowed".into(), payload, reply)).map_err(|_| "工作台已关闭,后续屏幕未发送")?;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
let (value, _) = rx.recv_timeout(Duration::from_secs(12)).map_err(|_| "画布未确认状态,后续屏幕未发送")??;
|
||||
if value["allowed"] != true {
|
||||
return Err("用户已接手或画布有新编辑,后续屏幕未发送;已生成结果保留".into());
|
||||
@ -1261,7 +1283,7 @@ impl Backend {
|
||||
result["sequence"] = json!(sequence);
|
||||
result["taskId"] = c["generation"]["lastTaskId"].clone();
|
||||
tx.send(Event::CreationCanvas(Box::new(native), result.clone())).map_err(|_| "工作台已关闭;生成画布仍保留在本机")?;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
Ok(result)
|
||||
}
|
||||
pub(super) fn creation_record_image(&self, dir: &Path, c: &mut Value, screen: &str, result: &Value) -> R<()> {
|
||||
@ -1573,6 +1595,8 @@ mod tests {
|
||||
recovery_attempts: Default::default(),
|
||||
recovery_serial: Default::default(),
|
||||
composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
access: Default::default(),
|
||||
};
|
||||
backend.bind_new(1);
|
||||
let dir = backend.project_dir(1).unwrap();
|
||||
|
||||
429
apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs
Normal file
429
apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs
Normal file
@ -0,0 +1,429 @@
|
||||
use super::{Backend, R, canvas_workspace, creation, original_project_present, pi_runtime, project_file, read_json, sync, transfer, write_json};
|
||||
use photocraft_format::atomic::{AtomicFs, RealFs};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashSet},
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
fn disk(error: std::io::Error) -> String {
|
||||
format!("成品目录写入或读取失败:{error}")
|
||||
}
|
||||
|
||||
fn name_component(name: &str) -> String {
|
||||
let cleaned: String = name.chars().take(70).map(|ch| if ch.is_control() || "<>:\"/\\|?*".contains(ch) { '_' } else { ch }).collect();
|
||||
let name = cleaned.trim_matches(|ch: char| ch == '.' || ch.is_whitespace());
|
||||
let stem = name.split('.').next().unwrap_or_default().to_ascii_uppercase();
|
||||
if name.is_empty() {
|
||||
return "小壹项目".into();
|
||||
}
|
||||
if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|
||||
|| stem
|
||||
.strip_prefix("COM")
|
||||
.or_else(|| stem.strip_prefix("LPT"))
|
||||
.is_some_and(|number| matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"))
|
||||
{
|
||||
return format!("_{name}");
|
||||
}
|
||||
name.into()
|
||||
}
|
||||
|
||||
fn file_record(root: &Path, path: &Path, category: &str, size: Option<(u32, u32)>) -> R<Value> {
|
||||
let relative = path.strip_prefix(root).map_err(|_| "交付文件不在成品目录内")?;
|
||||
let format = path.extension().and_then(|extension| extension.to_str()).ok_or("交付文件格式缺失")?;
|
||||
Ok(json!({"category":category,"relativePath":relative.to_string_lossy().replace('\\', "/"),
|
||||
"format":format,"width":size.map(|(width, _)| width),"height":size.map(|(_, height)| height),
|
||||
"sizeBytes":fs::metadata(path).map_err(disk)?.len(),
|
||||
"sha256":canvas_workspace::file_digest(path).map_err(disk)?,"verified":true}))
|
||||
}
|
||||
|
||||
fn artifact_size(path: &Path, format: &str) -> R<Option<(u32, u32)>> {
|
||||
let size = match format {
|
||||
"jpg" => {
|
||||
let bytes = fs::read(path).map_err(disk)?;
|
||||
if !bytes.starts_with(&[0xff, 0xd8, 0xff]) {
|
||||
return Err("JPG 文件头无效".into());
|
||||
}
|
||||
photocraft_codecs::probe_size(&bytes).map_err(|error| format!("无法读取 JPG 尺寸:{error}"))?
|
||||
}
|
||||
"psd" | "psb" => canvas_workspace::layered_size(&path.to_string_lossy(), &fs::read(path).map_err(disk)?)?,
|
||||
"pcraft" => {
|
||||
transfer::check_pcraft_file(path)?;
|
||||
let doc = photocraft_format::load_path(path).map_err(|error| format!("无法重开成品原稿:{error}"))?;
|
||||
(doc.size.width, doc.size.height)
|
||||
}
|
||||
"jpeg" | "png" | "webp" => {
|
||||
photocraft_codecs::probe_size(&fs::read(path).map_err(disk)?).map_err(|error| format!("无法读取工程资源图像尺寸:{error}"))?
|
||||
}
|
||||
_ => return Ok(None),
|
||||
};
|
||||
Ok(Some(size))
|
||||
}
|
||||
|
||||
fn copy_artifact(root: &Path, generation: &Path, source: &Value, category: &str, folder: &Path, name: &str) -> R<Value> {
|
||||
let format = source["format"].as_str().filter(|format| matches!(*format, "jpg" | "pcraft" | "psd" | "psb")).ok_or("成品格式无效")?;
|
||||
let filename = source["path"].as_str().and_then(|path| Path::new(path).file_name()).ok_or("成品路径缺失")?;
|
||||
let from = generation.join(filename);
|
||||
let parent = root.join(category).join(folder);
|
||||
fs::create_dir_all(&parent).map_err(disk)?;
|
||||
let to = parent.join(format!("{name}.{format}"));
|
||||
if to.exists() {
|
||||
return Err("成品清单含重复文件名".into());
|
||||
}
|
||||
fs::copy(&from, &to).map_err(disk)?;
|
||||
let size = artifact_size(&to, format)?.ok_or("成品清单含不支持的格式")?;
|
||||
let record = file_record(root, &to, category, Some(size))?;
|
||||
if ["width", "height", "sizeBytes", "sha256"].iter().any(|field| record[*field] != source[*field]) {
|
||||
return Err(format!("{name}.{format} 与已验证成品不一致"));
|
||||
}
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, files: &mut Vec<Value>) -> R<()> {
|
||||
let component = output["outputId"].as_str().ok_or("成品类型缺失")?;
|
||||
let label = match component {
|
||||
"detail" => "详情页",
|
||||
"main_images" => "主图",
|
||||
"sku_images" => "SKU",
|
||||
_ => return Err("成品类型无效".into()),
|
||||
};
|
||||
let variant = output["variantId"].as_str().ok_or("成品花色缺失")?;
|
||||
if Uuid::parse_str(variant).is_err() {
|
||||
return Err("成品花色标识无效".into());
|
||||
}
|
||||
let id = output["generationId"]
|
||||
.as_str()
|
||||
.filter(|id| id.strip_prefix("generation-").is_some_and(|suffix| !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_alphanumeric())))
|
||||
.ok_or("成品版本无效")?;
|
||||
let receipt = canvas_workspace::receipt_path(project, variant, component);
|
||||
let manifest = receipt.with_file_name(canvas_workspace::manifest_path(id));
|
||||
let generation = manifest.parent().ok_or("成品版本目录无效")?;
|
||||
let data = read_json(&manifest)?;
|
||||
if data["workspaceId"] != input["workspaceId"]
|
||||
|| data["outputId"] != component
|
||||
|| data["variantId"] != variant
|
||||
|| data["generationId"] != id
|
||||
|| data["validation"]["mode"] != "full"
|
||||
{
|
||||
return Err("制作输出与已验证成品版本不一致".into());
|
||||
}
|
||||
files.push(copy_artifact(root, generation, &data["sourceDocument"], "工程文件", folder, label)?);
|
||||
files.push(copy_artifact(root, generation, &data["layeredDocument"], "PSD", folder, label)?);
|
||||
let images = data["files"].as_array().filter(|rows| !rows.is_empty()).ok_or("成品 JPG 缺失")?;
|
||||
if component == "detail" {
|
||||
let mut screens = data["screenFiles"].as_array().filter(|rows| !rows.is_empty()).ok_or("详情页切片缺失")?.iter().collect::<Vec<_>>();
|
||||
screens.sort_by_key(|screen| screen["top"].as_u64());
|
||||
if images.len() != 1 {
|
||||
return Err("详情页长图数量无效".into());
|
||||
}
|
||||
files.push(copy_artifact(root, generation, &images[0], "详情页长图", folder, "详情页长图")?);
|
||||
for (index, screen) in screens.into_iter().enumerate() {
|
||||
files.push(copy_artifact(root, generation, screen, "详情页切片", folder, &format!("详情页-{:02}", index + 1))?);
|
||||
}
|
||||
} else {
|
||||
for (index, image) in images.iter().enumerate() {
|
||||
files.push(copy_artifact(root, generation, image, label, folder, &format!("{label}-{:02}", index + 1))?);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_tree(dir: &Path) -> R<()> {
|
||||
for entry in fs::read_dir(dir).map_err(disk)? {
|
||||
let entry = entry.map_err(disk)?;
|
||||
if entry.file_type().map_err(disk)?.is_dir() {
|
||||
sync_tree(&entry.path())?;
|
||||
} else {
|
||||
fs::OpenOptions::new().write(true).open(entry.path()).and_then(|file| file.sync_all()).map_err(disk)?;
|
||||
}
|
||||
}
|
||||
RealFs.sync_dir(dir).map_err(disk)
|
||||
}
|
||||
|
||||
fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, input: &Value, admitted: impl Fn() -> R<()>) -> R<Value> {
|
||||
admitted()?;
|
||||
let dir = project_file::delivery_directory(project, &input["deliveryDir"])?.ok_or("未选择成品目录")?;
|
||||
let delivery_id = input["deliveryId"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("本轮交付编号无效")?;
|
||||
let outputs = input["published"].as_array().filter(|rows| !rows.is_empty()).ok_or("本轮没有已验证成品")?;
|
||||
let creation = creation::load(project)?;
|
||||
let name = name_component(creation["brief"]["name"].as_str().unwrap_or_default());
|
||||
transfer::no_credentials(&json!(name))?;
|
||||
fs::create_dir_all(&dir).map_err(disk)?;
|
||||
let destination = |number| {
|
||||
let basename = if number == 1 { format!("{name}-成品") } else { format!("{name}-成品 ({number})") };
|
||||
dir.join(basename)
|
||||
};
|
||||
let existing_receipt = |target: &Path| {
|
||||
read_json(&target.join("交付清单.json"))
|
||||
.ok()
|
||||
.filter(|saved| saved["deliveryId"] == delivery_id)
|
||||
.map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"counts":saved["counts"]}))
|
||||
};
|
||||
// Recover a committed directory if the client lost the completion event.
|
||||
for number in 1.. {
|
||||
let target = destination(number);
|
||||
if !target.try_exists().map_err(disk)? {
|
||||
break;
|
||||
}
|
||||
if let Some(receipt) = existing_receipt(&target) {
|
||||
return Ok(receipt);
|
||||
}
|
||||
}
|
||||
let stage = tempfile::Builder::new().prefix(".xiaoyi-deliver-tmp-").tempdir_in(&dir).map_err(disk)?;
|
||||
let root = stage.path();
|
||||
let package_root = root.join("工程文件");
|
||||
fs::create_dir(&package_root).map_err(disk)?;
|
||||
let project_file = package_root.join(format!("{name}.xiaoyi"));
|
||||
let mut package = json!({"version":2,"localId":policy.project,"scope":policy.scope,
|
||||
"snapshot":Uuid::new_v4().to_string(),"sourceRoot":project,"resources":format!("{name} 资源")});
|
||||
project_file::write_project(project, &project_file, &mut package, policy)?;
|
||||
let reopened = read_json(&project_file)?;
|
||||
if reopened != package {
|
||||
return Err("小壹工程清单读回不一致".into());
|
||||
}
|
||||
transfer::no_credentials(&reopened)?;
|
||||
let snapshot = project_file::resource_checkpoint(&project_file, &reopened)?;
|
||||
let doc = photocraft_format::load_path(&snapshot.join("canvas.pcraft")).map_err(|error| format!("无法重开小壹工程画布:{error}"))?;
|
||||
let mut files = vec![file_record(root, &project_file, "工程文件", Some((doc.size.width, doc.size.height)))?];
|
||||
for entry in reopened["projectManifest"]["included"].as_array().ok_or("工程资源清单缺失")? {
|
||||
let relative = entry.as_str().ok_or("工程资源路径无效")?;
|
||||
let file = snapshot.join(relative);
|
||||
let format = file.extension().and_then(|extension| extension.to_str()).unwrap_or("");
|
||||
let size = artifact_size(&file, format)?;
|
||||
let record = file_record(root, &file, "工程资源", size)?;
|
||||
// The portable checkpoint normalizes its context and stops any active run.
|
||||
if !matches!(relative, "context.json" | "production-run.json")
|
||||
&& record["sha256"] != canvas_workspace::file_digest(&project.join(relative)).map_err(disk)?
|
||||
{
|
||||
return Err("工程资源与本机草稿内容不一致".into());
|
||||
}
|
||||
files.push(record);
|
||||
}
|
||||
|
||||
let variants: HashSet<_> = outputs.iter().filter_map(|output| output["variantId"].as_str()).collect();
|
||||
let mut variant_folders = BTreeMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
for output in outputs {
|
||||
admitted()?;
|
||||
let variant = output["variantId"].as_str().ok_or("成品花色缺失")?;
|
||||
let component = output["outputId"].as_str().ok_or("成品类型缺失")?;
|
||||
if !seen.insert((variant, component)) {
|
||||
return Err("本轮交付含重复输出".into());
|
||||
}
|
||||
let index = variant_folders.len() + 1;
|
||||
let folder = variant_folders.entry(variant).or_insert_with(|| {
|
||||
if variants.len() == 1 {
|
||||
return PathBuf::new();
|
||||
}
|
||||
let label = creation["brief"]["variants"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|row| row["id"] == variant)
|
||||
.and_then(|row| row["name"].as_str())
|
||||
.unwrap_or("花色");
|
||||
PathBuf::from(format!("{index:02} {}", name_component(label)))
|
||||
});
|
||||
copy_generation(root, project, input, output, folder, &mut files)?;
|
||||
}
|
||||
let all_outputs_completed = input["total"].as_u64() == Some(outputs.len() as u64);
|
||||
let mut counts = BTreeMap::new();
|
||||
for category in files.iter().filter_map(|file| file["category"].as_str()) {
|
||||
*counts.entry(category.to_owned()).or_insert(0) += 1;
|
||||
}
|
||||
let manifest = json!({"version":1,"deliveryId":delivery_id,"allOutputsCompleted":all_outputs_completed,
|
||||
"completedOutputs":outputs.len(),"totalOutputs":input["total"],"counts":counts,"files":files});
|
||||
transfer::no_credentials(&manifest)?;
|
||||
write_json(&root.join("交付清单.json"), &manifest)?;
|
||||
sync_tree(root)?;
|
||||
let _guard = sync::context_guard();
|
||||
admitted()?;
|
||||
for number in 1.. {
|
||||
let target = destination(number);
|
||||
if target.try_exists().map_err(disk)? {
|
||||
if let Some(receipt) = existing_receipt(&target) {
|
||||
return Ok(receipt);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match fs::rename(root, &target) {
|
||||
Ok(()) => {
|
||||
let flush = RealFs.sync_dir(&dir).err().map(|error| disk(error));
|
||||
return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed,
|
||||
"counts":counts,"durabilityWarning":flush}));
|
||||
}
|
||||
Err(_) if target.exists() => continue,
|
||||
Err(error) => return Err(disk(error)),
|
||||
}
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(super) fn deliver_bundle(&self, input: &Value, cancellation: &AtomicBool) -> R<Value> {
|
||||
let doc = input["doc"].as_u64().ok_or("项目编号无效")?;
|
||||
self.ensure_owner(doc)?;
|
||||
let project = self.locations.get(&doc).filter(|project| input["project"] == project.as_str()).ok_or("制作任务属于其他项目")?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
let admitted = || {
|
||||
if cancellation.load(Ordering::Acquire) {
|
||||
return Err("原制作回合已停止".into());
|
||||
}
|
||||
self.check_dispatch()?;
|
||||
self.ensure_owner(doc)?;
|
||||
original_project_present(&dir)
|
||||
};
|
||||
admitted()?;
|
||||
if input["accountEpoch"].as_u64() != Some(self.access.epoch)
|
||||
|| input["writeEpoch"].as_u64().is_none()
|
||||
|| input["accountId"] != self.auth["account"]["id"]
|
||||
|| input["origin"] != self.origin
|
||||
{
|
||||
return Err("账号或制作回合已切换".into());
|
||||
}
|
||||
let scope = self.scope();
|
||||
let policy = transfer::Policy { chat: false, scope: &scope, project };
|
||||
pi_runtime::record_export_event(self, doc, input, "export", "deliver_bundle", "running", Value::Null);
|
||||
let result = deliver_production_bundle(&dir, &policy, input, admitted);
|
||||
let (status, progress) = match &result {
|
||||
Ok(receipt) => {
|
||||
let status = if receipt["durabilityWarning"].is_string() { "unconfirmed" } else { "completed" };
|
||||
(status, json!({"counts":receipt["counts"],"allOutputsCompleted":receipt["allOutputsCompleted"]}))
|
||||
}
|
||||
Err(_) => ("failed", Value::Null),
|
||||
};
|
||||
pi_runtime::record_export_event(self, doc, input, "export", "deliver_bundle", status, progress);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_doc::{ColorMode, Document, SampleType, Size};
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, PathBuf, String, Value) {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let local = Uuid::new_v4().to_string();
|
||||
let project = root.path().join("drafts").join(&local);
|
||||
fs::create_dir_all(&project).unwrap();
|
||||
let canvas = Document::new("天青椅", Size::new(8, 10), ColorMode::Rgb, SampleType::U8);
|
||||
photocraft_format::PcraftWriter::new().save_path(&canvas, &project.join("canvas.pcraft"), &Default::default()).unwrap();
|
||||
write_json(&project.join("context.json"), &json!({"localId":local,"owner":"owner"})).unwrap();
|
||||
write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅"}})).unwrap();
|
||||
let variant = Uuid::new_v4().to_string();
|
||||
let workspace = Uuid::new_v4().to_string();
|
||||
let mut published = Vec::new();
|
||||
for (component, regions, screens) in [
|
||||
("detail", vec![(0, 8, 10)], vec![(0, 8, 4), (4, 8, 6)]),
|
||||
("main_images", vec![(0, 8, 4), (4, 8, 6)], vec![]),
|
||||
("sku_images", vec![(0, 8, 10)], vec![]),
|
||||
] {
|
||||
let receipt = canvas_workspace::receipt_path(&project, &variant, component);
|
||||
let mut result = json!({"workspaceId":workspace,"variantId":variant,"outputId":component});
|
||||
canvas_workspace::publish_product_generation(&receipt, &canvas, &json!(7), &mut result, ®ions, &screens).unwrap();
|
||||
assert_eq!(result["layeredDocument"]["format"], "psd");
|
||||
assert_eq!(result["validation"]["filesVerified"], 2 + regions.len() + screens.len());
|
||||
published.push(json!({"variantId":variant,"outputId":component,"generationId":result["generationId"]}));
|
||||
}
|
||||
let input = json!({"workspaceId":workspace,"deliveryId":Uuid::new_v4().to_string(),
|
||||
"deliveryDir":root.path().join("deliveries"),"total":3,"published":published});
|
||||
(root, project, local, input)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_preference_reopens_and_clears_without_revising_creation_inputs() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let project = root.path().join("drafts").join("project");
|
||||
fs::create_dir_all(&project).unwrap();
|
||||
let path = root.path().join("deliveries");
|
||||
write_json(&project.join("creation.json"), &json!({"version":1,"revision":9,"brief":{"name":"天青椅"}})).unwrap();
|
||||
assert!(creation::load(&project).unwrap()["deliveryDir"].is_null());
|
||||
creation::save_delivery_directory(&project, &json!(path)).unwrap();
|
||||
let saved = creation::load(&project).unwrap();
|
||||
assert_eq!(saved["deliveryDir"], json!(path));
|
||||
assert_eq!(saved["revision"], 9);
|
||||
assert!(creation::save_delivery_directory(&project, &json!(project.join("nested"))).is_err());
|
||||
assert_eq!(creation::load(&project).unwrap(), saved);
|
||||
creation::save_delivery_directory(&project, &Value::Null).unwrap();
|
||||
assert!(creation::load(&project).unwrap()["deliveryDir"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locally_published_outputs_form_a_reopenable_verified_bundle_and_keep_older_deliveries() {
|
||||
let (root, project, local, mut input) = fixture();
|
||||
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
|
||||
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
|
||||
assert_eq!(delivered["allOutputsCompleted"], true);
|
||||
let counts = &delivered["counts"];
|
||||
for (category, count) in [("工程文件", 4), ("PSD", 3), ("详情页长图", 1), ("详情页切片", 2), ("主图", 2), ("SKU", 1)] {
|
||||
assert_eq!(counts[category], count, "{category}");
|
||||
}
|
||||
let final_dir = PathBuf::from(delivered["path"].as_str().unwrap());
|
||||
let manifest_path = final_dir.join("交付清单.json");
|
||||
let manifest = read_json(&manifest_path).unwrap();
|
||||
transfer::no_credentials(&manifest).unwrap();
|
||||
for entry in manifest["files"].as_array().unwrap() {
|
||||
let path = final_dir.join(entry["relativePath"].as_str().unwrap());
|
||||
assert!(path.is_file(), "{}", path.display());
|
||||
assert_eq!(entry["sizeBytes"], fs::metadata(&path).unwrap().len());
|
||||
assert_eq!(entry["sha256"], canvas_workspace::file_digest(&path).unwrap());
|
||||
assert_eq!(entry["verified"], true);
|
||||
}
|
||||
for (path, width, height) in [
|
||||
("详情页长图/详情页长图.jpg", 8, 10),
|
||||
("详情页切片/详情页-01.jpg", 8, 4),
|
||||
("详情页切片/详情页-02.jpg", 8, 6),
|
||||
("主图/主图-01.jpg", 8, 4),
|
||||
("主图/主图-02.jpg", 8, 6),
|
||||
("SKU/SKU-01.jpg", 8, 10),
|
||||
] {
|
||||
let bytes = fs::read(final_dir.join(path)).unwrap();
|
||||
assert_eq!(photocraft_codecs::probe_size(&bytes).unwrap(), (width, height));
|
||||
}
|
||||
for name in ["详情页", "主图", "SKU"] {
|
||||
let filename = format!("{name}.psd");
|
||||
let bytes = fs::read(final_dir.join("PSD").join(&filename)).unwrap();
|
||||
assert_eq!(canvas_workspace::layered_size(&filename, &bytes).unwrap(), (8, 10));
|
||||
}
|
||||
let clean = root.path().join("clean");
|
||||
fs::create_dir(&clean).unwrap();
|
||||
assert_eq!(project_file::open(&final_dir.join("工程文件/天青椅.xiaoyi"), &clean, "owner").unwrap(), local);
|
||||
let original = fs::read(manifest_path).unwrap();
|
||||
assert_eq!(deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap()["path"], delivered["path"]);
|
||||
input["deliveryId"] = json!(Uuid::new_v4().to_string());
|
||||
let second = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
|
||||
assert!(second["path"].as_str().unwrap().ends_with("天青椅-成品 (2)"));
|
||||
assert_eq!(fs::read(final_dir.join("交付清单.json")).unwrap(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_destination_cancellation_and_credentials_leave_generations_intact() {
|
||||
let (root, project, local, mut input) = fixture();
|
||||
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
|
||||
let previous = input["deliveryDir"].clone();
|
||||
for invalid in [json!("relative"), json!(project.join("delivery")), json!(project.join("canvas.pcraft"))] {
|
||||
input["deliveryDir"] = invalid;
|
||||
assert!(deliver_production_bundle(&project, &policy, &input, || Ok(())).is_err());
|
||||
}
|
||||
input["deliveryDir"] = previous;
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = deliver_production_bundle(&project, &policy, &input, || {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() >= 5 { Err("cancelled".into()) } else { Ok(()) }
|
||||
});
|
||||
assert_eq!(result.unwrap_err(), "cancelled");
|
||||
let destination = root.path().join("deliveries");
|
||||
assert_eq!(fs::read_dir(&destination).unwrap().count(), 0);
|
||||
write_json(&project.join("creation.json"), &json!({"version":1,"brief":{"name":"天青椅","apiKey":"fixture-secret"}})).unwrap();
|
||||
assert!(deliver_production_bundle(&project, &policy, &input, || Ok(())).is_err());
|
||||
assert_eq!(fs::read_dir(&destination).unwrap().count(), 0);
|
||||
for output in input["published"].as_array().unwrap() {
|
||||
let pointer = canvas_workspace::receipt_path(&project, output["variantId"].as_str().unwrap(), output["outputId"].as_str().unwrap());
|
||||
assert_eq!(canvas_workspace::published_receipt(&pointer).unwrap()["generationId"], output["generationId"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -229,6 +229,7 @@ fn job_save_locked(dir: &Path, t: &Value, current_only: bool) -> R<()> {
|
||||
let id = t["id"].as_str().filter(|s| Uuid::parse_str(s).is_ok()).ok_or("任务身份无效")?;
|
||||
let archive = dir.join("image-jobs").join(id).join("task.json");
|
||||
let mut settled = t.clone();
|
||||
transfer::redact(&mut settled);
|
||||
if archive.exists() {
|
||||
let existing = read_json(&archive)?;
|
||||
if existing["id"] != t["id"]
|
||||
@ -654,6 +655,7 @@ impl Backend {
|
||||
if deadline.is_none() {
|
||||
return self.validate();
|
||||
}
|
||||
self.check_dispatch()?;
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先在素材库登录")?;
|
||||
let response = self
|
||||
.http
|
||||
@ -663,11 +665,20 @@ impl Backend {
|
||||
.send()
|
||||
.map_err(|_| "素材库授权校验连接中断")?;
|
||||
let (code, value) = body(response, MAX_JSON)?;
|
||||
if code != 200 || value["account"]["id"] != self.auth["account"]["id"] {
|
||||
if code == 401 {
|
||||
self.revoke_access("auth_revoked");
|
||||
let _ = self.renew_portal_session();
|
||||
return Err(AUTH_REVOKED.into());
|
||||
}
|
||||
if code == 200 && value["account"]["id"] != self.auth["account"]["id"] {
|
||||
self.revoke_access("scope_changed");
|
||||
return Err(ACCOUNT_CHANGED.into());
|
||||
}
|
||||
if code != 200 {
|
||||
return Err("授权已失效或账户已变化,原请求保留待核查".into());
|
||||
}
|
||||
self.auth["account"] = value["account"].clone();
|
||||
Ok(())
|
||||
self.check_dispatch()
|
||||
}
|
||||
pub(super) fn reference_image_preview(&self, input: &Value) -> R<Option<(Value, egui::ColorImage)>> {
|
||||
let doc = input["doc"].as_u64().ok_or("项目身份无效")?;
|
||||
@ -868,7 +879,8 @@ impl Backend {
|
||||
if references.len() != 1 { return Err("实拍合成只发送模板场景去除旧商品".into()); }
|
||||
job_bytes(&dir, &files.join("scene-product.png"), cutout).map_err(|_| "实拍抠图保存失败,未提交")?;
|
||||
}
|
||||
protocol::validate_prompt_length(&contract, text)?;
|
||||
let text = transfer::redact_text(text);
|
||||
protocol::validate_prompt_length(&contract, &text)?;
|
||||
let prior = if dir.join("image-task.json").exists() { read_json(&dir.join("image-task.json"))?["id"].clone() } else { Value::Null };
|
||||
json!({"version":1,"id":job,"doc":id,"revision":input["revision"],"mode":input["mode"],"target":target,"modelId":model_id,"modelKey":choice,"protocol":contract,"prompt":text,"references":references,"keyFingerprint":hash(key),"phase":"prepared","requestId":null,"upstreamTaskId":null,"center":input["center"],"accountScope":self.scope(),"localProjectId":self.locations.get(&id),"origin":self.origin,"createdAt":now(),"replacesTaskId":prior,"creationBinding":input["creationBinding"],"slotBinding":input["slotBinding"],"sceneComposite":scene.as_ref().map(|(recipe,_)|recipe)})
|
||||
};
|
||||
@ -908,7 +920,7 @@ impl Backend {
|
||||
v["imageFrame"] = json!({"width":width,"height":height});
|
||||
}
|
||||
let _ = tx.send(Event::Json("image-progress".into(), Ok(v)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
};
|
||||
let result = (|| -> R<()> {
|
||||
let raw_file = taskdir.join("response.json");
|
||||
@ -955,6 +967,7 @@ impl Backend {
|
||||
if matches!(kind, "result" | "task-result") && response.status() == reqwest::StatusCode::GONE {
|
||||
return Ok((410, Value::Null));
|
||||
}
|
||||
self.check_model_authority(&response, key)?;
|
||||
let decoded = body(response, if matches!(kind, "lookup" | "task-status") { 64 * 1024 } else { RESPONSE_BYTES })?;
|
||||
if let Some(last) = diagnostic["attempts"].as_array_mut().and_then(|a| a.last_mut()) {
|
||||
match kind {
|
||||
@ -1018,6 +1031,7 @@ impl Backend {
|
||||
let (client, request) = req.build_split();
|
||||
let request = request.map_err(|_| "生图请求准备失败,未提交")?;
|
||||
self.image_validate(deadline)?; // Live permission immediately before a paid dispatch.
|
||||
if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); }
|
||||
t["phase"] = json!("dispatched");
|
||||
job_save(&dir, &t)?;
|
||||
if t["creationBinding"].is_object() {
|
||||
@ -1026,6 +1040,8 @@ impl Backend {
|
||||
job_save(&dir, &t)?;
|
||||
}
|
||||
let response = slot_post(&dir, &t, || {
|
||||
if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); }
|
||||
self.check_dispatch()?;
|
||||
progress("98k 正在生成图片…", true);
|
||||
client.execute(request).map_err(|_| "生成连接中断,结果待核查;不会重发".into())
|
||||
})?;
|
||||
@ -1037,6 +1053,10 @@ impl Backend {
|
||||
t["requestId"] = json!(rid);
|
||||
job_save(&dir, &t)?;
|
||||
}
|
||||
if let Err(error) = self.check_model_authority(&response, key) {
|
||||
t["phase"] = json!("failed");
|
||||
return Err(error);
|
||||
}
|
||||
let (code, v) = body(response, RESPONSE_BYTES)?;
|
||||
if !(200..300).contains(&code) {
|
||||
return Err(format!("图片服务暂时未能完成请求(HTTP {code}),原请求待核查;不会重发"));
|
||||
@ -1062,6 +1082,7 @@ impl Backend {
|
||||
retain_result_expiry(&mut t, "task-result");
|
||||
return Ok(());
|
||||
}
|
||||
self.check_model_authority(&response, key)?;
|
||||
let (code, v) = body(response, RESPONSE_BYTES)?;
|
||||
if code == 202 && v["ready"] == false {
|
||||
return Err("原任务仍在生成,可继续查询进度".into());
|
||||
@ -1084,7 +1105,9 @@ impl Backend {
|
||||
if raw["model"].is_string() && raw["model"] != t["modelId"] {
|
||||
return Err("原结果与任务模型不一致,未应用".into());
|
||||
}
|
||||
job_bytes(&dir, &raw_file, &serde_json::to_vec(&raw).map_err(|_| "原响应保存失败")?).map_err(|_| "原结果保存失败,请保留原请求号")?;
|
||||
let mut safe_response = raw.clone();
|
||||
transfer::redact(&mut safe_response);
|
||||
job_bytes(&dir, &raw_file, &serde_json::to_vec(&safe_response).map_err(|_| "原响应保存失败")?).map_err(|_| "原结果保存失败,请保留原请求号")?;
|
||||
let outputs = raw["data"].as_array().filter(|a| a.len() == 1).ok_or("98k图片结果结构无法确认;不会重发")?;
|
||||
let out = &outputs[0];
|
||||
progress("正在下载并检查图片…", false);
|
||||
|
||||
@ -650,7 +650,8 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value {
|
||||
"98k连接中断,结果未知;不会重发" => "98k连接中断,结果未知;不会重发",
|
||||
"98k响应中断,结果未知;不会重发" => "98k响应中断,结果未知;不会重发",
|
||||
"原SDK请求只读定位连接中断,保留未知状态;不会重发" => "原SDK请求只读定位连接中断,保留未知状态;不会重发",
|
||||
"账户已改变,原项目和原请求已保留;请切回原账户" => "账户已改变,原项目和原请求已保留;请切回原账户",
|
||||
ACCOUNT_CHANGED | AUTH_REVOKED => error,
|
||||
"个人Key校验失败(HTTP 401)" => AUTH_REVOKED,
|
||||
"原请求待核查或已提交,禁止重发" => "原请求待核查或已提交,禁止重发",
|
||||
"原创作或生图请求待核查,禁止从Agent重新派发" => "原创作或生图请求待核查,禁止从Agent重新派发",
|
||||
"SDK输入过大" => "SDK输入过大",
|
||||
@ -658,6 +659,13 @@ fn rpc_error_frame(error: &str, new_request_preflight: bool) -> Value {
|
||||
_ => "本地SDK操作失败;请检查原请求状态,勿重发",
|
||||
};
|
||||
let mut frame = json!({"type":"error","error":safe});
|
||||
if safe == ACCOUNT_CHANGED {
|
||||
frame["category"] = json!("scope_changed");
|
||||
frame["dispatched"] = json!(false);
|
||||
} else if safe == AUTH_REVOKED {
|
||||
frame["category"] = json!("auth_revoked");
|
||||
frame["dispatched"] = json!(!new_request_preflight);
|
||||
}
|
||||
if new_request_preflight {
|
||||
if safe == "本地SDK操作失败;请检查原请求状态,勿重发" {
|
||||
frame["error"] = json!("客户端准备模型请求失败,本次未发送");
|
||||
@ -687,6 +695,12 @@ pub(super) fn run_rpc() -> R<()> {
|
||||
|
||||
type Selection = (String, String, Value, Value, Value);
|
||||
|
||||
fn check_dispatch_lease(value: &Value) -> R<()> {
|
||||
if value.is_null() || value.as_str().map(Path::new).is_some_and(|path| path.is_absolute() && path.is_file()) {
|
||||
Ok(())
|
||||
} else { Err(AUTH_REVOKED.into()) }
|
||||
}
|
||||
|
||||
fn verified_detail_model(record: &Value, input: &Value, settings: &Value, scope: &str) -> Option<Value> {
|
||||
let id = input["selectionId"].as_str()?;
|
||||
Uuid::parse_str(id).ok()?;
|
||||
@ -718,7 +732,13 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
}
|
||||
let method = input["method"].as_str().ok_or("SDK操作缺失")?;
|
||||
if !scope_matches(method, &input, &backend.scope()) {
|
||||
return Err("账户已改变,原项目和原请求已保留;请切回原账户".into());
|
||||
*selection = None;
|
||||
return Err(ACCOUNT_CHANGED.into());
|
||||
}
|
||||
if !matches!(method, "status" | "read" | "finish")
|
||||
&& let Err(error) = check_dispatch_lease(&input["dispatchLease"]) {
|
||||
*new_request_preflight = method == "request";
|
||||
return Err(error);
|
||||
}
|
||||
let project_records = backend.dir().join("pi-validation").join(&project);
|
||||
let dir = project_records.join("requests");
|
||||
@ -824,6 +844,7 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
.map(|(_, _, _, model, _)| model.clone())
|
||||
};
|
||||
if let Some(model) = scoped_model {
|
||||
backend.validate()?;
|
||||
(settings, model, "run")
|
||||
} else {
|
||||
let (settings, mut model, invocation, _) = selected(&mut backend, role)?;
|
||||
@ -909,6 +930,12 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
} else {
|
||||
request = request.bearer_auth(key);
|
||||
}
|
||||
if let Err(error) = check_dispatch_lease(&input["dispatchLease"]) {
|
||||
task["phase"] = json!("not_dispatched");
|
||||
write_task(&file, &task)?;
|
||||
*new_request_preflight = true;
|
||||
return Err(error);
|
||||
}
|
||||
request.send()
|
||||
};
|
||||
let mut raw = Vec::new();
|
||||
@ -929,6 +956,18 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
let content_type = response.headers().get("content-type").and_then(|s| s.to_str().ok()).unwrap_or("application/octet-stream").to_owned();
|
||||
response_metadata(&mut task, method, status, &content_type);
|
||||
write_task(&file, &task)?;
|
||||
if status == 401 {
|
||||
if method == "request" {
|
||||
task["phase"] = json!("failed");
|
||||
task["failureCode"] = json!("auth_revoked");
|
||||
write_task(&file, &task)?;
|
||||
}
|
||||
emit(json!({"type":"headers","status":401,"headers":{"content-type":"application/json"},"requestId":task["requestId"],"bodyHash":task["bodyHash"]}))?;
|
||||
// Refresh the model authorization catalogue for a subsequent turn.
|
||||
// The rejected request is terminal and is never replayed.
|
||||
backend.refresh_model_authority(key);
|
||||
return Err(AUTH_REVOKED.into());
|
||||
}
|
||||
emit(json!({"type":"headers","status":status,"headers":{"content-type":content_type},"requestId":task["requestId"],"bodyHash":task["bodyHash"]}))?;
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
@ -940,6 +979,7 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
append_response(&mut raw, part)?;
|
||||
emit(json!({"type":"chunk","data":STANDARD.encode(part)}))?;
|
||||
}
|
||||
transfer::check_wire(&raw)?;
|
||||
let text = std::str::from_utf8(&raw).map_err(|_| "98k响应编码无效,结果未知;不会重发")?;
|
||||
if method == "recover" {
|
||||
task["recovery"] = json!({"status":status,"at":now(),"raw":STANDARD.encode(&raw)});
|
||||
@ -994,14 +1034,16 @@ fn dispatch(input: Value, shared_http: &mut Option<NetworkClient>, selection: &m
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
if matches!(task["phase"].as_str(), Some("failed" | "unavailable"))
|
||||
&& (checked_lookup(&task).is_ok() || task["failureCode"] == "rate_limit_exceeded") {
|
||||
&& (checked_lookup(&task).is_ok() || task["failureCode"] == "rate_limit_exceeded" || task["failureCode"] == "auth_revoked") {
|
||||
// The proof and outcome already landed. A broken SDK output pipe
|
||||
// must not erase that authenticated result or reopen a terminal job.
|
||||
return Err(e);
|
||||
}
|
||||
task["phase"] = json!("unknown");
|
||||
retain_incomplete(&mut task, &raw, method == "recover")?;
|
||||
task["lastError"] = json!(&e);
|
||||
if transfer::check_wire(&raw).is_ok() {
|
||||
retain_incomplete(&mut task, &raw, method == "recover")?;
|
||||
}
|
||||
task["lastError"] = json!(transfer::redact_text(&e));
|
||||
write_task(&file, &task)?;
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,5 +1,6 @@
|
||||
//! A project file points to its sibling resource directory and its current checkpoint.
|
||||
use super::{Document, Path, PathBuf, R, Uuid, Value, fs, json, read_json, write_json};
|
||||
use super::transfer::{self, Policy, Selection};
|
||||
const CONTEXT: &str = "context.json";
|
||||
const EXTENSION: &str = "xiaoyi";
|
||||
|
||||
@ -22,15 +23,16 @@ fn project_entry(relative: &Path) -> bool {
|
||||
let Some(root) = parts.next().and_then(|part| part.to_str()) else { return false };
|
||||
if parts.next().is_none() {
|
||||
return matches!(root, "canvas.pcraft" | "context.json" | "canvas-workspace.json"
|
||||
| "creation.json" | "composer-draft.json" | ".composer-identity" | "agent-binding.json"
|
||||
| "template-workflow.json" | "template-slots.json" | "task.json" | "image-task.json" | "production-run.json")
|
||||
|| root.starts_with("material-");
|
||||
| "creation.json" | "creation-task.json" | "creation-canvas.pcraft" | "composer-draft.json" | "agent-binding.json"
|
||||
| "template-workflow.json" | "template-slots.json" | "template-input.json"
|
||||
| "task.json" | "image-task.json" | "production-run.json")
|
||||
|| root.starts_with("material-") && root.ends_with(".png");
|
||||
}
|
||||
match root {
|
||||
"agent" => relative.parent().and_then(Path::file_name).and_then(|n| n.to_str()) == Some("conversation-v1")
|
||||
&& relative.file_name().and_then(|n| n.to_str()).is_some_and(|name|
|
||||
name == "product-production-strategy.json" || name.starts_with("production-") && name.ends_with(".json")),
|
||||
"creation-assets" | "template-outputs" | "product-exports" | "composer-attachments" => true,
|
||||
"creation-assets" | "creation-generated" | "creation-tasks" | "template-outputs"
|
||||
| "product-exports" | "composer-attachments" | "reference-previews" =>
|
||||
matches!(relative.extension().and_then(|ext| ext.to_str()), Some("json" | "png" | "jpg" | "jpeg" | "webp" | "pcraft"))
|
||||
|| root == "product-exports" && matches!(relative.extension().and_then(|ext| ext.to_str()), Some("psd" | "psb")),
|
||||
"image-jobs" => relative.file_name().and_then(|name| name.to_str()).is_some_and(|name|
|
||||
matches!(name, "canvas-candidate.json" | "task.json" | "generated.png" | "failure.json" | "scene-product.png")
|
||||
|| name.starts_with("reference-") && name.ends_with(".png")),
|
||||
@ -38,7 +40,37 @@ fn project_entry(relative: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn resource_checkpoint(file: &Path, manifest: &Value) -> R<PathBuf> {
|
||||
pub(super) fn delivery_directory(project: &Path, value: &Value) -> R<Option<PathBuf>> {
|
||||
if value.is_null() { return Ok(None); }
|
||||
transfer::no_credentials(value)?;
|
||||
let path = value.as_str().map(Path::new).filter(|path| path.is_absolute())
|
||||
.ok_or("请选择绝对路径的成品目录")?;
|
||||
let draft_store = project.parent().ok_or("项目草稿目录无效")?.canonicalize().map_err(disk)?;
|
||||
// Resolve existing ancestors before creating anything, including Windows junctions.
|
||||
let mut ancestor = path;
|
||||
while !ancestor.try_exists().map_err(disk)? {
|
||||
ancestor = ancestor.parent().ok_or("成品保存位置不存在")?;
|
||||
}
|
||||
let existing = ancestor.canonicalize().map_err(disk)?;
|
||||
if !existing.is_dir() { return Err("成品保存位置必须是文件夹".into()); }
|
||||
let mut resolved = existing;
|
||||
let tail = path.strip_prefix(ancestor).map_err(|_| "成品保存位置无效")?;
|
||||
let mut normalized = false;
|
||||
for part in tail.components() {
|
||||
if part == std::path::Component::ParentDir {
|
||||
resolved.pop();
|
||||
normalized = true;
|
||||
} else {
|
||||
resolved.push(part.as_os_str());
|
||||
}
|
||||
}
|
||||
if resolved.starts_with(&draft_store) {
|
||||
return Err("请选择项目草稿目录以外的位置".into());
|
||||
}
|
||||
Ok(Some(if normalized { resolved } else { path.to_path_buf() }))
|
||||
}
|
||||
|
||||
pub(super) fn resource_checkpoint(file: &Path, manifest: &Value) -> R<PathBuf> {
|
||||
let resources = manifest["resources"].as_str().map(Path::new).filter(|path|
|
||||
matches!(path.components().next(), Some(std::path::Component::Normal(_))) && path.components().count() == 1
|
||||
).ok_or("工程资源目录无效")?;
|
||||
@ -64,59 +96,109 @@ fn copy_file(source: &Path, target: &Path, previous: Option<&Path>) -> R<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn checkpoint_file(source: &Path, output: &Path, logical: &str, previous: Option<&Path>,
|
||||
reopen: Option<(&Path, &Path)>, chat: bool) -> R<()> {
|
||||
if matches!(logical, CONTEXT | "production-run.json") || reopen.is_some() && logical.ends_with(".json") {
|
||||
let mut value = read_json(source)?;
|
||||
if let Some((old, new)) = reopen { rebase_paths(&mut value, old, new); }
|
||||
if logical == CONTEXT {
|
||||
let fields = value.as_object_mut().ok_or("工程上下文格式无效")?;
|
||||
fields.remove("projectFile");
|
||||
if !chat { fields.remove("messages"); }
|
||||
}
|
||||
if logical == "production-run.json" && value["active"] == true {
|
||||
value["active"] = json!(false);
|
||||
value["phase"] = json!("paused");
|
||||
}
|
||||
transfer::no_credentials(&value)?;
|
||||
write_json(output, &value)?;
|
||||
} else if let Some((old, new)) = reopen && logical.ends_with(".jsonl") {
|
||||
let bytes = fs::read(source).map_err(disk)?;
|
||||
transfer::check_file(logical, &bytes)?;
|
||||
let mut rebased = Vec::new();
|
||||
for line in std::str::from_utf8(&bytes).map_err(disk)?.lines().filter(|line| !line.trim().is_empty()) {
|
||||
let mut value: Value = serde_json::from_str(line).map_err(disk)?;
|
||||
rebase_paths(&mut value, old, new);
|
||||
serde_json::to_writer(&mut rebased, &value).map_err(disk)?;
|
||||
rebased.push(b'\n');
|
||||
}
|
||||
fs::write(output, rebased).map_err(disk)?;
|
||||
} else if logical.ends_with(".json") || logical.ends_with(".jsonl") {
|
||||
let bytes = fs::read(source).map_err(disk)?;
|
||||
transfer::check_file(logical, &bytes)?;
|
||||
fs::write(output, bytes).map_err(disk)?;
|
||||
} else {
|
||||
if logical.ends_with(".pcraft") { transfer::check_pcraft_file(source)?; }
|
||||
copy_file(source, output, previous)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_project(
|
||||
root: &Path, dir: &Path, target: &Path, previous: Option<&Path>, reopen: Option<(&Path, &Path)>,
|
||||
policy: &Policy<'_>, selection: &mut Selection,
|
||||
) -> R<()> {
|
||||
let relative_dir = dir.strip_prefix(root).map_err(disk)?;
|
||||
let published = (relative_dir.starts_with("product-exports") && relative_dir.components().count() == 3
|
||||
&& relative_dir.file_name().is_some_and(|name| name == "generations")).then(|| {
|
||||
let variant = dir.parent().unwrap();
|
||||
let Some(variant) = dir.parent() else { return Vec::new(); };
|
||||
["detail.json", "main_images.json", "sku_images.json"].into_iter()
|
||||
.filter_map(|name| read_json(&variant.join(name)).ok())
|
||||
.filter_map(|name| super::canvas_workspace::published_receipt(&variant.join(name)).ok())
|
||||
.filter_map(|receipt| receipt["generationId"].as_str().map(str::to_owned))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
for entry in fs::read_dir(dir).map_err(disk)? {
|
||||
let entry = entry.map_err(disk)?;
|
||||
if let Some(ids) = &published
|
||||
&& entry.file_name().to_str().is_none_or(|name| !ids.iter().any(|id| id == name)) { continue; }
|
||||
let path = entry.path();
|
||||
let relative = path.strip_prefix(root).map_err(disk)?;
|
||||
let logical = relative.to_string_lossy().replace('\\', "/");
|
||||
if let Some(ids) = &published
|
||||
&& entry.file_name().to_str().is_none_or(|name| !ids.iter().any(|id| id == name)) {
|
||||
selection.excluded.push(transfer::exclusion(&logical, "unpublished_output"));
|
||||
continue;
|
||||
}
|
||||
let kind = entry.file_type().map_err(disk)?;
|
||||
if kind.is_dir() && (dir != root || ["creation-assets", "template-outputs", "product-exports",
|
||||
"composer-attachments", "image-jobs", "agent"].iter().any(|name| relative == Path::new(name))) {
|
||||
copy_project(root, &path, target, previous, reopen)?;
|
||||
} else if kind.is_file() && project_entry(relative) {
|
||||
if kind.is_dir() && (dir != root || ["creation-assets", "creation-generated", "creation-tasks", "template-outputs",
|
||||
"product-exports", "composer-attachments", "image-jobs", "reference-previews", "agent"].iter().any(|name| relative == Path::new(name))) {
|
||||
copy_project(root, &path, target, previous, reopen, policy, selection)?;
|
||||
} else if kind.is_file() {
|
||||
let allowed = if relative.starts_with("agent") {
|
||||
policy.agent_file(&logical)
|
||||
} else if project_entry(relative) { Ok(()) } else { Err("outside_project_checkpoint") };
|
||||
if let Err(reason) = allowed {
|
||||
selection.excluded.push(transfer::exclusion(&logical, reason));
|
||||
continue;
|
||||
}
|
||||
let output = target.join(relative);
|
||||
fs::create_dir_all(output.parent().ok_or("工程资源路径无效")?).map_err(disk)?;
|
||||
if let Some((old, new)) = reopen
|
||||
&& relative.extension().and_then(|text| text.to_str()) == Some("json")
|
||||
{
|
||||
let mut value = read_json(&path)?;
|
||||
rebase_paths(&mut value, old, new);
|
||||
write_json(&output, &value)?;
|
||||
} else if relative == Path::new(CONTEXT) {
|
||||
let mut context = read_json(&path)?;
|
||||
if let Some(fields) = context.as_object_mut() { fields.remove("projectFile"); }
|
||||
write_json(&output, &context)?;
|
||||
} else {
|
||||
copy_file(&path, &output, previous.map(|p| p.join(relative)).as_deref())?;
|
||||
}
|
||||
checkpoint_file(&path, &output, &logical, previous.map(|p| p.join(relative)).as_deref(), reopen, policy.chat)?;
|
||||
selection.included.push(logical);
|
||||
} else {
|
||||
selection.excluded.push(transfer::exclusion(&logical, "outside_project_checkpoint"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_project(dir: &Path, file: &Path, manifest: &Value) -> R<()> {
|
||||
pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>) -> R<()> {
|
||||
let checkpoint = resource_checkpoint(file, manifest)?;
|
||||
let resource_dir = checkpoint.parent().ok_or("工程资源目录无效")?;
|
||||
fs::create_dir_all(resource_dir).map_err(disk)?;
|
||||
let previous = read_json(file).ok().filter(|old| old["version"] == 1 && old["localId"] == manifest["localId"]
|
||||
let previous = read_json(file).ok().filter(|old| matches!(old["version"].as_u64(), Some(1 | 2)) && old["localId"] == manifest["localId"]
|
||||
&& old["scope"] == manifest["scope"] && old["resources"] == manifest["resources"])
|
||||
.and_then(|old| resource_checkpoint(file, &old).ok())
|
||||
.filter(|previous| previous.is_dir());
|
||||
let stage = tempfile::tempdir_in(resource_dir).map_err(disk)?;
|
||||
copy_project(dir, dir, stage.path(), previous.as_deref(), None)?;
|
||||
let mut selection = Selection::default();
|
||||
copy_project(dir, dir, stage.path(), previous.as_deref(), None, policy, &mut selection)?;
|
||||
if !["canvas.pcraft", CONTEXT].into_iter().all(|required| selection.included.iter().any(|path| path == required)) {
|
||||
return Err("工程缺少必要的编辑数据,未写入工程包".into());
|
||||
}
|
||||
if !policy.chat { selection.excluded.push(transfer::exclusion("context.json#messages", "chat_history_disabled")); }
|
||||
selection.excluded.push(transfer::exclusion("pi-validation/requests", "account_local"));
|
||||
selection.excluded.push(transfer::exclusion("enterprise-templates", "account_local"));
|
||||
manifest["projectManifest"] = policy.manifest(stage.path(), selection.included, selection.excluded)?;
|
||||
transfer::no_credentials(manifest)?;
|
||||
fs::rename(stage.path(), &checkpoint).map_err(disk)?;
|
||||
if let Err(error) = write_json(file, manifest) {
|
||||
retire_checkpoint(resource_dir, &checkpoint, &manifest["localId"]);
|
||||
@ -154,11 +236,15 @@ pub(super) fn save(
|
||||
if options["project"] == true {
|
||||
let snapshot = Uuid::new_v4().to_string();
|
||||
let name = file.file_stem().and_then(|s| s.to_str()).ok_or("工程名称无效")?;
|
||||
let manifest = json!({"version":1,"localId":local,"scope":scope,"snapshot":snapshot,
|
||||
let chat = transfer::explicit_chat(&options["syncChatHistory"])?.unwrap_or_else(||
|
||||
context["projectFile"]["path"] == json!(file) && context["projectFile"]["syncChatHistory"] == true);
|
||||
let policy = Policy { chat, scope, project: local };
|
||||
let mut manifest = json!({"version":2,"localId":local,"scope":scope,"snapshot":snapshot,
|
||||
"sourceRoot":dir,"resources":format!("{name} 资源")});
|
||||
write_project(dir, &file, &manifest)?;
|
||||
context["projectFile"] = json!({"path":file,"snapshot":snapshot});
|
||||
write_project(dir, &file, &mut manifest, &policy)?;
|
||||
context["projectFile"] = json!({"path":file,"snapshot":snapshot,"syncChatHistory":chat});
|
||||
result["path"] = json!(file);
|
||||
result["localSave"] = json!({"state":"saved","path":file,"manifest":manifest["projectManifest"]});
|
||||
}
|
||||
if let Some((stage, count)) = staged {
|
||||
let name = file.file_stem().and_then(|s| s.to_str()).ok_or("工程名称无效")?;
|
||||
@ -172,9 +258,11 @@ pub(super) fn save(
|
||||
Ok(()) => {
|
||||
result["outputs"] = json!(destination);
|
||||
result["count"] = json!(count);
|
||||
result["artifactExport"] = json!({"state":"exported","path":destination,"count":count});
|
||||
}
|
||||
Err(error) if result["path"].is_string() => {
|
||||
result["outputError"] = json!(format!("工程已保存,成品文件夹写入失败:{error}"));
|
||||
result["artifactExport"] = json!({"state":"failed"});
|
||||
}
|
||||
Err(error) => return Err(disk(error)),
|
||||
};
|
||||
@ -188,6 +276,14 @@ fn rebase_paths(value: &mut Value, old: &Path, new: &Path) {
|
||||
Value::String(text) => {
|
||||
if let Ok(relative) = Path::new(text).strip_prefix(old) {
|
||||
*text = new.join(relative).to_string_lossy().into_owned();
|
||||
return;
|
||||
}
|
||||
let normalized = text.replace('\\', "/");
|
||||
let original = old.to_string_lossy().replace('\\', "/");
|
||||
if normalized == original {
|
||||
*text = new.to_string_lossy().into_owned();
|
||||
} else if let Some(relative) = normalized.strip_prefix(&original).and_then(|tail| tail.strip_prefix('/')) {
|
||||
*text = new.join(relative.split('/').collect::<PathBuf>()).to_string_lossy().into_owned();
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter_mut().for_each(|value| rebase_paths(value, old, new)),
|
||||
@ -201,12 +297,19 @@ pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R<String> {
|
||||
let manifest = read_json(&file)?;
|
||||
let resources = resource_checkpoint(&file, &manifest)?;
|
||||
if !resources.is_dir() { return Err("找不到工程资源,请把工程文件和资源文件夹放在同一位置".into()); }
|
||||
if manifest["version"] != 1 { return Err("此小壹工程需要兼容的客户端版本".into()); }
|
||||
if !matches!(manifest["version"].as_u64(), Some(1 | 2)) { return Err("此小壹工程需要兼容的客户端版本".into()); }
|
||||
transfer::no_credentials(&manifest)?;
|
||||
if manifest["scope"] != scope { return Err("请切回保存工程时使用的小壹账户".into()); }
|
||||
let id = manifest["localId"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("工程编号无效")?;
|
||||
let old = manifest["sourceRoot"].as_str().map(Path::new).filter(|path| path.is_absolute()).ok_or("工程数据目录无效")?;
|
||||
let old = manifest["sourceRoot"].as_str().filter(|path| !path.is_empty()).map(Path::new).ok_or("工程数据目录无效")?;
|
||||
let snapshot = manifest["snapshot"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("工程版本无效")?;
|
||||
let checkpoint = json!({"path":file,"snapshot":snapshot});
|
||||
let chat = if manifest["version"] == 1 {
|
||||
true
|
||||
} else {
|
||||
transfer::explicit_chat(&manifest["projectManifest"]["policy"]["syncChatHistory"])?.ok_or("工程缺少会话政策")?
|
||||
};
|
||||
let policy = Policy { chat, scope, project: id };
|
||||
let checkpoint = json!({"path":file,"snapshot":snapshot,"syncChatHistory":policy.chat});
|
||||
let destination = projects.join(id);
|
||||
if destination.exists() {
|
||||
let mut context = read_json(&destination.join(CONTEXT))?;
|
||||
@ -221,7 +324,15 @@ pub(super) fn open(file: &Path, projects: &Path, scope: &str) -> R<String> {
|
||||
}
|
||||
fs::create_dir_all(projects).map_err(disk)?;
|
||||
let stage = tempfile::tempdir_in(projects).map_err(disk)?;
|
||||
copy_project(&resources, &resources, stage.path(), None, Some((old, &destination)))?;
|
||||
let mut selection = Selection::default();
|
||||
copy_project(&resources, &resources, stage.path(), None, Some((old, &destination)), &policy, &mut selection)?;
|
||||
if manifest["version"] == 2 {
|
||||
let restored = policy.manifest(stage.path(), selection.included, selection.excluded)?;
|
||||
if manifest["projectManifest"]["version"] != 1 || restored["included"] != manifest["projectManifest"]["included"]
|
||||
|| restored["containsPiSession"] != manifest["projectManifest"]["containsPiSession"] {
|
||||
return Err("工程资源与恢复清单不一致,未导入本机".into());
|
||||
}
|
||||
}
|
||||
let mut context = read_json(&stage.path().join(CONTEXT))?;
|
||||
context["projectFile"] = checkpoint;
|
||||
write_json(&stage.path().join(CONTEXT), &context)?;
|
||||
@ -266,7 +377,7 @@ mod tests {
|
||||
let file = temp.path().join("选定的位置.xiaoyi");
|
||||
save(&root, &doc, &json!({"file":file,"project":true}), "guest", &id, &mut context).unwrap();
|
||||
let manifest = read_json(&file).unwrap();
|
||||
assert!(file.metadata().unwrap().len() < 1024);
|
||||
assert_eq!(manifest["version"], 2);
|
||||
assert!(resource_checkpoint(&file, &manifest).unwrap().join("canvas.pcraft").is_file());
|
||||
let projects = temp.path().join("new-profile");
|
||||
assert_eq!(open(&file, &projects, "guest").unwrap(), id);
|
||||
@ -276,7 +387,7 @@ mod tests {
|
||||
assert_eq!(reopened.size, doc.size);
|
||||
let metadata = read_json(&restored.join(CONTEXT)).unwrap();
|
||||
assert_eq!(metadata["composer"], context["composer"]);
|
||||
assert_eq!(metadata["messages"], context["messages"]);
|
||||
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");
|
||||
@ -298,6 +409,58 @@ mod tests {
|
||||
assert_eq!(open(&moved, &temp.path().join("another-profile"), "guest").unwrap(), id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_manifest_round_trips_with_and_without_pi_and_rejects_credential_text() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("working");
|
||||
let scope = "scope";
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let conversation = root.join("agent").join(scope).join(&id).join("conversation-v1");
|
||||
let session = conversation.join("sessions/turn.jsonl");
|
||||
fs::create_dir_all(session.parent().unwrap()).unwrap();
|
||||
let doc = Document::new("portable", Size::new(40, 30), ColorMode::Rgb, SampleType::U8);
|
||||
fs::write(root.join("canvas.pcraft"), photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap()).unwrap();
|
||||
let mut context = json!({"localId":id,"messages":[{"text":"可选的对话"}],"composer":"待发送的草稿"});
|
||||
write_json(&root.join(CONTEXT), &context).unwrap();
|
||||
write_json(&conversation.join("session.json"), &json!({"file":session})).unwrap();
|
||||
write_json(&conversation.join("pi-runtime-auth.json"), &json!({"Cookie":"fixture-vault"})).unwrap();
|
||||
fs::write(&session, format!("{}\n", json!({"type":"session","cwd":root}))).unwrap();
|
||||
for chat in [false, true] {
|
||||
let file = temp.path().join(format!("portable-{chat}.xiaoyi"));
|
||||
let options = json!({"file":file,"project":true,"syncChatHistory":chat});
|
||||
let saved = save(&root, &doc, &options, scope, &id, &mut context).unwrap();
|
||||
assert_eq!(saved["localSave"]["state"], "saved");
|
||||
assert!(saved["cloudSync"].is_null() && saved["productionDelivery"].is_null());
|
||||
let manifest = read_json(&file).unwrap();
|
||||
assert_eq!(saved["localSave"]["manifest"], manifest["projectManifest"]);
|
||||
assert_eq!(manifest["projectManifest"]["containsPiSession"], chat);
|
||||
let profile = temp.path().join(format!("clean-{chat}"));
|
||||
open(&file, &profile, scope).unwrap();
|
||||
let destination = profile.join(&id);
|
||||
assert_eq!(destination.join(session.strip_prefix(&root).unwrap()).exists(), chat);
|
||||
assert_eq!(read_json(&destination.join(CONTEXT)).unwrap().get("messages").is_some(), chat);
|
||||
assert!(!destination.join(conversation.strip_prefix(&root).unwrap()).join("pi-runtime-auth.json").exists());
|
||||
assert!(!manifest.to_string().contains("fixture-vault"));
|
||||
if chat {
|
||||
let pointer = destination.join(conversation.strip_prefix(&root).unwrap()).join("session.json");
|
||||
assert_eq!(read_json(&pointer).unwrap()["file"], json!(destination.join(session.strip_prefix(&root).unwrap())));
|
||||
fs::remove_file(resource_checkpoint(&file, &manifest).unwrap().join(session.strip_prefix(&root).unwrap())).unwrap();
|
||||
assert!(open(&file, &temp.path().join("missing-file-profile"), scope).is_err());
|
||||
}
|
||||
}
|
||||
fs::write(&session, b"{\"type\":\"message\",\"text\":\"API Key: fixture-leak-123\"}\n").unwrap();
|
||||
let blocked = temp.path().join("blocked.xiaoyi");
|
||||
let error = save(&root, &doc, &json!({"file":blocked,"project":true,"syncChatHistory":true}), scope, &id, &mut context).unwrap_err();
|
||||
assert!(!blocked.exists() && !error.contains("fixture-leak-123"));
|
||||
|
||||
let mut contaminated = doc.clone();
|
||||
contaminated.metadata.text.push(("note".into(), "Cookie: session=fixture-canvas-secret".into()));
|
||||
fs::write(root.join("canvas.pcraft"), photocraft_format::save_to_bytes(&contaminated, &Default::default()).unwrap()).unwrap();
|
||||
let blocked_canvas = temp.path().join("blocked-canvas.xiaoyi");
|
||||
let error = save(&root, &contaminated, &json!({"file":blocked_canvas,"project":true}), scope, &id, &mut context).unwrap_err();
|
||||
assert!(!blocked_canvas.exists() && !error.contains("fixture-canvas-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_and_jpg_can_be_saved_without_an_editable_checkpoint() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@ -658,9 +658,13 @@ mod tests {
|
||||
let remote = json!({"id":Uuid::new_v4().to_string(),"source":"web","revision":3,"deleteBlocked":true,"deleteBlockedReason":"pending_request"});
|
||||
let dir = b.project_dir(doc.id.0).unwrap();
|
||||
let mut context = read_json(&dir.join("context.json")).unwrap();
|
||||
assert_eq!(context["syncDirty"], true);
|
||||
// The fixture models a confirmed link to a clean copy of the web project.
|
||||
context["project"] = remote.clone();
|
||||
context["syncDirty"] = json!(false);
|
||||
write_json(&dir.join("context.json"), &context).unwrap();
|
||||
local["cloudLink"] = remote.clone();
|
||||
local["syncDirty"] = json!(false);
|
||||
let merged = b.reconcile_projects(vec![local.clone()], vec![remote.clone()], &[]).unwrap();
|
||||
assert_eq!(merged.len(), 1);
|
||||
assert_eq!(merged[0]["cloudPresent"], true);
|
||||
@ -669,15 +673,13 @@ mod tests {
|
||||
assert_eq!(b.reconcile_projects(vec![local.clone()], vec![], &[]).unwrap()[0]["cloudPresent"], false);
|
||||
assert!(b.delete_project(&local).unwrap_err().contains("尚未核对"));
|
||||
// A clean linked copy is still protected by an original unknown request.
|
||||
assert_eq!(context["syncDirty"], false);
|
||||
write_json(&dir.join("task.json"), &json!({"phase":"unknown","requestId":"original"})).unwrap();
|
||||
let kept = b.reconcile_projects(vec![local.clone()], vec![], std::slice::from_ref(&remote)).unwrap();
|
||||
assert_eq!(kept.len(), 1);
|
||||
assert_eq!(kept[0]["cloudDeleted"], true);
|
||||
assert_eq!(read_json(&dir.join("task.json")).unwrap()["requestId"], "original");
|
||||
write_json(&dir.join("task.json"), &json!({"phase":"failed","requestId":"original"})).unwrap();
|
||||
// The fixture's first save was clean. Mark a real unsynced edit explicitly
|
||||
// before testing the separate dirty-draft retention rule.
|
||||
// Mark an unsynced edit before testing dirty-draft retention.
|
||||
context["syncDirty"] = json!(true);
|
||||
local["syncDirty"] = json!(true);
|
||||
write_json(&dir.join("context.json"), &context).unwrap();
|
||||
|
||||
@ -545,6 +545,8 @@ mod tests {
|
||||
locations: HashMap::new(), last_saved: HashMap::new(), superseded_docs: Default::default(),
|
||||
draft_zip_writer: Default::default(),
|
||||
recovery_attempts: Default::default(), recovery_serial: Default::default(), composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
access: Default::default(),
|
||||
};
|
||||
let mut cache = Cache { version: 1, prompts: vec![prompt()], operations: vec![] };
|
||||
let id = cache.prompts[0].id.clone();
|
||||
@ -650,6 +652,8 @@ mod tests {
|
||||
recovery_attempts: Default::default(),
|
||||
recovery_serial: Default::default(),
|
||||
composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
access: Default::default(),
|
||||
};
|
||||
let input = json!({"accountId":"owner-b","origin":b.origin,"action":"create","title":"标题","body":"正文"});
|
||||
assert!(action(&mut b, "prompt-library-edit", &input).is_err());
|
||||
@ -722,6 +726,8 @@ mod tests {
|
||||
recovery_attempts: Default::default(),
|
||||
recovery_serial: Default::default(),
|
||||
composer_store: Default::default(),
|
||||
exit_admission_closed: Default::default(),
|
||||
access: Default::default(),
|
||||
};
|
||||
let mut cache = Cache { version: 1, ..Default::default() };
|
||||
edit(&mut cache, &json!({"action":"create","title":"标题","body":"正文"})).unwrap();
|
||||
|
||||
@ -271,7 +271,7 @@ impl Backend {
|
||||
match self.auto_recover_project_window(&local, false, budget, tx, ctx) {
|
||||
Ok(value) if !value.is_null() => {
|
||||
let _ = tx.send(Event::Json("recovery-status".into(), Ok(value)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
Err(_) | Ok(_) => {}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
//! Explicit, revision-checked native backup. The portal stores opaque files; all
|
||||
//! preview rendering and session restoration take place on this computer.
|
||||
use super::*;
|
||||
use super::transfer::{self, Policy, no_credentials};
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use photocraft_doc::LayerContent;
|
||||
use photocraft_geom::Rect;
|
||||
@ -97,7 +98,7 @@ fn safe_path(s: &str) -> R<&str> {
|
||||
Ok(s)
|
||||
}
|
||||
fn allowed_file(path: &str) -> bool {
|
||||
let roots = ["agent/", "image-jobs/", "creation-tasks/", "creation-assets/", "creation-generated/", "template-outputs/", "reference-previews/"];
|
||||
let roots = ["image-jobs/", "creation-tasks/", "creation-assets/", "creation-generated/", "template-outputs/", "reference-previews/"];
|
||||
let exact = [
|
||||
"agent-binding.json",
|
||||
"task.json",
|
||||
@ -112,40 +113,6 @@ fn allowed_file(path: &str) -> bool {
|
||||
(exact.contains(&path) || roots.iter().any(|p| path.starts_with(p)))
|
||||
&& matches!(Path::new(path).extension().and_then(|e| e.to_str()), Some("json" | "jsonl" | "wasm" | "png" | "jpg" | "jpeg" | "webp" | "pcraft"))
|
||||
}
|
||||
fn no_credentials(value: &Value) -> R<()> {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
for (key, value) in map {
|
||||
let key = key.to_ascii_lowercase();
|
||||
if ["authorization", "api_key", "apikey", "access_token", "refresh_token", "password", "secretkey"].contains(&key.as_str())
|
||||
|| (key == "key" && value.as_str().is_some_and(|s| s.starts_with("sk-")))
|
||||
{
|
||||
return Err("项目文件含连接凭据,未上传;请移除该文件中的凭据后再同步".into());
|
||||
}
|
||||
no_credentials(value)?;
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for item in items {
|
||||
no_credentials(item)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_text(path: &str, bytes: &[u8]) -> R<()> {
|
||||
if path.ends_with(".json") {
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| "项目JSON损坏,尚未同步")?;
|
||||
no_credentials(&value)?;
|
||||
} else if path.ends_with(".jsonl") {
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| "Agent会话编码无效,尚未同步")?;
|
||||
for line in text.lines().filter(|line| !line.trim().is_empty()) {
|
||||
no_credentials(&serde_json::from_str::<Value>(line).map_err(|_| "Agent会话记录不完整,请保留原文件")?)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn collect_files(base: &Path, path: &Path, prefix: &str, depth: usize, files: &mut Vec<Value>, total: &mut u64) -> R<()> {
|
||||
if !path.exists() {
|
||||
return Ok(());
|
||||
@ -178,7 +145,7 @@ fn collect_files(base: &Path, path: &Path, prefix: &str, depth: usize, files: &m
|
||||
return Err("会话附件超过256MiB或2048项,尚未同步".into());
|
||||
}
|
||||
let bytes = fs::read(path).map_err(|_| "会话文件无法读取")?;
|
||||
check_text(&relative, &bytes)?;
|
||||
transfer::check_file(&logical, &bytes)?;
|
||||
*total = total.saturating_add(bytes.len() as u64);
|
||||
files.push(json!({"path":logical,"sha256":digest(&bytes),"data":STANDARD.encode(bytes)}));
|
||||
}
|
||||
@ -187,9 +154,12 @@ fn collect_files(base: &Path, path: &Path, prefix: &str, depth: usize, files: &m
|
||||
|
||||
struct BackupSource { path: PathBuf, entry: Value }
|
||||
|
||||
fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, depth: usize, files: &mut Vec<BackupSource>, total: &mut u64) -> R<()> {
|
||||
fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, files: &mut Vec<BackupSource>, total: &mut u64,
|
||||
policy: &Policy<'_>, excluded: &mut Vec<Value>) -> R<()> {
|
||||
if !path.exists() { return Ok(()); }
|
||||
if depth > 12 { return Err("会话目录层级过多,尚未同步".into()); }
|
||||
let relative = path.strip_prefix(base).map_err(|_| "项目路径无效")?;
|
||||
if relative.components().count() > 12 { return Err("会话目录层级过多,尚未同步".into()); }
|
||||
if prefix == "project/" && relative.starts_with("sync-staging") { return Ok(()); }
|
||||
let meta = fs::symlink_metadata(path).map_err(|_| "项目文件不可读取")?;
|
||||
if meta.file_type().is_symlink() || !path.canonicalize().map_err(|_| "项目路径无效")?.starts_with(base.canonicalize().map_err(|_| "项目路径无效")?) {
|
||||
return Err("项目包含目录链接,尚未同步".into());
|
||||
@ -197,16 +167,29 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, depth: usize,
|
||||
if meta.is_dir() {
|
||||
let mut entries = fs::read_dir(path).map_err(|_| "会话目录无法读取")?.collect::<Result<Vec<_>, _>>().map_err(|_| "会话目录无法读取")?;
|
||||
entries.sort_by_key(|entry| entry.file_name());
|
||||
for entry in entries { collect_backup_sources(base, &entry.path(), prefix, depth + 1, files, total)?; }
|
||||
for entry in entries { collect_backup_sources(base, &entry.path(), prefix, files, total, policy, excluded)?; }
|
||||
} else if meta.is_file() {
|
||||
let relative = path.strip_prefix(base).map_err(|_| "项目路径无效")?.to_string_lossy().replace('\\', "/");
|
||||
let relative = relative.to_string_lossy().replace('\\', "/");
|
||||
let logical = format!("{prefix}{relative}");
|
||||
if prefix == "project/" {
|
||||
let allowed = if relative.starts_with("agent/") { policy.agent_file(&relative) }
|
||||
else if allowed_file(&relative) { Ok(()) } else { Err("outside_sync_scope") };
|
||||
if let Err(reason) = allowed {
|
||||
if !matches!(relative.as_str(), "context.json" | "canvas.pcraft" | "cloud-sync.json") {
|
||||
excluded.push(transfer::exclusion(&logical, reason));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if prefix == "requests/" && (!relative.ends_with(".json") || relative.contains('/')) {
|
||||
excluded.push(transfer::exclusion(&logical, "outside_sync_scope"));
|
||||
return Ok(());
|
||||
}
|
||||
safe_path(&logical)?;
|
||||
if prefix == "project/" && !allowed_file(&relative) { return Ok(()); }
|
||||
if prefix == "requests/" && (!relative.ends_with(".json") || relative.contains('/')) { return Ok(()); }
|
||||
if files.len() >= FILES_LIMIT || total.saturating_add(meta.len()) > SESSION_FILES_LIMIT { return Err("项目附件超过1GiB或2048项,尚未同步".into()); }
|
||||
if meta.len() == 0 {
|
||||
check_text(&relative, &[])?;
|
||||
if relative.ends_with(".pcraft") { return Err("项目画布为空,尚未备份".into()); }
|
||||
transfer::check_file(&logical, &[])?;
|
||||
files.push(BackupSource { path: path.to_owned(), entry: json!({"path":logical,"sha256":digest(&[]),"size":0,"data":""}) });
|
||||
return Ok(());
|
||||
}
|
||||
@ -214,7 +197,7 @@ fn collect_backup_sources(base: &Path, path: &Path, prefix: &str, depth: usize,
|
||||
let inline_size = files.iter().filter(|file| file.entry["source"].is_null()).filter_map(|file| file.entry["size"].as_u64()).sum::<u64>();
|
||||
if inline_size.saturating_add(meta.len()) > BACKUP_LIMIT { return Err("会话附件超过256MiB,尚未同步".into()); }
|
||||
let bytes = fs::read(path).map_err(|_| "会话文件无法读取")?;
|
||||
check_text(&relative, &bytes)?;
|
||||
transfer::check_file(&logical, &bytes)?;
|
||||
*total = total.saturating_add(bytes.len() as u64);
|
||||
files.push(BackupSource { path: path.to_owned(), entry: json!({"path":logical,"sha256":digest(&bytes),"size":bytes.len(),"data":STANDARD.encode(bytes)}) });
|
||||
return Ok(());
|
||||
@ -578,9 +561,11 @@ impl Backend {
|
||||
value["status"] = json!(state);
|
||||
value["syncDirty"] = json!(true);
|
||||
write_json(&dir.join("context.json"), &value)?;
|
||||
Ok(json!({"doc":id,"status":state,"revision":value["revision"],"projects":self.native_projects()?}))
|
||||
Ok(json!({"doc":id,"status":state,"revision":value["revision"],"accountId":self.auth["account"]["id"],
|
||||
"origin":self.origin,"projectState":{"state":state},"projects":self.native_projects()?}))
|
||||
}
|
||||
fn put_sync_json(&self, id: &str, value: &Value) -> R<Value> {
|
||||
self.check_dispatch()?;
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let response = self
|
||||
.http
|
||||
@ -589,6 +574,7 @@ impl Backend {
|
||||
.json(value)
|
||||
.send()
|
||||
.map_err(|_| "云同步结果未确认,本机文件和同步身份已保留;请刷新核对")?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
let (code, value) = body(response, MAX_JSON)?;
|
||||
if code != 200 {
|
||||
return Err(request_error(code));
|
||||
@ -603,6 +589,7 @@ impl Backend {
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.map_err(|_| "云端状态暂时无法核对,本机草稿保留")?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
let (code, value) = body(response, MAX_JSON)?;
|
||||
if code == 404 {
|
||||
Ok(None)
|
||||
@ -613,6 +600,7 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
fn upload_native(&self, id: &str, path: &Path, sha: &str, size: u64) -> R<()> {
|
||||
self.check_dispatch()?;
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
let file = fs::File::open(path).map_err(|_| "本机同步文件无法读取")?;
|
||||
let response = self
|
||||
@ -626,12 +614,20 @@ impl Backend {
|
||||
.body(reqwest::blocking::Body::new(file))
|
||||
.send()
|
||||
.map_err(|_| "文件上传中断,本机项目保留;可重新同步,已存相同内容不会重复占空间")?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
let (code, value) = body(response, MAX_JSON)?;
|
||||
if code != 200 || value["sha256"] != sha {
|
||||
return Err(request_error(code));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn check_cloud_authority(&self, status: u16) -> R<()> {
|
||||
if status != 401 { return Ok(()); }
|
||||
self.revoke_access("auth_revoked");
|
||||
let _ = self.clone().renew_portal_session();
|
||||
Err(request_error(status))
|
||||
}
|
||||
|
||||
pub(super) fn sync_project(&mut self, input: &Value) -> R<Value> {
|
||||
let id = input["doc"].as_u64();
|
||||
let local_id = if let Some(local) = input["localId"].as_str() {
|
||||
@ -675,24 +671,40 @@ impl Backend {
|
||||
let canvas = stage.join("canvas.pcraft");
|
||||
fs::copy(dir.join("canvas.pcraft"), &canvas).map_err(|_| "本机工程快照无法准备")?;
|
||||
let (canvas_sha, canvas_size) = file_digest(&canvas)?;
|
||||
transfer::check_pcraft_file(&canvas)?;
|
||||
let doc = photocraft_format::load_path(&canvas).map_err(|_| "本机工程读取失败,旧草稿保留")?;
|
||||
if state == "completed" && doc.layers.is_empty() {
|
||||
return Err("空白画布不能标记完结,请先完成详情页内容".into());
|
||||
}
|
||||
let rectangles = screen_rects(&doc)?;
|
||||
let mut files = Vec::new();
|
||||
let mut excluded = Vec::new();
|
||||
let mut total = 0;
|
||||
collect_backup_sources(&dir, &dir, "project/", 0, &mut files, &mut total)?;
|
||||
let scope = self.scope();
|
||||
let policy = Policy { chat: transfer::explicit_chat(&input["syncChatHistory"])?.unwrap_or(false), scope: &scope, project: &local_id };
|
||||
collect_backup_sources(&dir, &dir, "project/", &mut files, &mut total, &policy, &mut excluded)?;
|
||||
let requests = self.dir().join("pi-validation").join(&local_id).join("requests");
|
||||
collect_backup_sources(&requests, &requests, "requests/", 0, &mut files, &mut total)?;
|
||||
collect_backup_sources(&requests, &requests, "requests/", &mut files, &mut total, &policy, &mut excluded)?;
|
||||
for file in files.iter().filter(|file| file.entry["source"].is_string()) {
|
||||
transfer::check_pcraft_file(&file.path)?;
|
||||
}
|
||||
if !policy.chat { excluded.push(transfer::exclusion("project/context.json#messages", "chat_history_disabled")); }
|
||||
let included = files.iter().filter_map(|file| file.entry["path"].as_str().map(str::to_owned))
|
||||
.chain(["project/canvas.pcraft".into(), "project/context.json".into()]).collect();
|
||||
let sync_manifest = policy.manifest(&dir, included, excluded)?;
|
||||
let conversation = recovery_summary(&dir, &requests)?;
|
||||
no_credentials(&json!(conversation))?;
|
||||
let backup_version = if files.iter().any(|file| file.entry["source"].is_string()) { 2 } else { 1 };
|
||||
let backup = json!({"version":backup_version,"localId":local_id,"accountScope":self.scope(),"oldProjectRoot":dir.to_string_lossy(),"files":files.iter().map(|file|file.entry.clone()).collect::<Vec<_>>()});
|
||||
let backup = json!({"version":backup_version,"localId":local_id,"accountScope":scope,"oldProjectRoot":dir.to_string_lossy(),"syncManifest":sync_manifest,"files":files.iter().map(|file|file.entry.clone()).collect::<Vec<_>>()});
|
||||
no_credentials(&backup)?;
|
||||
write_json(&stage.join("session-backup.json"), &backup)?;
|
||||
let mut snapshot = context.clone();
|
||||
for key in ["doc", "path", "time", "cloudSyncedAt", "syncedRevision", "syncDirty", "cloudLink"] {
|
||||
for key in ["doc", "path", "time", "projectFile", "cloudSyncedAt", "syncedRevision", "syncDirty", "cloudLink"] {
|
||||
snapshot.as_object_mut().ok_or("项目上下文无效")?.remove(key);
|
||||
}
|
||||
if !policy.chat {
|
||||
snapshot.as_object_mut().ok_or("项目上下文无效")?.remove("messages");
|
||||
}
|
||||
let previous_project = context["project"].clone();
|
||||
snapshot["project"] = json!({});
|
||||
for key in ["document", "materialReferences"] {
|
||||
@ -736,6 +748,7 @@ impl Backend {
|
||||
let bytes = fs::read(&creation.path).map_err(|_| "创作资料备份无效")?;
|
||||
document["creation"] = super::creation::cloud_creation(&serde_json::from_slice::<Value>(&bytes).map_err(|_| "创作资料备份格式无效")?)?;
|
||||
}
|
||||
no_credentials(&document)?;
|
||||
let source_web = if linked["source"] == "web" { linked["id"].clone() } else { linked["sourceWebId"].clone() };
|
||||
if cloud_revision > 0 || pending["id"] == cloud_id {
|
||||
if let Some(remote) = self.cloud_snapshot(&cloud_id)? {
|
||||
@ -744,7 +757,7 @@ impl Backend {
|
||||
let rev = remote["revision"].as_u64().ok_or("云端版本无效")?;
|
||||
let context = finish_sync(&dir, &cloud_id, rev, revision, state, &source_web, &identity)?;
|
||||
return Ok(
|
||||
json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":rev,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"projects":self.projects()?,"reconciled":true}),
|
||||
json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":rev,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"reconciled":true,"cloudSync":{"state":"synced","revision":rev,"manifest":sync_manifest}}),
|
||||
);
|
||||
}
|
||||
if cloud_revision == 0 && remote["document"]["native"]["documentSource"].is_null() {
|
||||
@ -792,6 +805,7 @@ impl Backend {
|
||||
}
|
||||
let token = self.auth["access_token"].as_str().ok_or("请先登录素材库")?;
|
||||
for (source, bytes) in previews {
|
||||
self.check_dispatch()?;
|
||||
let response = self
|
||||
.http
|
||||
.put(format!("{}/api/desktop/projects/desktop/{cloud_id}/assets/{source}", self.origin))
|
||||
@ -800,6 +814,7 @@ impl Backend {
|
||||
.body(bytes)
|
||||
.send()
|
||||
.map_err(|_| "预览上传中断,本机项目保留")?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
let (code, _) = body(response, MAX_JSON)?;
|
||||
if code != 200 {
|
||||
return Err(request_error(code));
|
||||
@ -815,7 +830,7 @@ impl Backend {
|
||||
let context = finish_sync(&dir, &cloud_id, remote_revision, revision, state, &source_web, &identity)?;
|
||||
write_json(&pending_file, &json!({"id":cloud_id,"revision":remote_revision,"localRevision":revision,"phase":"complete"}))?;
|
||||
Ok(
|
||||
json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":remote_revision,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"projects":self.projects()?}),
|
||||
json!({"doc":id,"revision":revision,"localId":local_id,"cloudLink":context["project"],"cloudRevision":remote_revision,"syncedRevision":revision,"syncDirty":context["syncDirty"],"status":context["status"],"accountId":self.auth["account"]["id"],"origin":self.origin,"cloudSync":{"state":"synced","revision":remote_revision,"manifest":sync_manifest}}),
|
||||
)
|
||||
}
|
||||
fn native_bytes(&self, id: &str, source: &str, size: u64, sha: &str) -> R<Vec<u8>> {
|
||||
@ -830,6 +845,7 @@ impl Backend {
|
||||
.timeout(Duration::from_secs(300))
|
||||
.send()
|
||||
.map_err(|_| "工程下载中断,本机项目保留")?;
|
||||
self.check_cloud_authority(response.status().as_u16())?;
|
||||
if response.status().as_u16() != 200 {
|
||||
return Err(request_error(response.status().as_u16()));
|
||||
}
|
||||
@ -931,6 +947,13 @@ impl Backend {
|
||||
return Err("会话备份账户或项目不一致".into());
|
||||
}
|
||||
let files = backup["files"].as_array().filter(|v| v.len() <= FILES_LIMIT).ok_or("会话备份清单无效")?;
|
||||
let scope = self.scope();
|
||||
let sync_manifest = &backup["syncManifest"];
|
||||
let chat = if sync_manifest.is_null() { true } else {
|
||||
transfer::explicit_chat(&sync_manifest["policy"]["syncChatHistory"])?.ok_or("云工程缺少会话政策")?
|
||||
};
|
||||
let policy = Policy { chat, scope: &scope, project: &source_local_id };
|
||||
no_credentials(&backup)?;
|
||||
let request_target = account.join("pi-validation").join(&local_id).join("requests");
|
||||
if request_target.exists() && existing.is_none() {
|
||||
return Err("本机已有此项目原请求日志,未覆盖;请先保留并核对原项目".into());
|
||||
@ -954,7 +977,11 @@ impl Backend {
|
||||
return Err("备份文件重复".into());
|
||||
}
|
||||
let relative = if let Some(p) = name.strip_prefix("project/") {
|
||||
if !allowed_file(p) {
|
||||
let agent = p.starts_with("agent/") && if sync_manifest.is_null() {
|
||||
// V1/V2 backups that predate the explicit policy used the old path contract.
|
||||
matches!(Path::new(p).extension().and_then(|ext| ext.to_str()), Some("json" | "jsonl" | "wasm" | "png" | "jpg" | "jpeg" | "webp" | "pcraft"))
|
||||
} else { policy.agent_file(p).is_ok() };
|
||||
if !allowed_file(p) && !agent {
|
||||
return Err("备份文件不在白名单".into());
|
||||
}
|
||||
p
|
||||
@ -976,7 +1003,8 @@ impl Backend {
|
||||
if total > limit || digest(&bytes) != file["sha256"] {
|
||||
return Err("会话备份校验失败".into());
|
||||
}
|
||||
check_text(relative, &bytes)?;
|
||||
transfer::check_file(name, &bytes)?;
|
||||
if relative.ends_with(".pcraft") { transfer::check_pcraft(&bytes)?; }
|
||||
let bytes = restored_bytes(relative, &bytes, old_root, &new_root)?;
|
||||
let target = staging.join(relative);
|
||||
if let Some(parent) = target.parent() {
|
||||
@ -984,6 +1012,15 @@ impl Backend {
|
||||
}
|
||||
photocraft_format::atomic_write(&target, &bytes).map_err(|_| "会话恢复未完成,本机旧文件保留")?;
|
||||
}
|
||||
if !sync_manifest.is_null() {
|
||||
let included = seen.into_iter().chain(["project/canvas.pcraft".into(), "project/context.json".into()]).collect();
|
||||
let restored = policy.manifest(&staging, included, Vec::new())?;
|
||||
if sync_manifest["version"] != 1 || restored["included"] != sync_manifest["included"]
|
||||
|| restored["containsPiSession"] != sync_manifest["containsPiSession"]
|
||||
|| !policy.chat && context.get("messages").is_some() {
|
||||
return Err("同步清单与实际恢复文件不一致".into());
|
||||
}
|
||||
}
|
||||
if let Some(existing) = &existing {
|
||||
// Keep terminal original request journals active as well as in
|
||||
// the rollback copy. Differing records require explicit review.
|
||||
@ -1005,6 +1042,7 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
photocraft_format::atomic_write(&staging.join("canvas.pcraft"), data.get("canvas.pcraft").ok_or("工程文件缺失")?).map_err(|_| "工程写入失败")?;
|
||||
transfer::check_pcraft(data.get("canvas.pcraft").ok_or("工程文件缺失")?)?;
|
||||
let mut doc = photocraft_format::load_path(&staging.join("canvas.pcraft")).map_err(|_| "云工程格式不可读取,未替换旧项目")?;
|
||||
doc.id = photocraft_doc::DocId::fresh();
|
||||
context["doc"] = json!(doc.id.0);
|
||||
@ -1445,7 +1483,9 @@ mod tests {
|
||||
assert!(no_credentials(&json!({"nested":{"apiKey":"hidden"}})).is_err());
|
||||
assert!(no_credentials(&json!({"keyFingerprint":"hash","requestId":"original","phase":"unknown"})).is_ok());
|
||||
assert!(!allowed_file("settings.json"));
|
||||
assert!(allowed_file("agent/a/b/sessions/session.jsonl"));
|
||||
assert!(!allowed_file("agent/a/b/sessions/session.jsonl"));
|
||||
assert!(no_credentials(&json!({"text":"服务返回 Authorization: Bearer test-secret"})).is_err());
|
||||
assert!(no_credentials(&json!({"text":"连接 Cookie=session=secret"})).is_err());
|
||||
assert!(allowed_file("creation-tasks/task.json"));
|
||||
assert!(allowed_file("canvas-workspace.json"));
|
||||
assert!(allowed_file("image-jobs/00000000-0000-4000-8000-000000000001/canvas-candidate.json"));
|
||||
@ -1472,7 +1512,8 @@ mod tests {
|
||||
fs::File::create(&file).unwrap().set_len(BACKUP_LIMIT + 1).unwrap();
|
||||
let mut sources = Vec::new();
|
||||
let mut total = 0;
|
||||
collect_backup_sources(&dir, &dir, "project/", 0, &mut sources, &mut total).unwrap();
|
||||
let policy = Policy { chat: false, scope: "scope", project: "project" };
|
||||
collect_backup_sources(&dir, &dir, "project/", &mut sources, &mut total, &policy, &mut Vec::new()).unwrap();
|
||||
assert_eq!(total, BACKUP_LIMIT + 1);
|
||||
assert_eq!(sources.len(), 1);
|
||||
assert_eq!(sources[0].path, file);
|
||||
@ -1483,6 +1524,31 @@ mod tests {
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn sync_defaults_to_production_journals_and_validates_explicit_pi_opt_in() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let conversation = dir.join("agent/scope/project/conversation-v1");
|
||||
let session = conversation.join("sessions/turn.jsonl");
|
||||
write_json(&conversation.join("session.json"), &json!({"file":session})).unwrap();
|
||||
write_json(&conversation.join("production-detail-blue.json"), &json!({"state":"pending"})).unwrap();
|
||||
write_json(&conversation.join("events.jsonl"), &json!({"event":"private local diagnostics"})).unwrap();
|
||||
fs::create_dir_all(session.parent().unwrap()).unwrap();
|
||||
fs::write(&session, b"{\"text\":\"Bearer fixture-auth-secret\"}\n").unwrap();
|
||||
let mut policy = Policy { chat: false, scope: "scope", project: "project" };
|
||||
let (mut files, mut excluded, mut total) = (Vec::new(), Vec::new(), 0);
|
||||
collect_backup_sources(dir, dir, "project/", &mut files, &mut total, &policy, &mut excluded).unwrap();
|
||||
assert_eq!(files.len(), 1);
|
||||
let included = vec![files[0].entry["path"].as_str().unwrap().to_owned()];
|
||||
let manifest = policy.manifest(dir, included, excluded).unwrap();
|
||||
assert_eq!(manifest["containsPiSession"], false);
|
||||
assert_eq!(manifest["policy"]["syncChatHistory"], false);
|
||||
assert!(manifest["excluded"].as_array().unwrap().iter().any(|item| item["reason"] == "chat_history_disabled"));
|
||||
assert!(manifest["excluded"].as_array().unwrap().iter().any(|item| item["reason"] == "agent_private"));
|
||||
policy.chat = true;
|
||||
let error = collect_backup_sources(dir, dir, "project/", &mut Vec::new(), &mut 0, &policy, &mut Vec::new()).err().unwrap();
|
||||
assert!(!error.contains("fixture-auth-secret"));
|
||||
}
|
||||
#[test]
|
||||
fn real_native_file_and_unknown_session_round_trip_without_a_model_post() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let origin = format!("http://{}", listener.local_addr().unwrap());
|
||||
@ -1491,7 +1557,7 @@ mod tests {
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut uploaded = HashMap::new();
|
||||
let mut revision = 0;
|
||||
for _ in 0..14 {
|
||||
for _ in 0..12 {
|
||||
let (mut socket, _) = listener.accept().unwrap();
|
||||
let (head, payload) = read_request(&mut socket);
|
||||
assert!(head.to_ascii_lowercase().contains("authorization: bearer fixture-token"));
|
||||
@ -1540,14 +1606,22 @@ mod tests {
|
||||
fs::create_dir_all(dir.join("template-outputs")).unwrap();
|
||||
fs::copy(dir.join("canvas.pcraft"), dir.join("template-outputs/edited.pcraft")).unwrap();
|
||||
write_json(&dir.join("creation.json"), &json!({"version":1,"revision":2,"width":1440,"brief":{"source":"upload","name":"真实资料备份","brandId":"","brandName":"","identifierType":"sku","identifier":"","variant":"","colorMaterialId":"","colorName":"","dimensions":{"length":"","width":"","height":"","unit":"mm"},"images":[],"note":""},"facts":{"status":"idle","items":[],"missing":[]},"sellingPoints":{"batches":[],"selected":[],"direction":"","stale":false},"plan":{"status":"idle","screens":[],"invalidReason":"","confirmedAt":null,"confirmedInput":null},"designSnapshot":null,"generation":null})).unwrap();
|
||||
let session = dir.join("agent").join(b.scope()).join(&b.locations[&did]).join("binding").join("session.jsonl");
|
||||
let conversation = dir.join("agent").join(b.scope()).join(&b.locations[&did]).join("conversation-v1");
|
||||
let session = conversation.join("sessions/session.jsonl");
|
||||
fs::create_dir_all(session.parent().unwrap()).unwrap();
|
||||
fs::write(&session, format!("{{\"type\":\"session\",\"cwd\":{}}}\n", serde_json::to_string(&dir.to_string_lossy()).unwrap())).unwrap();
|
||||
write_json(&conversation.join("session.json"), &json!({"file":session})).unwrap();
|
||||
write_json(&conversation.join("pi-runtime-auth.json"), &json!({"Cookie":"secret"})).unwrap();
|
||||
let requests = b.dir().join("pi-validation").join(&b.locations[&did]).join("requests");
|
||||
write_json(&requests.join("original.json"), &json!({"id":"original","requestId":"customer-original","phase":"unknown","keyFingerprint":"hash-only"}))
|
||||
.unwrap();
|
||||
let response = b.sync_project(&json!({"doc":did,"revision":7,"status":"draft"})).unwrap();
|
||||
let response = b.sync_project(&json!({"doc":did,"revision":7,"status":"draft","syncChatHistory":true})).unwrap();
|
||||
assert_eq!(response["syncedRevision"], 7);
|
||||
assert_eq!(response["cloudSync"]["state"], "synced");
|
||||
assert_eq!(response["cloudSync"]["manifest"]["containsPiSession"], true);
|
||||
assert!(response["cloudSync"]["manifest"]["excluded"].as_array().unwrap().iter()
|
||||
.any(|entry| entry["path"].as_str().unwrap().ends_with("pi-runtime-auth.json")));
|
||||
assert!(response["localSave"].is_null() && response["productionDelivery"].is_null());
|
||||
let cloud = remote.lock().unwrap().clone();
|
||||
assert_eq!(cloud["document"]["version"], 3);
|
||||
let mut other = fixture(&origin);
|
||||
@ -1566,6 +1640,7 @@ mod tests {
|
||||
assert!(super::super::projects::idle(&restored_dir).is_err());
|
||||
let restored_session = restored_dir.join(session.strip_prefix(&dir).unwrap());
|
||||
assert!(fs::read_to_string(restored_session).unwrap().contains(&serde_json::to_string(&restored_dir.to_string_lossy()).unwrap()));
|
||||
assert!(!restored_dir.join(conversation.strip_prefix(&dir).unwrap()).join("pi-runtime-auth.json").exists());
|
||||
assert!(other.restore_native_project(&cloud).unwrap_err().contains("未覆盖"));
|
||||
server.join().unwrap();
|
||||
fs::remove_dir_all(&b.root).unwrap();
|
||||
|
||||
@ -356,6 +356,9 @@ impl Backend {
|
||||
Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"workflow":workflow,"creation":c,"pending":workflow["pending"]}))
|
||||
}
|
||||
pub(super) fn slot_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
if !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted") {
|
||||
self.check_dispatch()?;
|
||||
}
|
||||
if matches!(method, "slot-skeleton" | "slot-append" | "slot-adopt-prep" | "slot-edit-prep" | "slot-adopted" | "slot-templates" | "slot-product-export" | "slot-product-view")
|
||||
|| matches!(method, "slot-read" | "slot-recover" | "slot-reuse")
|
||||
&& self.project_dir(input["doc"].as_u64().ok_or("请先打开项目")?)?.join("canvas-workspace.json").is_file()
|
||||
@ -463,7 +466,7 @@ impl Backend {
|
||||
template_slots::reserve_candidate(&dir, id, letter, settings["imageModel"].as_str().ok_or("请选择生图模型")?, &prompt, &refs, rev(&state))?;
|
||||
let binding = template_slots::binding(&state, id, letter)?;
|
||||
let _ = events.send(Event::Json("slot-progress".into(), self.slot_result(doc, &dir)));
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
let profile = &c["designSnapshot"]["brand"]["profile"];
|
||||
let visual =
|
||||
profile["visualRules"].as_object().map(|m| m.values().filter_map(Value::as_str).collect::<Vec<_>>().join("\n")).unwrap_or_default();
|
||||
@ -531,7 +534,7 @@ impl Backend {
|
||||
} else {
|
||||
return Err("图位操作不存在".into());
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
self.slot_result(doc, &dir)
|
||||
}
|
||||
}
|
||||
|
||||
217
apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs
Normal file
217
apps/detail-photocraft/apps/photocraft/src/jiansun_transfer.rs
Normal file
@ -0,0 +1,217 @@
|
||||
//! Data that can leave the account's working directory.
|
||||
use super::{Path, R, Value, json};
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const CREDENTIAL_ERROR: &str = "项目资料含连接凭据,未写入备份";
|
||||
|
||||
static CREDENTIAL_TEXT: LazyLock<Regex> = LazyLock::new(|| {
|
||||
#[allow(clippy::expect_used)]
|
||||
Regex::new(concat!(
|
||||
r#"(?i)\b(?:authorization|(?:set[-_ ]?)?cookie|x[-_ ]?api[-_ ]?key|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|password|secret[-_ ]?key)["']?\s*[:=]\s*[^\r\n]+"#,
|
||||
r#"|\bbearer[ \t]+[a-z0-9._~+/=-]{4,}"#,
|
||||
r#"|\b(?:sk-(?:proj-)?|dcs_|dca_)[a-z0-9_-]{16,}"#,
|
||||
)).expect("constant credential pattern")
|
||||
});
|
||||
|
||||
fn credential_key(key: &str) -> bool {
|
||||
let key: String = key.chars().filter(|c| !matches!(c, '-' | '_' | ' ')).flat_map(char::to_lowercase).collect();
|
||||
matches!(key.as_str(), "authorization" | "cookie" | "setcookie" | "apikey" | "xapikey"
|
||||
| "accesstoken" | "refreshtoken" | "password" | "secretkey" | "credentials" | "privatekey" | "token" | "composerdrafttoken")
|
||||
}
|
||||
|
||||
fn credential_field(key: &str, value: &Value) -> bool {
|
||||
credential_key(key) || CREDENTIAL_TEXT.is_match(key)
|
||||
|| key.eq_ignore_ascii_case("key") && value.as_str().is_some_and(|text| text.starts_with("sk-"))
|
||||
}
|
||||
|
||||
pub(crate) fn redact_text(text: &str) -> String {
|
||||
CREDENTIAL_TEXT.replace_all(text, "[已脱敏]").into_owned()
|
||||
}
|
||||
|
||||
pub(super) fn redact(value: &mut Value) {
|
||||
match value {
|
||||
Value::String(text) => {
|
||||
if let std::borrow::Cow::Owned(safe) = CREDENTIAL_TEXT.replace_all(text.as_str(), "[已脱敏]") {
|
||||
*text = safe;
|
||||
}
|
||||
}
|
||||
Value::Array(values) => values.iter_mut().for_each(redact),
|
||||
Value::Object(fields) => {
|
||||
fields.retain(|key, value| !credential_field(key, value));
|
||||
fields.values_mut().for_each(redact);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn no_credentials(value: &Value) -> R<()> {
|
||||
match value {
|
||||
Value::String(text) if CREDENTIAL_TEXT.is_match(text) => return Err(CREDENTIAL_ERROR.into()),
|
||||
Value::Array(items) => for item in items { no_credentials(item)?; },
|
||||
Value::Object(fields) => for (key, item) in fields {
|
||||
if credential_field(key, item) {
|
||||
return Err(CREDENTIAL_ERROR.into());
|
||||
}
|
||||
no_credentials(item)?;
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn check_wire(bytes: &[u8]) -> R<()> {
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| "模型响应编码无效")?;
|
||||
if CREDENTIAL_TEXT.is_match(text) { return Err(CREDENTIAL_ERROR.into()); }
|
||||
if let Ok(value) = serde_json::from_str(text) { no_credentials(&value)?; }
|
||||
let mut deltas = HashMap::<(&str, u64), String>::new();
|
||||
for line in text.lines().filter_map(|line| line.strip_prefix("data:")) {
|
||||
let Ok(value) = serde_json::from_str::<Value>(line.trim_start()) else { continue };
|
||||
no_credentials(&value)?;
|
||||
let delta = &value["delta"];
|
||||
let index = value["index"].as_u64().or(value["output_index"].as_u64()).unwrap_or(0);
|
||||
for (kind, part) in [("text", delta["text"].as_str()), ("thinking", delta["thinking"].as_str()),
|
||||
("tool", delta["partial_json"].as_str()), ("responses", delta.as_str())] {
|
||||
if let Some(part) = part { deltas.entry((kind, index)).or_default().push_str(part); }
|
||||
}
|
||||
for choice in value["choices"].as_array().into_iter().flatten() {
|
||||
for kind in ["content", "reasoning_content"] {
|
||||
if let Some(part) = choice["delta"][kind].as_str() {
|
||||
deltas.entry((kind, choice["index"].as_u64().unwrap_or(0))).or_default().push_str(part);
|
||||
}
|
||||
}
|
||||
for tool in choice["delta"]["tool_calls"].as_array().into_iter().flatten() {
|
||||
if let Some(part) = tool["function"]["arguments"].as_str() {
|
||||
deltas.entry(("arguments", tool["index"].as_u64().unwrap_or(0))).or_default().push_str(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for content in deltas.into_values() {
|
||||
if CREDENTIAL_TEXT.is_match(&content) { return Err(CREDENTIAL_ERROR.into()); }
|
||||
if let Ok(value) = serde_json::from_str(&content) { no_credentials(&value)?; }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn check_pcraft(bytes: &[u8]) -> R<()> {
|
||||
let manifest = photocraft_format::read_manifest(bytes).map_err(|_| "工程画布清单不可读取")?;
|
||||
if manifest.document.metadata.text.iter().any(|(name, _)| credential_key(name)) {
|
||||
return Err(CREDENTIAL_ERROR.into());
|
||||
}
|
||||
no_credentials(&serde_json::to_value(manifest).map_err(|_| "工程画布清单无效")?)
|
||||
}
|
||||
|
||||
pub(super) fn check_file(path: &str, bytes: &[u8]) -> R<()> {
|
||||
if path.ends_with(".json") {
|
||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| "项目JSON损坏,尚未备份")?;
|
||||
no_credentials(&value)?;
|
||||
if path.starts_with("requests/") {
|
||||
for item in [&value["raw"], &value["partialRaw"], &value["recovery"]["raw"]] {
|
||||
if let Some(encoded) = item.as_str() {
|
||||
check_wire(&STANDARD.decode(encoded).map_err(|_| "原请求响应编码无效")?)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if path.ends_with(".jsonl") {
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| "Agent会话编码无效,尚未备份")?;
|
||||
for line in text.lines().filter(|line| !line.trim().is_empty()) {
|
||||
no_credentials(&serde_json::from_str::<Value>(line).map_err(|_| "Agent会话记录不完整,请保留原文件")?)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) struct Policy<'a> {
|
||||
pub(super) chat: bool,
|
||||
pub(super) scope: &'a str,
|
||||
pub(super) project: &'a str,
|
||||
}
|
||||
|
||||
pub(super) fn explicit_chat(value: &Value) -> R<Option<bool>> {
|
||||
if value.is_null() { return Ok(None); }
|
||||
value.as_bool().map(Some).ok_or_else(|| "同步对话选项无效".into())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Selection {
|
||||
pub(super) included: Vec<String>,
|
||||
pub(super) excluded: Vec<Value>,
|
||||
}
|
||||
|
||||
impl Policy<'_> {
|
||||
pub(super) fn agent_file(&self, path: &str) -> Result<(), &'static str> {
|
||||
let parts: Vec<_> = path.split('/').collect();
|
||||
match parts.as_slice() {
|
||||
["agent", scope, project, "conversation-v1", name] if *scope == self.scope && *project == self.project => {
|
||||
if *name == "product-production-strategy.json" || production_journal(name) {
|
||||
Ok(())
|
||||
} else if *name == "session.json" {
|
||||
if self.chat { Ok(()) } else { Err("chat_history_disabled") }
|
||||
} else {
|
||||
Err("agent_private")
|
||||
}
|
||||
}
|
||||
["agent", scope, project, "conversation-v1", "sessions", name]
|
||||
if *scope == self.scope && *project == self.project && name.ends_with(".jsonl") =>
|
||||
{
|
||||
if self.chat { Ok(()) } else { Err("chat_history_disabled") }
|
||||
}
|
||||
_ => Err("agent_private"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn manifest(&self, stage: &Path, mut included: Vec<String>, mut excluded: Vec<Value>) -> R<Value> {
|
||||
let prefix = format!("agent/{}/{}/conversation-v1/", self.scope, self.project);
|
||||
let pointer = format!("{prefix}session.json");
|
||||
let paths = || included.iter().map(|path| path.strip_prefix("project/").unwrap_or(path));
|
||||
let has_session = paths().any(|path| path == pointer);
|
||||
if has_session {
|
||||
let value = super::read_json(&stage.join(&pointer))?;
|
||||
let name = value["file"].as_str().and_then(|file| file.rsplit(['/', '\\']).next()).ok_or("工程会话指针无效")?;
|
||||
let session = format!("{prefix}sessions/{name}");
|
||||
if !paths().any(|path| path == session) {
|
||||
return Err("工程会话缺少当前记录".into());
|
||||
}
|
||||
} else if paths().any(|path| path.starts_with(&format!("{prefix}sessions/"))) {
|
||||
return Err("工程会话缺少当前记录指针".into());
|
||||
}
|
||||
included.sort();
|
||||
excluded.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str()));
|
||||
let value = json!({"version":1,"policy":{"syncChatHistory":self.chat},
|
||||
"containsPiSession":has_session,"included":included,"excluded":excluded});
|
||||
no_credentials(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
fn production_journal(name: &str) -> bool {
|
||||
let Some(name) = name.strip_prefix("production-").and_then(|name| name.strip_suffix(".json")) else { return false };
|
||||
["detail-", "main_images-", "sku_images-"].iter().any(|prefix| name.strip_prefix(prefix)
|
||||
.is_some_and(|variant| !variant.is_empty() && variant.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_'))))
|
||||
}
|
||||
|
||||
pub(super) fn exclusion(path: &str, reason: &str) -> Value {
|
||||
json!({"path":redact_text(path),"reason":reason})
|
||||
}
|
||||
|
||||
pub(super) fn check_pcraft_file(path: &Path) -> R<()> {
|
||||
let bytes = photocraft_format::read_file(path).map_err(|_| "工程画布文件无法读取")?;
|
||||
check_pcraft(&bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_a_credential_split_across_saved_provider_delta_frames() {
|
||||
let wire = concat!(
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Bearer \"}}]}\n\n",
|
||||
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"fixture-cross-frame-secret\"}}]}\n\n",
|
||||
);
|
||||
assert!(check_wire(wire.as_bytes()).is_err());
|
||||
}
|
||||
}
|
||||
@ -352,7 +352,8 @@ impl log::Log for AppLogger {
|
||||
return;
|
||||
}
|
||||
let thread = std::thread::current();
|
||||
let line = format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &record.args().to_string());
|
||||
let message = crate::jiansun_backend::transfer::redact_text(&record.args().to_string());
|
||||
let line = format_line(×tamp(SystemTime::now()), record.level(), thread.name().unwrap_or("?"), record.target(), &message);
|
||||
if self.stderr {
|
||||
let _ = std::io::stderr().write_all(line.as_bytes());
|
||||
}
|
||||
@ -621,11 +622,13 @@ mod tests {
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
record(log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
|
||||
record(log::Level::Warn, "photocraft::jiansun", "gateway returned Cookie: session=fixture-log-secret");
|
||||
record(log::Level::Debug, "photocraft", "below info");
|
||||
let text = read(&path);
|
||||
assert!(text.contains(" INFO [") && text.contains("photocraft::app_dirs: settings directory\n"), "{text}");
|
||||
assert!(text.contains("wgpu_hal::vulkan: a real warning\n"), "{text}");
|
||||
assert!(!text.contains("too chatty") && !text.contains("below info"), "{text}");
|
||||
assert!(text.contains("gateway returned [已脱敏]") && !text.contains("fixture-log-secret"), "{text}");
|
||||
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("photocraft_gpu").build()));
|
||||
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@ -40,6 +40,8 @@ mod jiansun_models;
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod jiansun_acceptance;
|
||||
mod app_icon;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod app_tray;
|
||||
mod appearance;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod apple_events;
|
||||
@ -717,6 +719,8 @@ fn main() -> eframe::Result {
|
||||
app.open_paths(&files);
|
||||
if let Some(root) = services::config_dir() {
|
||||
app.jiansun = Some(jiansun_backend::start(root, cc.egui_ctx.clone()));
|
||||
#[cfg(target_os = "windows")]
|
||||
{ app.services.app_tray = Some(Box::new(app_tray::WindowsTray::new(&cc.egui_ctx))); }
|
||||
std::thread::spawn(|| {
|
||||
if let Err(error) = jiansun_backend::start_agent_daemon() {
|
||||
log::warn!("小壹常驻服务启动未完成:{error}");
|
||||
|
||||
@ -55,6 +55,7 @@ craft-update = { workspace = true }
|
||||
rayon = { workspace = true }
|
||||
# Safe native UI-language APIs (Windows/macOS); no subprocess or web dependency.
|
||||
sys-locale = "=0.3.2"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
|
||||
# Installed RAM for the GPU memory budget (`gpu_canvas::physical_memory`) and the user's decimal
|
||||
# symbol (`i18n::decimal_separator`, a registry read): the safe binding the desktop app already
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
//! Local Windows acceptance of PhotoCraft's exit and restart with a paid-request
|
||||
//! boundary replaced by a channel. Each process reopens the native file from disk.
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows {
|
||||
pub mod windows {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, atomic::{AtomicBool, Ordering::Relaxed}, mpsc};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
@ -14,12 +14,21 @@ mod windows {
|
||||
const ACCOUNT: &str = "local-qa";
|
||||
const EDIT: &str = "Edit made during the production turn";
|
||||
|
||||
pub struct TrayProbe {
|
||||
pub create: fn(&egui::Context) -> Box<dyn photocraft_ui_egui::AppTray>,
|
||||
pub hidden: fn(&eframe::Frame) -> bool,
|
||||
}
|
||||
|
||||
struct Host {
|
||||
app: PhotocraftApp,
|
||||
dispatched: Arc<AtomicBool>,
|
||||
mode: String,
|
||||
dir: PathBuf,
|
||||
handled: bool,
|
||||
hidden: Arc<AtomicBool>,
|
||||
saved: Arc<AtomicBool>,
|
||||
exited_from_tray: bool,
|
||||
native_window_hidden: Option<fn(&eframe::Frame) -> bool>,
|
||||
}
|
||||
|
||||
impl eframe::App for Host {
|
||||
@ -37,9 +46,23 @@ mod windows {
|
||||
std::fs::write(self.dir.join("edited"), b"canvas edit applied").unwrap();
|
||||
if self.mode.starts_with("exit") {
|
||||
photocraft_ui_egui::menus::invoke(&mut self.app, ctx, "file.exit", Value::Null).unwrap();
|
||||
} else if self.mode == "tray" {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.app.services.app_tray.as_ref().is_some_and(|tray| tray.visible())
|
||||
&& self.native_window_hidden.is_some_and(|is_hidden| is_hidden(frame))
|
||||
{
|
||||
if !self.hidden.swap(true, Relaxed) {
|
||||
println!("root viewport hidden with real notification-area icon");
|
||||
}
|
||||
if self.saved.load(Relaxed) && !self.exited_from_tray {
|
||||
self.exited_from_tray = true;
|
||||
println!("background save completed while root viewport was hidden");
|
||||
photocraft_ui_egui::menus::invoke(&mut self.app, ctx, "file.exit", Value::Null).unwrap();
|
||||
}
|
||||
}
|
||||
eframe::App::logic(&mut self.app, ctx, frame);
|
||||
if self.mode == "exit-fail" && self.app.jiansun.is_some()
|
||||
&& self.app.ui.status_error && self.app.ui.status.contains("保存未确认") {
|
||||
@ -64,7 +87,7 @@ mod windows {
|
||||
photocraft_format::atomic_write(path, &serde_json::to_vec(value).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
pub fn run(dir: PathBuf, mode: String) {
|
||||
pub fn run(dir: PathBuf, mode: String, tray: Option<TrayProbe>) {
|
||||
let canvas = dir.join("canvas.pcraft");
|
||||
let journal = dir.join("production-run.json");
|
||||
let draft = dir.join("draft.json");
|
||||
@ -95,11 +118,17 @@ mod windows {
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (events, rx) = mpsc::channel();
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
|
||||
app.services.app_tray = tray.as_ref().map(|probe| (probe.create)(&cc.egui_ctx));
|
||||
let native_window_hidden = tray.map(|probe| probe.hidden);
|
||||
let mut workspace = Workspace::new(tx, rx);
|
||||
workspace.draft_flush = Some(Arc::new(|_, _, _, _, _| Ok(())));
|
||||
app.jiansun = Some(workspace);
|
||||
let dispatched = Arc::new(AtomicBool::new(false));
|
||||
let signal = Arc::clone(&dispatched);
|
||||
let hidden = Arc::new(AtomicBool::new(false));
|
||||
let worker_hidden = hidden.clone();
|
||||
let saved = Arc::new(AtomicBool::new(false));
|
||||
let worker_saved = saved.clone();
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
let current_mode = mode.clone();
|
||||
let evidence = dir.clone();
|
||||
@ -126,18 +155,21 @@ mod windows {
|
||||
continue;
|
||||
}
|
||||
Request::Action(method, input) if method == "product-exit-checkpoint" => {
|
||||
assert_eq!(input["checkpoint"]["status"], "paused_on_exit");
|
||||
write(&journal, &input["checkpoint"]);
|
||||
Event::Json(method, Ok(Value::Null))
|
||||
}
|
||||
Request::Save(..) if current_mode == "exit-fail" =>
|
||||
Event::Json("save".into(), Err("QA: 本机草稿写入失败".into())),
|
||||
Request::Save(doc, revision, _) if current_mode == "exit" => {
|
||||
Request::Save(doc, revision, _) if matches!(current_mode.as_str(), "exit" | "tray") => {
|
||||
assert!(doc.layers.iter().any(|layer| layer.name == EDIT));
|
||||
assert!(evidence.join("edited").is_file());
|
||||
if current_mode == "tray" { assert!(worker_hidden.load(Relaxed)); }
|
||||
// Make the receipt arrive in a later native frame.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
writer.save_path(&doc, &canvas, &Default::default()).unwrap();
|
||||
write(&draft, &json!({"revision":revision}));
|
||||
worker_saved.store(true, Relaxed);
|
||||
println!("saved real native canvas at revision {revision}");
|
||||
Event::Saved(doc.id.0, revision, json!({"localId":PROJECT,"savedPath":canvas}))
|
||||
}
|
||||
@ -148,7 +180,7 @@ mod windows {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
Ok(Box::new(Host { app, dispatched, mode, dir, handled:false }))
|
||||
Ok(Box::new(Host { app, dispatched, mode, dir, handled:false, hidden, saved, exited_from_tray:false, native_window_hidden }))
|
||||
})).unwrap();
|
||||
println!("native window exited");
|
||||
}
|
||||
@ -159,6 +191,6 @@ fn main() {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let mode = args.next().unwrap().into_string().unwrap();
|
||||
let dir = args.next().unwrap().into();
|
||||
windows::run(dir, mode);
|
||||
windows::run(dir, mode, None);
|
||||
}
|
||||
}
|
||||
|
||||
@ -209,6 +209,7 @@ impl PhotocraftApp {
|
||||
held_opens: Default::default(),
|
||||
held_preset_import: None,
|
||||
allow_close: false,
|
||||
explicit_exit: false,
|
||||
stylus: Default::default(),
|
||||
control_click: Default::default(),
|
||||
background_jobs: false,
|
||||
|
||||
@ -583,6 +583,10 @@ impl PhotocraftApp {
|
||||
!self.jobs.saves.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn exporting(&self) -> bool {
|
||||
self.session.jobs().iter().any(|job| job.command.starts_with("file.export"))
|
||||
}
|
||||
|
||||
/// Save through the control session's capability-scoped writer. No file
|
||||
/// picker or ambient writer is reachable from this path. Returns the path
|
||||
/// written and the export warnings (also shown to the user).
|
||||
|
||||
@ -100,6 +100,7 @@ impl PhotocraftApp {
|
||||
// A window bigger than its display (1440 × 900 on 1366 × 768) runs under the taskbar:
|
||||
// maximize it into the work area once (#315).
|
||||
work_area::fit_window(ctx);
|
||||
discard_ui::poll_tray(self, ctx);
|
||||
discard_ui::guard_window_close(self, ctx);
|
||||
// A zoom field being typed in: plays its alert, and notes a click on the pasteboard.
|
||||
crate::zoom_field::tick(self, ctx);
|
||||
@ -174,6 +175,7 @@ impl PhotocraftApp {
|
||||
self.poll_file_dialog(ctx, Some(frame));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::jiansun::advance(self, ctx);
|
||||
discard_ui::refresh_tray_status(self);
|
||||
}
|
||||
|
||||
/// Shared UI body. A wrapping host must call `finish_type_reset_pass` after return,
|
||||
@ -181,6 +183,8 @@ impl PhotocraftApp {
|
||||
pub fn ui_frame(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if crate::jiansun::flushing_exit(self) { ui.disable(); }
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
canvas::retain_agent_adoption(self, &ctx);
|
||||
// One control owner even when this callback cannot draw the custom editor.
|
||||
if !self.fonts_ready
|
||||
|
||||
@ -118,13 +118,58 @@ impl PhotocraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Called once per frame: holds back a window close request while there is unsaved work. Every
|
||||
/// way of leaving (File › Exit / Quit, the close button, the OS's quit event, `app.quit`) ends up
|
||||
/// here as a close request.
|
||||
pub(crate) fn poll_tray(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if ctx.viewport_id() != egui::ViewportId::ROOT { return; }
|
||||
let Some(action) = app.services.app_tray.as_mut().and_then(|tray| tray.take_action()) else { return };
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
if matches!(action, crate::TrayAction::Exit)
|
||||
&& let Err(error) = crate::menus::invoke(app, ctx, EXIT, Value::Null)
|
||||
{
|
||||
app.ui.status = error;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_tray_status(app: &mut PhotocraftApp) {
|
||||
if app.services.app_tray.as_ref().is_some_and(|tray| tray.visible()) {
|
||||
let status = background_status(app).unwrap_or_else(|| "当前没有运行中的任务".into());
|
||||
if let Some(tray) = app.services.app_tray.as_mut() { tray.set_status(&status); }
|
||||
}
|
||||
}
|
||||
|
||||
fn background_status(app: &PhotocraftApp) -> Option<String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(status) = crate::jiansun::background_status(app) { return Some(status); }
|
||||
if app.saving() { return Some("正在保存文档".into()); }
|
||||
app.exporting().then(|| "正在导出文件".into())
|
||||
}
|
||||
|
||||
/// Native close parks an active workspace. File › Exit and the tray's Exit drain it.
|
||||
pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if !ctx.input(|i| i.viewport().close_requested()) {
|
||||
if ctx.viewport_id() != egui::ViewportId::ROOT || !ctx.input(|i| i.viewport().close_requested()) {
|
||||
return;
|
||||
}
|
||||
if !app.explicit_exit && !app.allow_close && app.services.app_tray.is_some()
|
||||
&& let Some(status) = background_status(app)
|
||||
&& let Some(tray) = app.services.app_tray.as_mut()
|
||||
{
|
||||
match tray.show(&status) {
|
||||
Ok(()) => {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
|
||||
return;
|
||||
}
|
||||
Err(error) => {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
app.ui.status = format!("无法移至小壹托盘:{error}。可通过文件菜单退出。");
|
||||
app.ui.status_error = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if crate::jiansun::guard_production_exit(app, ctx) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
return;
|
||||
@ -136,7 +181,11 @@ pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
// A save or print worker must finish its external side effect before the process exits;
|
||||
// `jobs_ui` repeats the close after completion and keeps errors visible.
|
||||
if app.saving() || app.printing() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let flush_finished = crate::jiansun::exit_flush_finished(app);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let flush_finished = false;
|
||||
if (app.saving() && !flush_finished) || app.printing() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
app.jobs.close_after_saves = true;
|
||||
return;
|
||||
@ -346,7 +395,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
/// Acts on the answer about `doc`, the document the prompt is asking about.
|
||||
fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId, answer: Answer) {
|
||||
match answer {
|
||||
Answer::Cancel => app.discard = None,
|
||||
Answer::Cancel => {
|
||||
if app.discard.take().is_some_and(|prompt| prompt.id == EXIT) {
|
||||
app.explicit_exit = false;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::jiansun::cancel_exit(app);
|
||||
}
|
||||
}
|
||||
Answer::Discard => advance(app, ctx),
|
||||
Answer::Save if save(app, ctx, doc) => advance(app, ctx),
|
||||
Answer::Save => {}
|
||||
|
||||
@ -57,6 +57,7 @@ pub enum Request {
|
||||
Save(Arc<Document>, u64, Value),
|
||||
Generate(Arc<Document>, Value),
|
||||
SlotPreview(Arc<Document>, Value),
|
||||
DeliverProductionBundle(Value, Arc<AtomicBool>),
|
||||
OpenedResult { binding: Value, result: Result<(Box<Document>, Value), String> },
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
@ -103,6 +104,8 @@ pub struct PiCanvasSnapshot {
|
||||
pub cancellation: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
type ExitReceipt = mpsc::Receiver<Result<(), String>>;
|
||||
|
||||
pub enum Event {
|
||||
Json(String, Result<Value, String>),
|
||||
Opened(Box<Document>, Value),
|
||||
@ -1013,9 +1016,14 @@ pub struct Workspace {
|
||||
draft_changed: bool,
|
||||
product_checkpoint: Value,
|
||||
production_exit: Option<product_production::PendingExit>,
|
||||
pub pause_production_agent: Option<fn(u64, &str)>,
|
||||
pub exit_admission_closed: Arc<AtomicBool>,
|
||||
pub prepare_daemon_exit: Option<Box<dyn Fn() -> ExitReceipt>>,
|
||||
pub cancel_daemon_exit: Option<fn()>,
|
||||
pub pause_production_agent: Option<fn(u64, &str, Option<u64>)>,
|
||||
loaded_draft: Option<u64>,
|
||||
pub draft_flush: Option<composer_drafts::Flush>,
|
||||
pub account_epoch: Option<Arc<std::sync::atomic::AtomicU64>>,
|
||||
accepted_account_epoch: u64,
|
||||
composer_drafts: composer_drafts::State,
|
||||
allow_apply: bool,
|
||||
preview: Option<(Value, egui::TextureHandle)>,
|
||||
@ -1095,6 +1103,7 @@ pub struct Workspace {
|
||||
creation_width: u32,
|
||||
creation_count: usize,
|
||||
creation_budget_minutes: u64,
|
||||
creation_delivery_dir: Option<String>,
|
||||
creation_catalog: std::collections::HashMap<String, Vec<Value>>,
|
||||
creation_reads: creation_reads::UiState,
|
||||
creation_view_geometry: Value,
|
||||
@ -1110,6 +1119,7 @@ pub struct Workspace {
|
||||
product_production: Option<product_production::Run>,
|
||||
product_views: product_production::Views,
|
||||
product_target_hidden: bool,
|
||||
write_epoch: u64,
|
||||
product_start_queued: bool,
|
||||
product_export: Option<Value>,
|
||||
canvas_workspace: canvas_workspace::State,
|
||||
@ -1265,6 +1275,9 @@ impl Workspace {
|
||||
input["baseRevision"] = json!(st.revision);
|
||||
input["slotRevision"] = self.template_workflow["revision"].as_u64().map(Value::from).unwrap_or(json!(0));
|
||||
input["imageModel"] = json!(self.image_model);
|
||||
if input["continueProduct"] == true && self.pi_request_scope["writeEpoch"].is_u64() {
|
||||
input["writeEpoch"] = self.pi_request_scope["writeEpoch"].clone();
|
||||
}
|
||||
if local_adoption {
|
||||
if self.saving.is_some() {return Err("请等待本机保存完成,再采纳图片".into());}
|
||||
if self.canvas_workspace.pending_adoption.is_some() {
|
||||
@ -1290,6 +1303,11 @@ impl Workspace {
|
||||
self.busy = Some(method.into());
|
||||
return Ok(json!({"submitted":true,"saving":true}));
|
||||
}
|
||||
if method == "slot-skeleton" && input.get("deliveryDir").is_none()
|
||||
&& input["brief"].is_object()
|
||||
{
|
||||
input["deliveryDir"] = json!(self.creation_delivery_dir);
|
||||
}
|
||||
if matches!(method, "slot-apply" | "slot-skeleton" | "slot-product-export") {
|
||||
if method == "slot-skeleton" && (input["generateProduct"] == true || input["resumeProduct"] == true)
|
||||
&& let Some(problem) = self.production_model_problem() {
|
||||
@ -1354,6 +1372,10 @@ impl Workspace {
|
||||
let Some(mut pending) = self.pending_slot_apply.take() else { return };
|
||||
let method = pending["dispatchMethod"].as_str().unwrap_or("slot-apply").to_owned();
|
||||
let resume_busy = pending["resumeBusy"].as_str().map(str::to_owned);
|
||||
if !self.accepts_production_epoch(&pending["writeEpoch"]) {
|
||||
if self.busy.as_deref() == Some("slot-apply-save") { self.busy = None; }
|
||||
return;
|
||||
}
|
||||
let waiting = self.busy.as_deref() == Some("slot-apply-save");
|
||||
let live_handoff = pending["continueProduct"] == true && resume_busy.as_deref() == Some("pi-agent") && self.pi_run.is_some();
|
||||
if waiting {
|
||||
@ -1500,7 +1522,12 @@ impl Workspace {
|
||||
draft_changed: false,
|
||||
product_checkpoint: Value::Null,
|
||||
production_exit: None,
|
||||
exit_admission_closed: Arc::new(AtomicBool::new(false)),
|
||||
prepare_daemon_exit: None,
|
||||
cancel_daemon_exit: None,
|
||||
pause_production_agent: None,
|
||||
account_epoch: None,
|
||||
accepted_account_epoch: 0,
|
||||
loaded_draft: None,
|
||||
draft_flush: None,
|
||||
composer_drafts: composer_drafts::State::default(),
|
||||
@ -1581,6 +1608,7 @@ impl Workspace {
|
||||
creation_width: 1440,
|
||||
creation_count: 3,
|
||||
creation_budget_minutes: product_production::DEFAULT_BUDGET_MINUTES,
|
||||
creation_delivery_dir: None,
|
||||
creation_catalog: Default::default(),
|
||||
creation_reads: Default::default(),
|
||||
creation_view_geometry: json!({}),
|
||||
@ -1596,6 +1624,7 @@ impl Workspace {
|
||||
product_production: None,
|
||||
product_views: product_production::Views::default(),
|
||||
product_target_hidden: false,
|
||||
write_epoch: 0,
|
||||
product_start_queued: false,
|
||||
product_export: None,
|
||||
canvas_workspace: canvas_workspace::State::default(),
|
||||
@ -1852,6 +1881,7 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn handover(&mut self) {
|
||||
self.revoke_production_epoch();
|
||||
self.product_production = None;
|
||||
self.product_start_queued = false;
|
||||
self.product_export = None;
|
||||
@ -1963,6 +1993,7 @@ impl Workspace {
|
||||
self.creation_width = retained.draft["width"].as_u64().unwrap_or(1440) as u32;
|
||||
self.creation_count = retained.draft["screenCount"].as_u64().unwrap_or(3) as usize;
|
||||
self.creation_budget_minutes = product_production::budget_minutes(&retained.draft);
|
||||
self.creation_delivery_dir = product_production::delivery_dir(&retained.draft);
|
||||
self.creation_dirty = true;
|
||||
self.draft_changed = true;
|
||||
self.sync_dirty = true;
|
||||
@ -2381,6 +2412,11 @@ impl Workspace {
|
||||
if whole_detail { scope["wholeDetail"] = json!(true); }
|
||||
let mut text = text;
|
||||
if whole_detail && let Some(run) = self.product_production.as_mut() {
|
||||
self.write_epoch += 1;
|
||||
scope["writeEpoch"] = json!(self.write_epoch);
|
||||
if run.output_selected() {
|
||||
scope["documentKey"] = product_document_key(&active.doc);
|
||||
}
|
||||
scope["productProduction"] = json!(true);
|
||||
scope["productionDeadline"] = json!(run.deadline());
|
||||
scope["requestedOutputs"] = run.requested_outputs();
|
||||
@ -2518,6 +2554,8 @@ impl Workspace {
|
||||
self.requested_previews.clear();
|
||||
self.stream_reply.clear();
|
||||
self.handover();
|
||||
self.pi_run = None;
|
||||
self.pi_binding = Value::Null;
|
||||
self.ready_image = None;
|
||||
self.project_covers.clear();
|
||||
self.cover_loading.clear();
|
||||
@ -2526,6 +2564,7 @@ impl Workspace {
|
||||
self.delete_error.clear();
|
||||
}
|
||||
self.account = v["account"].clone();
|
||||
if let Some(epoch) = v["accountEpoch"].as_u64() { self.accepted_account_epoch = epoch; }
|
||||
if let Some(origin) = v["origin"].as_str() {
|
||||
self.origin = origin.into();
|
||||
}
|
||||
@ -2730,6 +2769,20 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn receive_json_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: String, mut result: Result<Value, String>) {
|
||||
if let Ok(value) = &mut result {
|
||||
if !self.accepts_production_epoch(&value["writeEpoch"]) {
|
||||
if value["writeEpoch"] == self.pi_request_scope["writeEpoch"]
|
||||
&& (method == "agent" && matches!(self.busy.as_deref(), Some("agent" | "pi-agent"))
|
||||
|| self.busy.as_deref() == Some(method.as_str()) && matches!(method.as_str(), "slot-skeleton" | "slot-product-export"))
|
||||
{
|
||||
self.busy = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(error) = value["executionError"].as_str() {
|
||||
result = Err(error.to_owned());
|
||||
}
|
||||
}
|
||||
if method == "project-operation" { self.project_operation_received(app, result); return; }
|
||||
match method.as_str() {
|
||||
"template-progress" => { self.receive_template_progress(app, result); return; }
|
||||
@ -2769,6 +2822,14 @@ impl Workspace {
|
||||
let live_image_request = method == "image" && self.busy.as_deref() == Some("image");
|
||||
self.receive_candidate_recovery(app, &method, &result);
|
||||
let workflow_receipt = self.workflow.operation_receipt(&workflow_envelope, &method, &result, &self.account["id"], &self.origin, app.session.active().map(|s|s.doc.id.0));
|
||||
if !self.accepts_production_epoch(&workflow_envelope["writeEpoch"]) {
|
||||
if workflow_envelope["writeEpoch"] == self.pi_request_scope["writeEpoch"]
|
||||
&& self.busy.as_deref() == Some("slot-append")
|
||||
{
|
||||
self.busy = Some("agent".into());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !workflow_receipt && matches!(method.as_str(), "slot-append" | "slot-adopt-prep")
|
||||
&& self.workflow.any_operation_in_flight() {
|
||||
return; // An unrelated late receipt cannot settle or clear this operation.
|
||||
@ -2901,6 +2962,22 @@ impl Workspace {
|
||||
|
||||
fn receive_json_success(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, v: Value, live_image_request: bool) {
|
||||
match method {
|
||||
"auth-fence" if v["accountId"] == self.account["id"] && v["origin"] == self.origin => {
|
||||
self.with_product_target(app, |w, app| {
|
||||
w.pause_for_authorization(&v["category"]);
|
||||
if let Some(state) = app.session.active().filter(|state| w.loaded_draft == Some(state.doc.id.0)) {
|
||||
w.save_project_draft(state, ctx);
|
||||
}
|
||||
});
|
||||
if v["category"] == "auth_revoked" {
|
||||
self.receive_library_status(&json!({"libraryStatus":"sign_in_required","libraryHttpStatus":401,
|
||||
"libraryMessage":"授权已失效,制作已暂停;请重新登录"}));
|
||||
self.model_ready = false;
|
||||
self.image_ready = false;
|
||||
self.copy_ready = false;
|
||||
self.note("授权已失效,制作已暂停");
|
||||
}
|
||||
}
|
||||
"slot-product-export" => self.production_export_received(app, &v),
|
||||
"slot-skeleton" if v["productionPreparation"] == true => {
|
||||
let current = app.session.active().filter(|state| v["doc"] == state.doc.id.0);
|
||||
@ -2922,7 +2999,13 @@ impl Workspace {
|
||||
}
|
||||
name if name.starts_with("slot-") => self.receive_json_slot(app, name, v),
|
||||
name if name.starts_with("creation-") => self.receive_creation_ui(app, name, &v),
|
||||
"project-sync" | "project-state" => creation::sync_received(self, app, &v),
|
||||
"project-sync" => creation::sync_received(self, app, &v),
|
||||
"project-state" if v["accountId"] == self.account["id"] && v["origin"] == self.origin
|
||||
&& v["doc"].as_u64() == app.session.active().map(|state| state.doc.id.0) => {
|
||||
self.project_context["status"] = v["projectState"]["state"].clone();
|
||||
self.sync_dirty = true;
|
||||
if let Some(items) = v["projects"].as_array() { self.merge_project_receipt(app, items); }
|
||||
}
|
||||
"login-url" => {
|
||||
if let Some(url) = v.as_str()
|
||||
&& let Some(open) = &app.services.open_url
|
||||
@ -3336,7 +3419,10 @@ impl Workspace {
|
||||
ctx.request_repaint_after(Duration::from_millis(60));
|
||||
}
|
||||
if !self.queue.is_empty() {
|
||||
if current != self.owner_doc.map(|id| (id, self.expected_revision)) {
|
||||
let target = &self.pi_request_scope["documentKey"];
|
||||
if current != self.owner_doc.map(|id| (id, self.expected_revision))
|
||||
|| target.is_object() && app.session.active().is_none_or(|state| product_document_key(&state.doc) != *target)
|
||||
{
|
||||
if self.pi_run.is_some() {
|
||||
self.recording_edit_owner = None;
|
||||
self.queue.clear();
|
||||
@ -3400,13 +3486,17 @@ impl Workspace {
|
||||
canvas_workspace::observe_canvas_input(ctx);
|
||||
self.observe_startup_interaction(ctx);
|
||||
}
|
||||
self.with_product_target(app, |w, app| {
|
||||
if let Some((meta, adopted)) = w.poll_canvas_adoption(app, ctx, painting) {
|
||||
w.finish_adoption_receipt(app, &meta, adopted);
|
||||
}
|
||||
});
|
||||
// Settle owned native apply receipts before manual-edit detection.
|
||||
agent_native::settle_jobs(self, app);
|
||||
if self.authority_active() {
|
||||
self.with_product_target(app, |w, app| {
|
||||
if let Some((meta, adopted)) = w.poll_canvas_adoption(app, ctx, painting) {
|
||||
w.finish_adoption_receipt(app, &meta, adopted);
|
||||
}
|
||||
});
|
||||
// Settle owned native apply receipts before manual-edit detection.
|
||||
self.with_product_target(app, |w, app| { agent_native::settle_jobs(w, app); });
|
||||
} else {
|
||||
self.agent_native.cancel();
|
||||
}
|
||||
self.professional_sync(app);
|
||||
self.enforce_canvas_scope(app);
|
||||
self.project_open_locals = self.live_project_locals(app);
|
||||
@ -3414,6 +3504,13 @@ impl Workspace {
|
||||
self.sync_dirty = true;
|
||||
}
|
||||
while let Ok(mut event) = self.rx.try_recv() {
|
||||
if self.production_exit.is_some()
|
||||
&& !matches!(&event, Event::Saved(..) | Event::PiAction(..))
|
||||
&& !matches!(&event, Event::Json(method, _) if matches!(method.as_str(),
|
||||
"save" | "product-exit-checkpoint" | "slot-product-view-save" | "slot-product-export" | "production-deliver-bundle"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Event::SlotCanvas(doc, meta) = &mut event
|
||||
&& let Some(preview) = meta.as_object_mut().and_then(|fields| fields.remove("originalPreview"))
|
||||
&& meta["accountId"] == self.account["id"] && meta["origin"] == self.origin
|
||||
@ -3421,6 +3518,9 @@ impl Workspace {
|
||||
app.remember_original_preview(doc.id, &preview);
|
||||
}
|
||||
match event {
|
||||
Event::Json(method, Ok(value)) if method == "production-deliver-bundle" => {
|
||||
self.production_bundle_received(&value);
|
||||
}
|
||||
Event::Json(method, result) if method == "product-exit-checkpoint" => {
|
||||
if let Some(exit) = &mut self.production_exit {
|
||||
exit.checkpoint = Some(result.map(|_| ()));
|
||||
@ -3459,13 +3559,15 @@ impl Workspace {
|
||||
self.advance_production_exit(app, ctx);
|
||||
return;
|
||||
}
|
||||
if self.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire) { return; }
|
||||
if !self.tick_context(app, ctx) { return; }
|
||||
let current = app.session.active().map(|s| (s.doc.id.0, s.revision));
|
||||
self.tick_pending_edits(app, ctx, current);
|
||||
self.creation_autosave(app, ctx);
|
||||
if painting && (self.busy.is_some() || self.saving.is_some()) {
|
||||
ctx.request_repaint_after(Duration::from_millis(100));
|
||||
if self.authority_active() {
|
||||
self.with_product_target(app, |w, app| {
|
||||
let current = app.session.active().map(|s| (s.doc.id.0, s.revision));
|
||||
w.tick_pending_edits(app, ctx, current);
|
||||
});
|
||||
}
|
||||
self.creation_autosave(app, ctx);
|
||||
let visible = self.library && !self.material && !self.creation_open;
|
||||
let focused = ctx.input(|i| i.raw.focused);
|
||||
let refresh_due = project_refresh_due(
|
||||
@ -3516,8 +3618,12 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
fn save_project_draft(&mut self, state: &photocraft_engine::DocState, ctx: &egui::Context) -> bool {
|
||||
let composer_saved = self.flush_document_draft(ctx, Some(state.doc.id.0), false);
|
||||
self.enqueue_project_draft(state, composer_saved)
|
||||
}
|
||||
|
||||
fn enqueue_project_draft(&mut self, state: &photocraft_engine::DocState, composer_saved: bool) -> bool {
|
||||
let key = (state.doc.id.0, state.revision);
|
||||
let composer_saved = self.flush_document_draft(ctx, Some(key.0), false);
|
||||
if !composer_saved { self.draft_changed = true; }
|
||||
let meta = json!({"composer":self.composer,"messages":self.messages,"project":self.project_context,"syncDirty":self.sync_dirty,"creationDraft":self.creation_draft()});
|
||||
let submitted = self.tx.send(Request::Save(state.doc.clone(), state.revision, meta)).is_ok();
|
||||
@ -3532,6 +3638,10 @@ impl Workspace {
|
||||
fn receive_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, event: Event) {
|
||||
match event {
|
||||
Event::PiAction(method, input, reply) => {
|
||||
if !self.authority_active() || input["accountEpoch"].as_u64().is_some_and(|epoch| epoch != self.accepted_account_epoch) {
|
||||
let _ = reply.send(Err(BridgeFailure::new("auth_revoked", false, false, "授权已失效,原操作未应用")));
|
||||
return;
|
||||
}
|
||||
if self.production_exit.is_some() {
|
||||
let _ = reply.send(Err(BridgeFailure::new("cancelled", false, false, "客户端正在退出,原操作可在重新打开后核查")));
|
||||
return;
|
||||
@ -3551,7 +3661,8 @@ impl Workspace {
|
||||
{
|
||||
self.queue_canvas_feedback(doc, json!({"nativeLayerId":layer}), "图层已更新");
|
||||
}
|
||||
let snapshot = if method == "pi-product-screen" || method == "pi-detail-images" && value["adopted"] == true {
|
||||
let snapshot = if matches!(method.as_str(), "pi-product-screen" | "pi-image-request")
|
||||
|| method == "pi-detail-images" && value["adopted"] == true {
|
||||
app.session.active().zip(self.agent_native.cancellation()).map(|(active, cancellation)| {
|
||||
PiCanvasSnapshot { document: active.doc.clone(), cancellation }
|
||||
})
|
||||
@ -3567,6 +3678,7 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
Event::SlotAdopt { bytes, meta } => {
|
||||
if !self.authority_active() { return; }
|
||||
if meta["purpose"] == "professional-edit" { self.professional_image_received(app, bytes, meta); }
|
||||
else if let Some((meta, adopted)) = self.canvas_adopt(app, bytes, meta) {
|
||||
self.finish_adoption_receipt(app, &meta, adopted);
|
||||
@ -3578,6 +3690,12 @@ impl Workspace {
|
||||
Event::Json(method, result) => self.receive_json_event(app, ctx, method, result),
|
||||
Event::Opened(doc, meta) => self.receive_opened(app, ctx, doc, meta),
|
||||
Event::Saved(id, rev, meta) => {
|
||||
if meta["documentKey"].is_object() && app.session.active().is_some_and(|state|
|
||||
state.doc.id.0 == id && product_document_key(&state.doc) != meta["documentKey"])
|
||||
{
|
||||
if self.saving == Some((id, rev)) { self.saving = None; }
|
||||
return;
|
||||
}
|
||||
self.saving = None;
|
||||
self.saved = Some((id, rev, meta["time"].as_str().unwrap_or("").into()));
|
||||
self.persisted_revisions.insert(id, rev);
|
||||
@ -3821,6 +3939,10 @@ impl Workspace {
|
||||
} else if status != "connected" { self.library_authorization_enabled = None; }
|
||||
}
|
||||
}
|
||||
fn authority_active(&self) -> bool {
|
||||
self.account_epoch.as_ref().is_none_or(|epoch|
|
||||
epoch.load(std::sync::atomic::Ordering::Acquire) == self.accepted_account_epoch)
|
||||
}
|
||||
fn needs_library_login(&self) -> bool {
|
||||
self.library_status == "sign_in_required" || self.account.is_null() && !self.library_blocked()
|
||||
}
|
||||
@ -3835,6 +3957,7 @@ impl Workspace {
|
||||
fn set_library_issue(&mut self, error: &str) -> bool {
|
||||
let state = match error {
|
||||
"请先在素材库登录" | "账户状态不一致,请重新授权" |
|
||||
"授权已失效,制作已暂停;请重新登录" |
|
||||
"素材库授权已过期或被撤销,请重新连接;本机作品已保留" => "sign_in_required",
|
||||
"当前账户没有素材库访问权限,请核对账户或联系管理员;本机作品已保留" => "forbidden",
|
||||
"素材库尚未开放客户端连接,请由管理员恢复服务开关;本机作品已保留" => "disabled",
|
||||
@ -4130,13 +4253,63 @@ pub(crate) fn advance(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn product_document_key(doc: &Document) -> Value {
|
||||
let Some(mapping) = canvas_workspace::document_mapping(doc) else { return Value::Null; };
|
||||
json!({"workspaceId":mapping["workspaceId"],"outputId":mapping["component"],
|
||||
"variantId":mapping["variantId"],"templateId":mapping["templateId"],
|
||||
"templateVersion":mapping["templateVersion"],"templateHash":mapping["templateHash"],
|
||||
"mappingDocumentId":mapping["outputId"]})
|
||||
}
|
||||
|
||||
pub(crate) fn guard_production_exit(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
let Some(mut workspace) = app.jiansun.take() else { return false; };
|
||||
let waiting = workspace.begin_production_exit(app, ctx);
|
||||
app.jiansun = Some(workspace);
|
||||
if waiting { app.explicit_exit = true; }
|
||||
waiting
|
||||
}
|
||||
|
||||
pub(crate) fn flushing_exit(app: &PhotocraftApp) -> bool {
|
||||
app.jiansun.as_ref().is_some_and(|w| w.production_exit.is_some())
|
||||
}
|
||||
|
||||
pub(crate) fn exit_flush_finished(app: &PhotocraftApp) -> bool {
|
||||
app.jiansun.as_ref().is_some_and(|w| w.production_exit.is_none()
|
||||
&& w.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire))
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_exit(app: &mut PhotocraftApp) {
|
||||
use std::sync::atomic::Ordering;
|
||||
let Some(workspace) = app.jiansun.as_mut() else { return };
|
||||
if workspace.exit_admission_closed.swap(false, Ordering::AcqRel) {
|
||||
if let Some(cancel) = workspace.cancel_daemon_exit { cancel(); }
|
||||
workspace.busy = None;
|
||||
workspace.pi_run = None;
|
||||
workspace.pi_native = false;
|
||||
workspace.pi_request_scope = Value::Null;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn background_status(app: &PhotocraftApp) -> Option<String> {
|
||||
app.jiansun.as_ref().and_then(|workspace| workspace.background_status(app))
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
fn background_status(&self, app: &PhotocraftApp) -> Option<String> {
|
||||
self.product_production.as_ref().and_then(product_production::Run::progress_label)
|
||||
.or_else(|| (self.product_start_queued || self.product_export.is_some()
|
||||
|| self.busy.as_deref() == Some("slot-product-export")).then(|| "正在制作或导出".into()))
|
||||
.or_else(|| (self.saving.is_some() || self.product_view_save_pending()).then(|| "正在保存小壹工程".into()))
|
||||
.or_else(|| (self.pending() || self.pending_slot_apply.is_some()
|
||||
|| matches!(self.busy.as_deref(), Some("creation-facts" | "creation-points" | "creation-plan" | "creation-generate" | "creation-recover")))
|
||||
.then(|| "小壹正在处理任务".into()))
|
||||
.or_else(|| (self.unknown && self.automatic_recovery_doc(app).is_some()
|
||||
&& self.original_image_recoveries().any(|(_, id)| {
|
||||
self.image_recovery_schedules.get(id).is_none_or(|schedule| !schedule.exhausted())
|
||||
})).then(|| "正在核查原生图请求".into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bind_workspace_rendering(app: &PhotocraftApp, ui: &Ui) {
|
||||
if app.jiansun.is_some() {
|
||||
glow_pill::bind(ui, app.gpu_render_state.as_ref());
|
||||
@ -4620,6 +4793,11 @@ mod agent_daemon_control_tests {
|
||||
}
|
||||
|
||||
fn action_impl(app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &str, input: Value) -> Result<Value, String> {
|
||||
if app.jiansun.as_ref().is_some_and(|w| w.exit_admission_closed.load(std::sync::atomic::Ordering::Acquire))
|
||||
&& !matches!(method, "state" | "agent-daemon-state")
|
||||
{
|
||||
return Err("小壹正在退出,未派发新任务".into());
|
||||
}
|
||||
if matches!(method, "agent-daemon-state" | "agent-daemon-start") {
|
||||
if !input.as_object().is_some_and(|fields| fields.is_empty()) { return Err("后台 Agent 控制不接受参数".into()); }
|
||||
return app.services.agent_daemon.as_ref().ok_or("当前客户端不支持后台 Agent 服务")?(method == "agent-daemon-start");
|
||||
@ -5182,7 +5360,7 @@ mod tests {
|
||||
&& input["context"]["requestScope"]["outputId"].is_null()
|
||||
&& input["context"]["requestScope"]["goalUserEntry"].is_null()));
|
||||
thread_local! { static PAUSED: std::cell::RefCell<Option<(u64, String)>> = const { std::cell::RefCell::new(None) }; }
|
||||
w.pause_production_agent = Some(|doc, project| PAUSED.with(|call| {
|
||||
w.pause_production_agent = Some(|doc, project, _| PAUSED.with(|call| {
|
||||
*call.borrow_mut() = Some((doc, project.into()));
|
||||
}));
|
||||
let owner = w.local_identity("owned-product");
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -17,6 +17,40 @@ pub(super) struct State {
|
||||
drafts: HashMap<(u64, String), Draft>,
|
||||
}
|
||||
impl Workspace {
|
||||
pub(super) fn save_exit_composers(&self, ctx: &egui::Context) -> Option<std::sync::mpsc::Receiver<Result<(), String>>> {
|
||||
let scope = self.local_identity("");
|
||||
let cursor = egui::text_edit::TextEditState::load(ctx, super::composer_input_id()).and_then(|state| state.cursor.char_range());
|
||||
let drafts: Vec<_> = self.composer_drafts.drafts.iter()
|
||||
.filter(|((_, identity), _)| identity.starts_with(&scope))
|
||||
.filter_map(|(key, draft)| {
|
||||
let (text, selection) = if self.composer_drafts.active.as_ref() == Some(key) {
|
||||
(self.composer.as_str(), cursor)
|
||||
} else { (draft.text.as_str(), draft.cursor) };
|
||||
if !draft.dirty && text == draft.text && selection == draft.cursor { return None; }
|
||||
let length = text.chars().count();
|
||||
let primary = selection.map_or(length, |c| usize::from(c.primary.index)).min(length) as u64;
|
||||
let secondary = selection.map_or(primary, |c| usize::from(c.secondary.index).min(length) as u64);
|
||||
Some((draft.token.clone(), text.to_owned(), primary, secondary, draft.generation))
|
||||
}).collect();
|
||||
if drafts.is_empty() { return None; }
|
||||
let flush = self.draft_flush.clone();
|
||||
let ctx = ctx.clone();
|
||||
let (send, receive) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let result = (|| {
|
||||
let flush = flush.ok_or("草稿存储暂不可用")?;
|
||||
for (token, text, primary, secondary, generation) in drafts {
|
||||
let next = generation.checked_add(1).ok_or("草稿版本溢出")?;
|
||||
flush(&token, &text, primary, secondary, next)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
let _ = send.send(result);
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
Some(receive)
|
||||
}
|
||||
|
||||
pub(super) fn flush_account_drafts(&mut self, ctx: &egui::Context) -> bool {
|
||||
if self.observed_doc.is_some() && !self.flush_document_draft(ctx, self.observed_doc, false) {
|
||||
self.account_error = "草稿保存失败,内容已保留在内存;请恢复本机写入后重试".into();
|
||||
|
||||
@ -585,6 +585,7 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val
|
||||
w.creation_width = w.creation["width"].as_u64().unwrap_or(1440) as u32;
|
||||
w.creation_count = w.creation["screenCount"].as_u64().unwrap_or(3).clamp(1, 12) as usize;
|
||||
w.creation_budget_minutes = super::product_production::budget_minutes(&w.creation);
|
||||
w.creation_delivery_dir = super::product_production::delivery_dir(&w.creation);
|
||||
if method == "creation-save"
|
||||
&& let Some(plan) = edited_plan
|
||||
{
|
||||
@ -597,6 +598,7 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val
|
||||
w.creation_width = draft["width"].as_u64().unwrap_or(1440) as u32;
|
||||
w.creation_count = draft["screenCount"].as_u64().unwrap_or(3) as usize;
|
||||
w.creation_budget_minutes = super::product_production::budget_minutes(&draft);
|
||||
w.creation_delivery_dir = super::product_production::delivery_dir(&draft);
|
||||
w.creation_plan = draft["screens"].clone();
|
||||
w.creation_direction = draft["direction"].as_str().unwrap_or("").into();
|
||||
w.creation_selected = draft["selected"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
|
||||
@ -618,10 +620,12 @@ pub(super) fn received(w: &mut Workspace, app: &PhotocraftApp, method: &str, val
|
||||
}
|
||||
w.creation_count = draft["screenCount"].as_u64().filter(|n| [3, 5, 6, 8, 12].contains(n)).unwrap_or(w.creation_count as u64) as usize;
|
||||
w.creation_budget_minutes = super::product_production::budget_minutes(&draft);
|
||||
w.creation_delivery_dir = super::product_production::delivery_dir(&draft);
|
||||
w.creation_dirty = w.creation_brief != w.creation["brief"]
|
||||
|| w.creation_plan != w.creation["plan"]["screens"]
|
||||
|| w.creation_direction != w.creation["sellingPoints"]["direction"].as_str().unwrap_or("")
|
||||
|| w.creation_count as u64 != w.creation["screenCount"].as_u64().unwrap_or(3)
|
||||
|| w.creation_delivery_dir != super::product_production::delivery_dir(&w.creation)
|
||||
|| w.creation_budget_minutes != super::product_production::budget_minutes(&w.creation);
|
||||
w.restored_creation_signature = w.creation_dirty.then(|| w.creation_draft().to_string());
|
||||
}
|
||||
@ -663,6 +667,7 @@ pub(super) fn sync_received(w: &mut Workspace, app: &PhotocraftApp, value: &Valu
|
||||
if let Some(items) = value["projects"].as_array() {
|
||||
w.merge_project_receipt(app, items);
|
||||
}
|
||||
w.project_refresh_requested = true;
|
||||
w.creation_progress = if w.sync_dirty { "云端已保存该版本,当前仍有新修改" } else { "已同步" }.into();
|
||||
}
|
||||
// The import worker reports a final receipt rather than intermediate bytes;
|
||||
@ -734,7 +739,17 @@ impl Workspace {
|
||||
if self.creation_restore_draft.is_object() {
|
||||
return self.creation_restore_draft.clone();
|
||||
}
|
||||
json!({"revision":self.creation["revision"],"brief":self.creation_brief,"width":self.creation_width,"screens":self.creation_plan,"direction":self.creation_direction,"selected":self.creation_selected,"screenCount":self.creation_count,"productionBudgetMinutes":self.creation_budget_minutes})
|
||||
let mut draft = json!({"revision":self.creation["revision"],"brief":self.creation_brief,"width":self.creation_width,
|
||||
"screens":self.creation_plan,"direction":self.creation_direction,"selected":self.creation_selected,"screenCount":self.creation_count});
|
||||
if self.creation_budget_minutes != super::product_production::DEFAULT_BUDGET_MINUTES
|
||||
|| self.creation["productionBudgetMinutes"].is_number()
|
||||
{
|
||||
draft["productionBudgetMinutes"] = json!(self.creation_budget_minutes);
|
||||
}
|
||||
if let Some(path) = &self.creation_delivery_dir {
|
||||
draft["deliveryDir"] = json!(path);
|
||||
}
|
||||
draft
|
||||
}
|
||||
fn can_save_creation(&self) -> bool {
|
||||
self.busy.is_none() && (!self.unknown || self.scoped_production_pending())
|
||||
@ -765,6 +780,7 @@ impl Workspace {
|
||||
let brief_changed = self.creation_brief != self.creation["brief"]
|
||||
|| self.creation["width"].as_u64() != Some(u64::from(self.creation_width))
|
||||
|| self.creation["screenCount"].as_u64() != Some(self.creation_count as u64)
|
||||
|| super::product_production::delivery_dir(&self.creation) != self.creation_delivery_dir
|
||||
|| super::product_production::budget_minutes(&self.creation) != self.creation_budget_minutes;
|
||||
let plan_changed = self.creation_plan != self.creation["plan"]["screens"];
|
||||
let method = if brief_changed {
|
||||
@ -783,7 +799,10 @@ impl Workspace {
|
||||
}
|
||||
pub(super) fn sync_action(&mut self, app: &PhotocraftApp, method: &str, mut input: Value) {
|
||||
if method == "project-sync" && input["status"] != "completed" {
|
||||
if let Err(error) = self.request_current_sync(app) { self.error = error.clone(); self.project_list_error = error; }
|
||||
if let Err(error) = self.request_current_sync(app, input["syncChatHistory"] == true) {
|
||||
self.error = error.clone();
|
||||
self.project_list_error = error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.busy.is_some() || self.saving.is_some() || self.project_operation_pending() {
|
||||
@ -820,9 +839,15 @@ impl Workspace {
|
||||
&& self.project_operation["accountId"] == self.account["id"] && self.project_operation["origin"] == self.origin
|
||||
&& self.current_sync_item(app).is_some_and(|item| item["id"] == self.project_operation["projectId"]);
|
||||
let label = if self.project_operation_pending() {"正在处理…"} else if sync_failed {"同步失败"} else if changed {"云同步"} else {"已同步"};
|
||||
let hint = if sync_failed { self.project_operation["message"].as_str().unwrap_or("同步未完成,请查看我的项目") } else { "备份工程、资料和对话到当前素材库账户" };
|
||||
let chat_option = ui.scope_id().with(("cloud-chat-history", self.origin.as_str(),
|
||||
self.account["id"].as_str(), app.session.active().map(|state| state.doc.id.0)));
|
||||
let mut chat = ui.ctx().data(|data| data.get_temp::<bool>(chat_option)).unwrap_or(false);
|
||||
if ui.add_enabled(idle && changed, egui::Checkbox::new(&mut chat, "同步对话")).changed() {
|
||||
ui.ctx().data_mut(|data| data.insert_temp(chat_option, chat));
|
||||
}
|
||||
let hint = if sync_failed { self.project_operation["message"].as_str().unwrap_or("同步未完成,请查看我的项目") } else { "备份工程和资料到当前素材库账户" };
|
||||
if stitch_ui::action_button(ui, label, stitch_ui::ButtonRole::Secondary, idle && changed && !self.creation_dirty).on_hover_text(hint).clicked() {
|
||||
self.sync_action(app, "project-sync", json!({"status":"draft"}));
|
||||
self.sync_action(app, "project-sync", json!({"status":"draft","syncChatHistory":chat}));
|
||||
}
|
||||
if stitch_ui::action_button(ui, "完结", stitch_ui::ButtonRole::Primary, idle && !self.unknown && !self.creation_dirty).clicked() {
|
||||
self.sync_confirm = true;
|
||||
@ -835,7 +860,7 @@ impl Workspace {
|
||||
}
|
||||
if stitch_ui::action_button(ui, "完结并同步", stitch_ui::ButtonRole::Primary, idle).clicked() {
|
||||
self.sync_confirm = false;
|
||||
self.sync_action(app, "project-sync", json!({"status":"completed"}));
|
||||
self.sync_action(app, "project-sync", json!({"status":"completed","syncChatHistory":chat}));
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -927,6 +952,9 @@ impl Workspace {
|
||||
if input["screenCount"].is_null() {
|
||||
input["screenCount"] = json!(self.creation_count);
|
||||
}
|
||||
if method == "creation-save" && input.get("deliveryDir").is_none() {
|
||||
input["deliveryDir"] = json!(self.creation_delivery_dir);
|
||||
}
|
||||
if method == "creation-save" && input["productionBudgetMinutes"].is_null() {
|
||||
input["productionBudgetMinutes"] = json!(self.creation_budget_minutes);
|
||||
}
|
||||
@ -1327,6 +1355,7 @@ impl Workspace {
|
||||
self.creation_dirty |= response.changed();
|
||||
self.control_geometry("production-budget", response.rect);
|
||||
});
|
||||
self.delivery_directory_control(app, ui, editable);
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let save = stitch_ui::action_button(
|
||||
@ -1472,6 +1501,52 @@ impl Workspace {
|
||||
})
|
||||
}
|
||||
|
||||
fn delivery_directory_control(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, editable: bool) {
|
||||
ui.label("成品自动保存目录");
|
||||
let path = self.creation_delivery_dir.as_deref().unwrap_or("未选择");
|
||||
ui.add(egui::Label::new(path).wrap()).on_hover_text(path);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let choose = stitch_ui::action_button(ui, "选择文件夹", stitch_ui::ButtonRole::Secondary, editable);
|
||||
self.control_geometry("choose-delivery-directory", choose.rect);
|
||||
if choose.clicked() {
|
||||
let initial_dir = self.creation_delivery_dir.clone();
|
||||
let doc = self.creation_doc;
|
||||
let identity = self.local_identity("");
|
||||
if let Err(error) = app.ask_file(crate::FileDialogRequest::Folder { initial_dir }, move |app, answer| {
|
||||
let path = match answer {
|
||||
crate::FileDialogAnswer::FolderTo(path) => path,
|
||||
crate::FileDialogAnswer::Unavailable(error) => return Err(error),
|
||||
_ => return Ok(Value::Null),
|
||||
};
|
||||
let w = app.jiansun.as_mut().filter(|w| w.creation_doc == doc && w.local_identity("") == identity)
|
||||
.ok_or("账号或项目已切换,未修改保存目录")?;
|
||||
if !std::path::Path::new(&path).is_absolute() {
|
||||
return Err("请选择绝对路径的成品目录".into());
|
||||
}
|
||||
if app.session.active().and_then(|state| state.path.as_deref())
|
||||
.map(std::path::Path::new).and_then(std::path::Path::parent)
|
||||
.is_some_and(|draft| std::path::Path::new(&path).starts_with(draft) && draft.ends_with(
|
||||
w.open_projects.get(&doc.unwrap_or_default()).and_then(|id| id.rsplit('|').next()).unwrap_or_default()))
|
||||
{
|
||||
return Err("请选择项目草稿目录以外的位置".into());
|
||||
}
|
||||
w.creation_delivery_dir = Some(path);
|
||||
w.creation_dirty = true;
|
||||
Ok(Value::Null)
|
||||
}) {
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
let clear = stitch_ui::action_button(ui, "清除", stitch_ui::ButtonRole::Secondary,
|
||||
editable && self.creation_delivery_dir.is_some());
|
||||
self.control_geometry("clear-delivery-directory", clear.rect);
|
||||
if clear.clicked() {
|
||||
self.creation_delivery_dir = None;
|
||||
self.creation_dirty = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn add_reference_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, width: f32) {
|
||||
let supported = ui.input(|input| {
|
||||
let files = &input.raw.hovered_files;
|
||||
@ -1533,7 +1608,7 @@ impl Workspace {
|
||||
let variants = brief_variants(&brief);
|
||||
set_brief_variants(&mut brief, variants);
|
||||
brief["templateSelection"] = template.clone();
|
||||
if let Err(error) = self.slot_action(app, "slot-skeleton", json!({"brief":brief,"width":self.creation_width,"template":template,"outputId":"detail","generateProduct":generate,"productionBudgetMinutes":self.creation_budget_minutes})) {
|
||||
if let Err(error) = self.slot_action(app, "slot-skeleton", json!({"brief":brief,"width":self.creation_width,"template":template,"outputId":"detail","generateProduct":generate,"productionBudgetMinutes":self.creation_budget_minutes,"deliveryDir":self.creation_delivery_dir})) {
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
@ -3427,18 +3502,23 @@ mod tests {
|
||||
let (mut w, mut app, requests) = brief_fixture();
|
||||
w.creation["revision"] = json!(1);
|
||||
w.creation_dirty = true;
|
||||
let delivery = std::env::temp_dir().join("成品");
|
||||
w.creation_delivery_dir = Some(delivery.to_string_lossy().into_owned());
|
||||
w.creation_action(&mut app, "creation-save", json!({})).unwrap();
|
||||
assert!(form_editable(w.busy.as_deref(), false));
|
||||
let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("save request") };
|
||||
assert_eq!(method, "creation-save");
|
||||
assert_eq!(input["deliveryDir"], json!(delivery));
|
||||
w.creation_delivery_dir = None;
|
||||
w.creation_brief["name"] = json!("保存过程中继续输入的产品名");
|
||||
w.creation_brief["categoryName"] = json!("新选品类");
|
||||
let draft = w.creation_draft();
|
||||
let value = json!({"doc":w.creation_doc,"accountId":w.account["id"],"origin":w.origin,
|
||||
"creation":{"revision":2,"brief":input["brief"],"width":input["width"],"screenCount":input["screenCount"],"plan":{"screens":input["screens"]}}});
|
||||
"creation":{"revision":2,"deliveryDir":input["deliveryDir"],"brief":input["brief"],"width":input["width"],"screenCount":input["screenCount"],"plan":{"screens":input["screens"]}}});
|
||||
received(&mut w, &app, "creation-save", &value);
|
||||
assert_eq!(w.creation_brief, draft["brief"]);
|
||||
assert!(w.creation_dirty);
|
||||
assert!(w.creation_delivery_dir.is_none(), "clearing the folder supersedes the in-flight save");
|
||||
assert_eq!(w.creation["revision"], 2);
|
||||
assert!(!form_editable(Some("creation-import"), false));
|
||||
assert!(!form_editable(None, true));
|
||||
@ -3570,10 +3650,13 @@ mod tests {
|
||||
let search = control_rect(&w, "source-search");
|
||||
let hint = control_rect(&w, "entry-hint");
|
||||
let budget = control_rect(&w, "production-budget");
|
||||
let delivery = control_rect(&w, "choose-delivery-directory");
|
||||
let enter = control_rect(&w, "enter-canvas");
|
||||
assert_eq!(w.creation_budget_minutes, 45);
|
||||
assert!(hint.bottom() <= budget.top() && budget.bottom() <= enter.top());
|
||||
assert!(budget.right() <= width);
|
||||
assert!(budget.bottom() <= delivery.top() && delivery.bottom() <= enter.top());
|
||||
assert!(delivery.right() <= width);
|
||||
if width >= 900.0 {
|
||||
assert!(source.right() < search.left() && source.top() < search.bottom() && search.top() < source.bottom(), "wide source and lookup share a row");
|
||||
assert!(hint.bottom() <= enter.top(), "entry actions follow the save status");
|
||||
|
||||
@ -6,12 +6,19 @@ use super::{json, Workspace, Value, BridgeFailure, PhotocraftApp, Instant, workf
|
||||
#[path = "pi_core_smoke.rs"]
|
||||
mod core_smoke;
|
||||
|
||||
fn identity(w: &Workspace, input: &Value) -> Result<(), String> {
|
||||
if w.pi_run.as_deref().is_some_and(|s| input["run"].as_str() == Some(s)) && w.pi_binding == json!({"accountId":w.account["id"],"origin":w.origin}) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("本地Agent会话或账户已改变".into())
|
||||
fn identity(w: &Workspace, input: &Value) -> Result<(), BridgeFailure> {
|
||||
let run = input["run"].as_str();
|
||||
if w.pi_binding == json!({"accountId":w.account["id"],"origin":w.origin}) {
|
||||
if run.is_some() && run == w.pi_run.as_deref()
|
||||
&& w.accepts_production_epoch(&w.pi_request_scope["writeEpoch"])
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if w.pi_request_scope["productProduction"] == true && run.is_some_and(|id| w.agent_native.cancelled(id)) {
|
||||
return Err(BridgeFailure::new("cancelled", false, false, "当前制作会话已取消"));
|
||||
}
|
||||
}
|
||||
Err("本地Agent会话或账户已改变".into())
|
||||
}
|
||||
fn status(w: &Workspace, app: &PhotocraftApp) -> Value {
|
||||
let same = app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc && s.revision == w.expected_revision);
|
||||
@ -116,6 +123,11 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result<Value, String> {
|
||||
}
|
||||
let mut clean = json!({"version":1,"type":"tool","toolCallId":call,"toolName":name,"status":state,
|
||||
"timestampMs":timestamp,"summary":format!("{prefix}:{label}"),"run":w.pi_run});
|
||||
if let Some(category) = event["category"].as_str().filter(|category| matches!(*category,
|
||||
"inference" | "canvas_read" | "canvas_write" | "disk_persist" | "remote_image" | "ui_ack" | "export")) {
|
||||
clean["category"] = json!(category);
|
||||
clean["phase"] = json!(state);
|
||||
}
|
||||
if !event["durationMs"].is_null() {
|
||||
let duration = event["durationMs"].as_u64().filter(|n| *n <= MAX_SAFE_INTEGER).ok_or("工具状态时长无效")?;
|
||||
clean["durationMs"] = json!(duration);
|
||||
@ -216,8 +228,17 @@ fn image_linked_copy(doc: &photocraft_doc::Document, slot_id: &Value) -> Vec<Val
|
||||
}
|
||||
|
||||
fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &str, input: &Value, private: bool) -> Result<Value, BridgeFailure> {
|
||||
if !w.authority_active() {
|
||||
return Err(BridgeFailure::new("auth_revoked", false, false, "授权已失效,原操作未应用"));
|
||||
}
|
||||
if matches!(method, "pi-production-open" | "pi-image-request" | "pi-workflow-execute" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen") && !private { return Err("工作流执行仅允许当前本机Agent会话".into()); }
|
||||
if method == "pi-begin" {
|
||||
if w.library_http_status == Some(401) {
|
||||
return Err(BridgeFailure::new("auth_revoked", false, false, "授权已失效,制作已暂停;请重新登录"));
|
||||
}
|
||||
if !w.accepts_production_epoch(&input["requestScope"]["writeEpoch"]) {
|
||||
return Err(BridgeFailure::new("cancelled", false, false, "原制作回合已停止"));
|
||||
}
|
||||
if (input["accountId"].is_string() && input["accountId"] != w.account["id"]) || (input["origin"].is_string() && input["origin"] != w.origin) {
|
||||
return Err("画布与模型账户不一致".into());
|
||||
}
|
||||
@ -299,6 +320,10 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
if method == "pi-edit-reconcile" { return super::agent_native::reconcile_edit(w, app, input).map_err(BridgeFailure::from); }
|
||||
if method == "pi-workflow-reconcile" { return workflow_bridge::reconcile(w, app, input).map_err(BridgeFailure::from); }
|
||||
identity(w, input)?;
|
||||
let key = &w.pi_request_scope["documentKey"];
|
||||
if key.is_object() && app.session.active().is_none_or(|active| super::product_document_key(&active.doc) != *key) {
|
||||
return Err(BridgeFailure::new("scope_changed", false, false, "原工作画布的输出、花色或模板映射已变化"));
|
||||
}
|
||||
w.pi_touched = Instant::now();
|
||||
w.track_pi_canvas(app);
|
||||
if method != "pi-state" && !app.session.active().is_some_and(|s| Some(s.doc.id.0) == w.owner_doc) {
|
||||
@ -524,6 +549,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
return Err("图位不属于本轮制作画布".into());
|
||||
}
|
||||
Ok(json!({"action":action,"request":request,"revision":w.expected_revision,
|
||||
"writeEpoch":w.pi_request_scope["writeEpoch"],
|
||||
"scope":{"id":w.template_workflow["workspaceId"],"templateHash":w.template_workflow["templateHash"],
|
||||
"structureHash":w.template_workflow["structureHash"],"outputId":w.pi_request_scope["outputId"],
|
||||
"variantId":w.pi_request_scope["variantId"]}}))
|
||||
@ -799,6 +825,25 @@ mod tests {
|
||||
(w, app, input)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_auth_epoch_change_rejects_a_queued_write_before_the_account_event() {
|
||||
use std::sync::{Arc, atomic::{AtomicU64, Ordering}};
|
||||
let (mut w, mut app, mut input) = activity_fixture();
|
||||
let epoch = Arc::new(AtomicU64::new(0));
|
||||
w.account_epoch = Some(epoch.clone());
|
||||
w.allow_apply = true;
|
||||
input["accountEpoch"] = json!(0);
|
||||
epoch.store(1, Ordering::Release);
|
||||
let (reply, result) = mpsc::channel();
|
||||
let ctx = egui::Context::default();
|
||||
w.receive_event(&mut app, &ctx, super::super::Event::PiAction("pi-edit".into(), input, reply));
|
||||
assert_eq!(result.recv().unwrap().unwrap_err().category, "auth_revoked");
|
||||
let change = json!({"category":"auth_revoked","accountId":w.account["id"],"origin":w.origin});
|
||||
w.receive_event(&mut app, &ctx, super::super::Event::Json("auth-fence".into(), Ok(change)));
|
||||
assert!(!w.allow_apply && w.pi_write_blocked && w.agent_effects_paused);
|
||||
assert_eq!(w.library_http_status, Some(401));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_pi_action_cannot_expose_private_workflow_delegation() {
|
||||
let (mut w, mut app, mut input) = activity_fixture();
|
||||
@ -1129,6 +1174,8 @@ mod tests {
|
||||
let (_, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
w.account = json!({"id":"qa"});
|
||||
w.model = "chat-qa".into();
|
||||
w.models = vec![json!({"id":"qa","key":"chat-qa"})];
|
||||
w.busy = Some("agent".into());
|
||||
w.pi_request_scope = w.context(&app)["requestScope"].clone();
|
||||
w.owner_doc = Some(id);
|
||||
@ -1498,6 +1545,7 @@ mod tests {
|
||||
w.canvas_workspace.variant = "wood".into();
|
||||
w.template_workflow = json!({"templateId":"pack","templateVersion":"1","templateHash":"original"});
|
||||
let original_layer = app.session.active().unwrap().active_layer.unwrap().0;
|
||||
w.composer_reference_add_target(&app, &json!({"documentId":doc,"nativeLayerId":original_layer,"component":"layer"})).unwrap();
|
||||
w.submit(&app, "分析这张候选,但不要直接修改".into());
|
||||
let Request::Action(method, request) = requests.try_recv().unwrap() else { panic!("one explicit request") };
|
||||
assert_eq!(method, "agent");
|
||||
@ -1535,12 +1583,14 @@ mod tests {
|
||||
w.unknown = false;
|
||||
w.model_ready = true;
|
||||
w.canvas_workspace.context = None;
|
||||
let document = app.session.active().unwrap().doc.id.0;
|
||||
let layer = app.session.execute("type.create", json!({"text":"原图位标题","size":24})).unwrap()["layer"].as_u64().unwrap();
|
||||
w.composer_reference_add_target(&app, &json!({"documentId":document,"nativeLayerId":layer,"component":"layer"})).unwrap();
|
||||
w.submit(&app, "只解释原图位".into());
|
||||
let Request::Action(_, request) = requests.try_recv().expect("submitted request") else { panic!("expected action") };
|
||||
let snapshot = request["context"]["requestScope"].clone();
|
||||
assert!(!snapshot["references"].as_array().unwrap().is_empty());
|
||||
let run = "12345678-1234-1234-1234-123456789012";
|
||||
let document = app.session.active().unwrap().doc.id.0;
|
||||
for field in ["subject", "references", "component"] {
|
||||
let mut forged = snapshot.clone();
|
||||
match field {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -118,9 +118,9 @@ impl Workspace {
|
||||
Some(self.project_sync_item(app, &item))
|
||||
}
|
||||
|
||||
pub(super) fn request_current_sync(&mut self, app: &PhotocraftApp) -> Result<Value, String> {
|
||||
pub(super) fn request_current_sync(&mut self, app: &PhotocraftApp, chat: bool) -> Result<Value, String> {
|
||||
let item = self.current_sync_item(app).ok_or("请先保存并打开项目")?;
|
||||
self.request_project_sync(app, &item)
|
||||
self.request_project_sync_with_policy(app, &item, chat)
|
||||
}
|
||||
|
||||
fn project_action_block(&self, app: &PhotocraftApp, item: &Value) -> Option<&'static str> {
|
||||
@ -149,6 +149,10 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn request_project_sync(&mut self, app: &PhotocraftApp, item: &Value) -> Result<Value, String> {
|
||||
self.request_project_sync_with_policy(app, item, false)
|
||||
}
|
||||
|
||||
fn request_project_sync_with_policy(&mut self, app: &PhotocraftApp, item: &Value, chat: bool) -> Result<Value, String> {
|
||||
if let Some(reason) = self.project_action_block(app, item) { return Err(reason.into()); }
|
||||
let item = self.project_sync_item(app, item);
|
||||
let (_, action) = sync_choice(&item);
|
||||
@ -162,6 +166,7 @@ impl Workspace {
|
||||
input = item["cloudUpdateRef"].clone();
|
||||
} else if kind == "sync" {
|
||||
input["localId"] = item["id"].clone();
|
||||
input["syncChatHistory"] = json!(chat);
|
||||
input["status"] = json!("draft");
|
||||
let identity = self.local_identity(item["id"].as_str().ok_or("项目编号无效")?);
|
||||
if let Some(state) = app.session.documents().iter().find(|state| self.open_projects.get(&state.doc.id.0) == Some(&identity)) {
|
||||
|
||||
@ -11,11 +11,12 @@ struct SaveDialog {
|
||||
psd: bool,
|
||||
jpg: bool,
|
||||
candidates: bool,
|
||||
chat_history: Option<bool>,
|
||||
}
|
||||
|
||||
impl SaveDialog {
|
||||
fn options(&self, file: String) -> Value {
|
||||
json!({"file":file,"project":self.project,"psd":self.psd,"jpg":self.jpg,"candidates":self.candidates})
|
||||
json!({"file":file,"project":self.project,"psd":self.psd,"jpg":self.jpg,"candidates":self.candidates,"syncChatHistory":self.chat_history})
|
||||
}
|
||||
}
|
||||
|
||||
@ -59,7 +60,7 @@ impl PhotocraftApp {
|
||||
let name: String = name.chars().map(|ch| if ch.is_control() || "\"<>:/\\|?*".contains(ch) { '_' } else { ch }).collect();
|
||||
let suggested = previous.clone().unwrap_or_else(|| format!("{name}.xiaoyi"));
|
||||
let dialog = SaveDialog { doc, account:w.account["id"].clone(), origin:w.origin.clone(),
|
||||
project:true, psd:false, jpg:false, candidates:false, suggested };
|
||||
project:true, psd:false, jpg:false, candidates:false, chat_history:(choose || previous.is_none()).then_some(false), suggested };
|
||||
if let Some(file) = previous.filter(|_| !choose) {
|
||||
Some(w.submit_project_save(self, ctx, &dialog, file))
|
||||
} else {
|
||||
@ -90,6 +91,9 @@ pub(super) fn show_project_save(w: &mut Workspace, app: &mut PhotocraftApp, ctx:
|
||||
ui.add_space(12.0);
|
||||
ui.checkbox(&mut dialog.project, "小壹工程 (.xiaoyi)");
|
||||
ui.label(RichText::new("打开工程可继续编辑画布和候选").size(12.0).color(tokens.text_dim));
|
||||
let mut include_chat = dialog.chat_history == Some(true);
|
||||
ui.add_enabled(dialog.project, egui::Checkbox::new(&mut include_chat, "随工程保存项目对话"));
|
||||
dialog.chat_history = Some(include_chat && dialog.project);
|
||||
ui.add_space(8.0);
|
||||
ui.checkbox(&mut dialog.psd, "PSD 分层文件");
|
||||
ui.checkbox(&mut dialog.jpg, "JPG 图片");
|
||||
@ -143,6 +147,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn save_dialog_initializes_project_and_keeps_export_choices_independent() {
|
||||
for width in [800.0, 420.0] {
|
||||
exercise_save_dialog(width);
|
||||
}
|
||||
}
|
||||
|
||||
fn exercise_save_dialog(width: f32) {
|
||||
let (tx, _) = std::sync::mpsc::channel();
|
||||
let (_, rx) = std::sync::mpsc::channel();
|
||||
let mut workspace = Workspace::new(tx, rx);
|
||||
@ -155,7 +165,7 @@ mod tests {
|
||||
let mut started = false;
|
||||
let builder = Harness::builder()
|
||||
.with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
|
||||
.with_size(egui::vec2(800.0, 570.0));
|
||||
.with_size(egui::vec2(width, 570.0));
|
||||
let mut harness = builder.wgpu().build_ui_state(move |ui, app| {
|
||||
if !started {
|
||||
PhotocraftApp::setup_context(ui.ctx(), crate::theme::ThemeKind::ProMedium);
|
||||
@ -171,8 +181,9 @@ mod tests {
|
||||
let read = |ctx: &egui::Context| ctx.data(|data| data.get_temp::<SaveDialog>(id)).unwrap();
|
||||
let initial = read(&harness.ctx);
|
||||
assert!(initial.project);
|
||||
assert_eq!(initial.chat_history, Some(false));
|
||||
assert!(!initial.psd && !initial.jpg && !initial.candidates);
|
||||
for label in ["PSD 分层文件", "JPG 图片", "候选区图片"] {
|
||||
for label in ["随工程保存项目对话", "PSD 分层文件", "JPG 图片", "候选区图片"] {
|
||||
let pos = harness.get_by_label(label).rect().center();
|
||||
harness.hover_at(pos);
|
||||
harness.run_steps(2);
|
||||
@ -183,7 +194,10 @@ mod tests {
|
||||
}
|
||||
let selected = read(&harness.ctx);
|
||||
assert!(selected.project && selected.psd && selected.jpg && selected.candidates);
|
||||
assert_eq!(selected.options("test.xiaoyi".into())["syncChatHistory"], true);
|
||||
if let Some(path) = std::env::var_os("PHOTOCRAFT_PROJECT_SAVE_SCREENSHOT") {
|
||||
let path = std::path::PathBuf::from(path);
|
||||
let path = if width < 700.0 { path.with_file_name("project-save-narrow.png") } else { path };
|
||||
harness.render().unwrap().save(path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -257,6 +257,7 @@ pub(crate) use services::SAVE_OPTIONS_OPEN;
|
||||
#[cfg(test)]
|
||||
pub(crate) use services::saved_revision_after_write;
|
||||
pub use services::{
|
||||
AppTray, TrayAction,
|
||||
AdoptAutosaveFn, AgentDaemonFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationReadLimitedFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn,
|
||||
CaptionStyleFn, ClipboardGetFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings,
|
||||
ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn,
|
||||
@ -711,6 +712,7 @@ pub struct PhotocraftApp {
|
||||
pub(crate) held_preset_import: Option<preset_group_prompt::Held>,
|
||||
/// Set once the user has agreed to quit, so the resulting close request goes through.
|
||||
pub(crate) allow_close: bool,
|
||||
pub(crate) explicit_exit: bool,
|
||||
/// Pen pressure/tilt from the platform (see `stylus`).
|
||||
pub stylus: stylus::Stylus,
|
||||
control_click: control_click::ControlClick,
|
||||
|
||||
@ -45,8 +45,16 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Va
|
||||
{
|
||||
authorize(id, ¶ms)?;
|
||||
}
|
||||
if id == "file.exit" && crate::jiansun::guard_production_exit(app, ctx) {
|
||||
return Ok(Value::Null);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if id == "file.exit" {
|
||||
app.explicit_exit = true;
|
||||
if crate::jiansun::guard_production_exit(app, ctx) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if crate::jiansun::flushing_exit(app) {
|
||||
return Err("正在保存小壹进度,请等待退出".into());
|
||||
}
|
||||
if crate::discard_ui::intercept(app, id, ¶ms) {
|
||||
return Ok(Value::Null);
|
||||
@ -275,6 +283,7 @@ fn invoke_file_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str,
|
||||
}
|
||||
}
|
||||
"file.exit" => {
|
||||
app.explicit_exit = true;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@ -486,6 +486,7 @@ pub struct Services {
|
||||
/// (Windows custom title bar, #2246). Called once per frame; `None` when the window is
|
||||
/// decorated or the platform needs no fixing.
|
||||
pub window_frame: Option<WindowFrameFn>,
|
||||
pub app_tray: Option<Box<dyn AppTray>>,
|
||||
/// How the custom title bar's caption buttons look and where they sit (Linux: the desktop's
|
||||
/// style and button layout). Read every frame, with the context to wake when it changes;
|
||||
/// `None` keeps Windows' buttons at the right end.
|
||||
@ -507,3 +508,16 @@ pub struct Services {
|
||||
/// Without one, eframe closes the window and the app ends with it.
|
||||
pub quit: Option<QuitFn>,
|
||||
}
|
||||
|
||||
/// The desktop shell owns the notification-area icon and its native event callbacks.
|
||||
pub trait AppTray {
|
||||
fn visible(&self) -> bool;
|
||||
fn show(&mut self, status: &str) -> Result<(), String>;
|
||||
fn take_action(&mut self) -> Option<TrayAction>;
|
||||
fn set_status(&mut self, status: &str);
|
||||
}
|
||||
|
||||
pub enum TrayAction {
|
||||
Restore,
|
||||
Exit,
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user