diff --git a/Backend/README.md b/Backend/README.md
index 0b199fd..e7046f0 100644
--- a/Backend/README.md
+++ b/Backend/README.md
@@ -17,11 +17,13 @@ SOURCE_BACKUP=大鱼调色仓库 Backend/
## 客户端
-主 APP 检查更新与插件注册并行,检查结束且注册成功后显示3秒退出倒计时。发现更新则保留窗口;下载可取消,校验 SHA-256、字节数、Installer/App签名团队、Gatekeeper、包内 Bundle ID、版本、安装位置及模板。保存并退出 FCP/Motion 后打开系统安装器,不强杀宿主。下一次启动可记录已完成升级。
+主 APP 检查更新与插件注册并行,注册后保持运行,关闭窗口后仍在后台收集诊断;菜单栏可重新打开或明确退出。发现更新会显示提示;下载可取消,校验 SHA-256、字节数、Installer/App签名团队、Gatekeeper、包内 Bundle ID、版本、安装位置及模板。保存并退出 FCP/Motion 后打开系统安装器,不强杀宿主。下一次启动可记录已完成升级。
主 APP 与 XPC 共享随机安装标识及诊断开关。诊断默认开启,界面明确说明并可关闭;不上传素材、LUT、预设、用户路径、账号、硬件 UUID 或原始崩溃文件。后台私有队列最多256条/384KB,批次16条,网络超时并延迟重试,服务端按事件 UUID 去重。关闭后清除待发摘要并停止新请求;已经送达的数据按保留期清理。
-采集进程启动、初始化、检查器创建/慢刷新、Metal 管线准备、首次渲染、渲染错误、超过6秒的疑似阻塞,以及本插件近7天系统崩溃报告的脱敏摘要。疑似阻塞不等于根因;整个进程被停止、网络不可用、主机强制断电时无法保证即时送达。不会拦截崩溃信号,也不采集整个 FCP 的报告。本轮保留调色与宿主回调逻辑,尚未修复偶发卡死。
+1.18.0(104)起每分钟汇总进程内存/CPU/线程数和渲染、参数读取、跟踪帧耗时;慢于100ms的单次事件最多每阶段30秒一条。超过6秒的疑似阻塞附当前阶段,并限频调用系统 sample 采样本进程1秒(间隔至少120秒,每小时最多6次,8秒超时,失败明确标记);仅提取调用栈,临时原文随即删除。主运行循环使用公共模式脉冲,避免正常菜单/模态循环被主队列探针误报。
+
+主 APP 每分钟扫描本产品 APP 和 XPC 近7天 IPS,补采终止后的待发送队列;不要求用户重启主 APP。崩溃摘要记录故障实际版本/build、终止类别、故障线程的镜像UUID与偏移;排除自检和 ASAN 记录。已送达报告本地去重,云端继续按事件UUID去重。疑似阻塞不等于根因;整个进程被停止、网络不可用、主机强制断电时无法保证即时送达。不会拦截崩溃信号,也不采集整个 FCP 的报告;整个进程完全无法调度时,内部采样无法运行,须依靠系统生成的后续报告。本轮保留调色与宿主回调逻辑,尚未修复偶发卡死。
## 验证与发布
diff --git a/Backend/tests/contract.php b/Backend/tests/contract.php
index 68e9b23..fddb5db 100644
--- a/Backend/tests/contract.php
+++ b/Backend/tests/contract.php
@@ -38,6 +38,9 @@ try {
$reply=Dayu_Color_Beta::ingest(request($body));
check($reply->status===200 && $reply->data['accepted'] && count($wpdb->rows)===1,'valid event accepted');
Dayu_Color_Beta::ingest(request($body));check(count($wpdb->rows)===1,'retry idempotency');
+ $newFields=array('source_build'=>'104','process_role'=>'plugin','termination_namespace'=>'DYLD','termination_code'=>1,'memory_mb'=>512,'cpu_percent'=>120,'thread_count'=>32,'resource_kind'=>'cube','pid'=>123,'width'=>3840,'height'=>2160,'sample_status'=>'captured','frames'=>'DYRenderer | image + 32 | UUID');
+ check(Dayu_Color_Beta::clean_fields($newFields)==$newFields,'new evidence fields survive server normalization');
+ foreach(array('render','plugin_state','tracking_frame','process_health','performance_summary','hang_sample') as $name){$b=$body;$b['events'][0]['event']=$name;$b['events'][0]['fields']=$newFields;check(Dayu_Color_Beta::ingest(request($b))->status===200,'new event accepted '.$name);}
foreach(array('version'=>array(),'build'=>array(),'event'=>'material_path','session_id'=>'bad','occurred_at'=>null) as $key=>$bad){$b=$body;$b['events'][0][$key]=$bad;check(Dayu_Color_Beta::ingest(request($b))->data['status']===400,'malformed '.$key);}
$b=$body;$b['events']=array_fill(0,33,$event);check(Dayu_Color_Beta::ingest(request($b))->data['status']===400,'batch limit');
$b=$body;$b['padding']=str_repeat('a',100000);check(Dayu_Color_Beta::ingest(request($b))->data['status']===413,'byte limit');
diff --git a/Backend/wp-content/mu-plugins/dayu-color-beta.php b/Backend/wp-content/mu-plugins/dayu-color-beta.php
index 5612ddb..a1a93a7 100644
--- a/Backend/wp-content/mu-plugins/dayu-color-beta.php
+++ b/Backend/wp-content/mu-plugins/dayu-color-beta.php
@@ -12,10 +12,10 @@ final class Dayu_Color_Beta {
const EVENTS = array('process_start','process_exit','plugin_init','inspector_create','inspector_refresh',
'device_prepare','gpu_pipeline','first_render','render_error','main_thread_stall',
'operation_stall','previous_session_pending','crash_summary','registration','host_confirmed',
- 'update_check','update_download','update_validation','update_installer','diagnostic_summary');
+ 'render','plugin_state','tracking_frame','process_health','performance_summary','hang_sample','update_check','update_download','update_validation','update_installer','diagnostic_summary');
const FIELDS = array('phase','stage','pipeline','duration_ms','status','error_domain','error_code',
'exception','signal','frames','report_time','count','pending','model','os_version','fcp_version',
- 'cpu_cores','memory_gb','gpu','main_delay_ms','active_stages','source_version');
+ 'cpu_cores','memory_gb','gpu','main_delay_ms','active_stages','source_version','source_build','process_role','termination_namespace','termination_code','pid','resource_kind','memory_mb','cpu_percent','thread_count','uptime_s','max_duration_ms','average_ms','width','height','layer_count','mask_count','sample_status');
public static function boot() {
add_action('rest_api_init', array(__CLASS__, 'routes'));
@@ -90,7 +90,7 @@ final class Dayu_Color_Beta {
$out = array();
foreach (self::FIELDS as $key) {
if (!array_key_exists($key,$input) || !is_scalar($input[$key])) continue;
- if (in_array($key,array('duration_ms','main_delay_ms','memory_gb','cpu_cores','count','pending','error_code'),true)) {
+ if (in_array($key,array('duration_ms','main_delay_ms','memory_gb','cpu_cores','count','pending','error_code','pid','termination_code','memory_mb','cpu_percent','thread_count','uptime_s','max_duration_ms','average_ms','width','height','layer_count','mask_count'),true)) {
if (is_numeric($input[$key]) && is_finite((float)$input[$key])) $out[$key]=max(-1000000,min(86400000,(float)$input[$key]));
continue;
}
@@ -165,15 +165,17 @@ final class Dayu_Color_Beta {
echo '
公测更新
'.($manifest?'当前版本:'.esc_html($manifest['version']).'('.esc_html($manifest['build']).')':'尚未发布更新包').'
';
echo '诊断事件
| 时间(UTC) | 版本 | 报告标识 | 来源/事件 | 内容 |
';
+ echo '| 时间(UTC) | 上传版本 / 故障版本 | 报告标识 | 来源/事件 | 内容 |
';
foreach ($result['events'] as $row) {
- echo ''.esc_html($row['occurred_at']).' 送达 '.esc_html($row['received_at']).' | '.esc_html($row['client_version'].' ('.$row['client_build'].')').' | '.esc_html($row['installation_id']).' 会话 '.esc_html(substr($row['session_id'],0,8)).' | '.esc_html($row['source'].' / '.$row['event']).' | '.esc_html(wp_json_encode(json_decode($row['fields_json'],true),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)).' |
';
+ $fields=json_decode($row['fields_json'],true)?:array();
+ $crashed=$row['event']==='crash_summary' ? '
故障:'.esc_html(($fields['source_version']??'未知').' ('.($fields['source_build']??'未采集').')') : '';
+ echo ''.esc_html($row['occurred_at']).' 送达 '.esc_html($row['received_at']).' | '.esc_html($row['client_version'].' ('.$row['client_build'].')').$crashed.' | '.esc_html($row['installation_id']).' 会话 '.esc_html(substr($row['session_id'],0,8)).' | '.esc_html($row['source'].' / '.$row['event']).' | '.esc_html(wp_json_encode(json_decode($row['fields_json'],true),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)).' |
';
}
echo '
';
$base=array('page'=>'dayu-color-beta','build'=>$request->get_param('build'),'event'=>$request->get_param('event'),'installation'=>$request->get_param('installation'));
if ($result['page']>1) echo '上一页 ';
if (count($result['events'])===50) echo '下一页';
- echo '
仅包含产品版本、环境、阶段耗时、错误代码及本插件崩溃摘要,不接收素材、预设、硬件UUID或账户凭据。
';
+ echo '仅包含产品版本、环境、阶段耗时、资源使用、错误代码及本产品崩溃/卡顿调用栈摘要,不接收素材、预设、硬件UUID或账户凭据。
';
}
}
Dayu_Color_Beta::boot();
diff --git a/Packaging/build_pkg.py b/Packaging/build_pkg.py
index d27ede0..ca5b8ce 100644
--- a/Packaging/build_pkg.py
+++ b/Packaging/build_pkg.py
@@ -112,8 +112,8 @@ def main():
appearance=dict(title="大鱼调色", subtitle="适用于 Final Cut Pro 与 Motion 的原生调色效果",
badgeImage=str(ROOT / "design/dayu-color-app-icon-v1.png"), authorContact="https://dayu.media"),
pages=dict(welcome="安装大鱼调色 " + version + ",包含原生 FxPlug 调色插件和 Final Cut Pro 效果入口。",
- readme="系统要求:macOS 14.6 或更高版本。本发行构建适用于 Apple Silicon Mac。\n\n安装内容:\n/Library/Plug-Ins/FxPlug/大鱼调色.app\n登录用户“影片/Motion Templates/Effects/大鱼调色”中的效果模板与预览图。\n\n重新打开 Final Cut Pro 后,在“效果 → 大鱼调色”中应用;Motion 中可选择原生滤镜。\n本安装包不包含用户自选 LUT、预设或媒体文件。\n\n公测诊断默认开启,可在主 APP 关闭。仅发送版本、系统环境、加载耗时与本插件错误摘要到 dayu.media;不发送素材、预设或账号,保留30天。主 APP 启动时检查更新,新版由用户确认安装。",
- license="", conclusion="大鱼调色已安装。主 APP 自动注册插件,成功后显示3秒倒计时退出。可点击“打开 FCP 检查”保留窗口,并在宿主中实际检查效果。"))
+ readme="系统要求:macOS 14.6 或更高版本。本发行构建适用于 Apple Silicon Mac。\n\n安装内容:\n/Library/Plug-Ins/FxPlug/大鱼调色.app\n登录用户“影片/Motion Templates/Effects/大鱼调色”中的效果模板与预览图。\n\n重新打开 Final Cut Pro 后,在“效果 → 大鱼调色”中应用;Motion 中可选择原生滤镜。\n本安装包不包含用户自选 LUT、预设或媒体文件。\n\n公测诊断默认开启,可在主 APP 关闭。仅发送版本、系统环境、阶段耗时、资源使用与本产品崩溃/卡顿调用栈摘要到 dayu.media;不发送素材、预设或账号,保留30天。主 APP 启动时检查更新,新版由用户确认安装。",
+ license="", conclusion="大鱼调色已安装。主 APP 自动注册插件,成功后保持运行。关闭窗口仍在后台收集已开启的诊断;菜单栏可重新打开或退出。请重开宿主并实际检查效果。"))
manifest_path = CACHE / "dayu-color-package-manifest.json"
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
command = ["/usr/bin/python3", str(skill / "package_fxplug.py"), "--repo", str(forge), "--manifest", str(manifest_path)]
diff --git a/README.md b/README.md
index d47b053..7af7243 100644
--- a/README.md
+++ b/README.md
@@ -94,7 +94,7 @@ PQ/HLG 输出或跟随 Rec.2020 宿主暂只接受一级与印片;存在活跃
1.7.1 兼容颜色数据行夹带文字的 Cube:保留数值前缀、未读取通道补 0、保持原行位置。用户原文件 65³ 全表与本机 FCP 自定 LUT 读取规则对照通过;正式路径407项原生检查、FCP导入/缩略图/应用/冷重开通过,原始字节保留。见[兼容依据](research/LUTNotes1.7.1.md)、[宿主验证](verification/HostLUTNotes1.7.1.json)和[1.7.1安装包 Release](https://dayu.media/git/dayu/dayu-color/releases/tag/v1.7.1-lut-notes-20261102)。网站公测更新清单仍为原1.7.0,本轮未改动后端。
-主 APP 保留深色介绍、置顶发布地址、自动注册和3秒退出倒计时;加入启动自动检查公测更新和可关闭的云端诊断。更新使用完整 PKG,由用户确认下载并通过完整性、签名与产品校验后打开系统安装器;安装前要求保存并退出 FCP/Motion。诊断记录版本、环境、启动/界面/管线/首次渲染耗时及错误摘要,后台限量重试、云端去重并保留30天,不发送素材、LUT、预设、账号或硬件 UUID。暂未加入登录、授权及业务加密模块。
+主 APP 保留深色介绍、置顶发布地址和自动注册;1.18.0 起保持后台运行,关闭窗口不退出,菜单栏可重新打开或退出;加入启动自动检查公测更新和可关闭的云端诊断。更新使用完整 PKG,由用户确认下载并通过完整性、签名与产品校验后打开系统安装器;安装前要求保存并退出 FCP/Motion。诊断记录版本、环境、启动/界面/管线/首次渲染耗时及错误摘要,后台限量重试、云端去重并保留30天,不发送素材、LUT、预设、账号或硬件 UUID。暂未加入登录、授权及业务加密模块。
[1.7.0站点公测安装包](https://dayu.media/wp-content/uploads/dayu-color-beta/updates/dayu-color-1-7-0-45.pkg)、[1.7.0 Release](https://dayu.media/git/dayu/dayu-color/releases/tag/v1.7.0-beta-20261102)、[日志管理页](https://dayu.media/wp-admin/tools.php?page=dayu-color-beta)(管理员)。反馈可附主 APP 的报告标识与发生时间。详见[公测前后端与隐私/恢复说明](Backend/README.md)、[1.7.0发行说明](Packaging/Release-1.7.0.md)和[正式宿主/日志验证](verification/BetaClientQA.json)。本轮保留既有调色与宿主回调逻辑,收集偶发卡死证据,尚未宣称解决该问题。
diff --git a/research/CloudDiagnostics1.18.0.md b/research/CloudDiagnostics1.18.0.md
index a3f0e0d..f3088fa 100644
--- a/research/CloudDiagnostics1.18.0.md
+++ b/research/CloudDiagnostics1.18.0.md
@@ -18,3 +18,5 @@
取消主 APP 注册后倒计时退出,关闭窗口后保留后台运行,提供重新打开与明确退出入口。补充持续扫描自身 APP/插件系统报告、崩溃实际版本与 build、异常终止类别、镜像 UUID/偏移;卡顿使用公共运行循环探针、限频调用栈摘要与资源统计;渲染与跟踪持续阶段、慢操作摘要,避免每帧磁盘和网络发送。现有诊断开关及 30 天保留不变,不上传素材、LUT、预设、账号和原始诊断文件。
验证与交付结果待实现后追加。卡顿具体根因和 dyld 历史报告仍待新版本现场数据。
+
+数据结构依据:[Apple IPS JSON 说明](https://developer.apple.com/documentation/xcode/interpreting-the-json-format-of-a-crash-report);运行循环依据:[CFRunLoop](https://developer.apple.com/documentation/corefoundation/cfrunloop)。
diff --git a/tools/verify_beta.mm b/tools/verify_beta.mm
index 4489003..a2f9b3c 100644
--- a/tools/verify_beta.mm
+++ b/tools/verify_beta.mm
@@ -32,6 +32,30 @@ int main(int argc,char **argv){@autoreleasepool{
NSDictionary *safe=DYBetaSafeFields(@{@"phase":@"end",@"frames":@"/Users/test/secret.mov",@"error_domain":@"token=secret",@"email":@"private@example.invalid",@"duration_ms":@(NAN)});
check([safe[@"frames"]isEqual:@"[REDACTED]"]&&[safe[@"error_domain"]isEqual:@"[REDACTED]"]&&!safe[@"email"]&&!safe[@"duration_ms"],@"privacy allowlist and redaction");
check(DYBetaSafeFields((id)@[]).count==0,@"bad fields do not crash");
+ NSDictionary *header=@{@"bundleID":@"com.dayu.color.XPC",@"app_version":@"1.10.0",@"build_version":@"72",@"timestamp":@"2026-11-05 10:00:00 +0800"};
+ NSDictionary *body=@{@"faultingThread":@0,@"pid":@123,@"exception":@{@"type":@"EXC_BAD_ACCESS",@"signal":@"SIGSEGV"},
+ @"termination":@{@"namespace":@"DYLD",@"code":@1,@"details":@[@"Library not loaded: /Users/private/movie.mov"]},
+ @"usedImages":@[@{@"name":@"大鱼调色 XPC Service",@"uuid":@"12345678-1234-4234-8234-123456789012",@"path":@"/Users/private/test.app"}],
+ @"threads":@[@{@"frames":@[@{@"imageIndex":@0,@"imageOffset":@456},@{@"symbol":@"DYRenderer",@"imageIndex":@0,@"imageOffset":@789}]}]};
+ NSDictionary *evidence=DYBetaCrashEvidence(header,body);
+ check([evidence[@"source_version"]isEqual:@"1.10.0"]&&[evidence[@"source_build"]isEqual:@"72"],@"crashed version independent from uploader");
+ check([evidence[@"frames"]containsString:@"456"]&&[evidence[@"frames"]containsString:@"12345678-1234-4234-8234-123456789012"],@"unsymbolicated frames preserve UUID and offset");
+ check([evidence[@"status"]isEqual:@"library_missing"]&&![[evidence description]containsString:@"private"],@"dyld classification without user paths");
+ check(DYBetaCrashEvidence(@{@"bundleID":@"com.apple.FinalCut"},body)==nil,@"no collection from unrelated host");
+ NSMutableDictionary *dev=[[body mutableCopy]autorelease];dev[@"threads"]=@[@{@"frames":@[@{@"symbol":@"DYRunDiagnostics"}]}];
+ check(DYBetaCrashEvidence(header,dev)==nil,@"development crashes excluded");
+ dev[@"threads"]=@[@{@"frames":@[@{@"symbol":@"__asan_report_load8"}]}];check(DYBetaCrashEvidence(header,dev)==nil,@"sanitizer crashes excluded");
+ check(DYBetaCrashEvidence((id)@[],(id)@[])==nil,@"malformed report safely rejected");
+ NSString *sample=@"Path: /Users/private/sample.app\nCall graph:\n 10 Thread_1 DispatchQueue_1: com.apple.main-thread\n + 10 _dispatch_semaphore_wait_slow (in libdispatch.dylib) + 4 [0x1234]\n + 10 private (in /Users/private/secret)\n 10 Thread_2\n + 10 DYRenderer (in 大鱼调色 XPC Service) + 32 [0x1234]\nBinary Images:\n/Users/private/media.mov";
+ NSString *sampleFrames=DYBetaSampleFrames(sample);
+ check([sampleFrames containsString:@"_dispatch_semaphore_wait_slow"]&&[sampleFrames containsString:@"DYRenderer"]&&![sampleFrames containsString:@"private"],@"sample extracts call graph only");
+ check(DYBetaSampleFrames(@"sampling denied").length==0,@"unavailable sampling stays explicit");
+ NSError *missing=[NSError errorWithDomain:NSCocoaErrorDomain code:260 userInfo:@{NSFilePathErrorKey:@"/Users/private/look.cube"}];
+ NSDictionary *errorFields=DYBetaErrorFields(missing,@"render_source");
+ check([errorFields[@"resource_kind"]isEqual:@"cube"]&&![[errorFields description]containsString:@"private"],@"missing LUT classified without filename");
+ double started=NSProcessInfo.processInfo.systemUptime;
+ for(int i=0;i<10000;i++)DYBetaSpanEnd(DYBetaSpanBegin(@"render",nil),nil);
+ check(NSProcessInfo.processInfo.systemUptime-started<1,@"disabled test process avoids per-frame work and transport");
if(argc==3){NSData *data=[NSData dataWithContentsOfFile:[NSString stringWithUTF8String:argv[2]]];NSDictionary *real=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];NSError *error=nil;
BOOL verified=[DYBetaUpdater validatePackage:[NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]]] manifest:real error:&error];
if(!verified)fprintf(stderr,"%s\n",error.localizedDescription.UTF8String);check(verified,@"signed notarized full product package");
diff --git a/verification/Diagnostics1.18.0.json b/verification/Diagnostics1.18.0.json
new file mode 100644
index 0000000..f7da2b8
--- /dev/null
+++ b/verification/Diagnostics1.18.0.json
@@ -0,0 +1,17 @@
+{
+ "version": "1.18.0",
+ "build": 104,
+ "offlineClientChecks": 75,
+ "backendContractChecks": 27,
+ "appSyntax": "passed",
+ "productionBaselineSHA256": "d2b73816e871765bc2f7d1604a1beda98b99e2d9ac4f62039de7bf3a81107593",
+ "scope": [
+ "crash original version/build",
+ "unsymbolicated UUID and offset",
+ "development crash exclusion",
+ "sample stack-only privacy",
+ "resource category without filename",
+ "new server allowlist"
+ ],
+ "formalRuntimeValidation": "pending"
+}
diff --git a/大鱼调色/Plugin/DYPlugIn.mm b/大鱼调色/Plugin/DYPlugIn.mm
index 1c70824..cd40feb 100644
--- a/大鱼调色/Plugin/DYPlugIn.mm
+++ b/大鱼调色/Plugin/DYPlugIn.mm
@@ -41,12 +41,14 @@
// remote parameter read and view rebuild for every scalar in the burst.
if(!_modelRefreshPending.exchange(true)){id host=_apiManager;dispatch_async(dispatch_get_main_queue(),^{self->_modelRefreshPending.store(false);[NSNotificationCenter.defaultCenter postNotificationName:DYModelChanged object:host];});}return YES;}
- (BOOL)pluginState:(NSData**)state atTime:(CMTime)t quality:(FxQuality)q error:(NSError**)e{
+ uint64_t stateSpan=DYBetaSpanBegin(@"plugin_state",nil);@try{
DYUniforms u;DYReadUniforms(_apiManager,t,&u);CMTime frameDuration=kCMTimeInvalid,origin=kCMTimeZero;idtiming=[_apiManager apiForProtocol:@protocol(FxTimingAPI_v4)];if([timing respondsToSelector:@selector(frameDuration:)])[timing frameDuration:&frameDuration];if([timing respondsToSelector:@selector(startTimeForEffect:)])[timing startTimeForEffect:&origin];int64_t frame=DYFilmFrameIndex(t,frameDuration,origin);u.filmFrameKey=DYFilmFrameKey(frame,u.film.grainHold,u.film.grainSeed);DYAssetState*a=DYReadAssets(_apiManager,t);DYToolDocument *tools=DYReadTools(_apiManager,t);[self adoptToolCanvasDocument:tools.document];[_viewerParameterBridge publishUniforms:&u document:tools.document atTime:t];[_viewerParameterBridge publishAssets:a atTime:t];double copyAuto=0;[[_apiManager apiForProtocol:@protocol(FxParameterRetrievalAPI_v6)]getFloatValue:©Auto fromParameter:8800 atTime:t];NSDictionary *snapshot=DYToolRenderSnapshot(tools.document,t);for(NSMutableDictionary *node in snapshot[@"layers"])if([node[@"type"]isEqual:@"film"]){DYUniforms layer=DYToolUniforms(node);node[@"filmFrameKey"]=@(DYFilmFrameKey(frame,layer.film.grainHold,layer.film.grainSeed));}NSInteger primaries=-1;idgamut=[_apiManager apiForProtocol:@protocol(FxColorGamutAPI_v2)];if([gamut respondsToSelector:@selector(colorPrimaries)])primaries=gamut.colorPrimaries;NSDictionary*s=@{@"colorManagement":a.colorManagement?:@{},@"hostPrimaries":@(primaries),@"schema":@2,@"tools":snapshot,@"copyAuto":@(copyAuto>.5),@"uniforms":[NSData dataWithBytes:&u length:sizeof(u)],@"paths":a.paths?:@{},@"spider":a.spiderMesh?:[NSData data]};*state=[NSPropertyListSerialization dataWithPropertyList:s format:NSPropertyListBinaryFormat_v1_0 options:0 error:e];return *state!=nil;
+ }@finally{DYBetaSpanEnd(stateSpan,nil);}
}
- (BOOL)destinationImageRect:(FxRect*)rect sourceImages:(NSArray*)src destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(!src.count)return NO;*rect=src[0].imagePixelBounds;return YES;}
- (BOOL)sourceTileRect:(FxRect*)rect sourceImageIndex:(NSUInteger)i sourceImages:(NSArray*)src destinationTileRect:(FxRect)dstRect destinationImage:(FxImageTile*)dst pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{if(i>=src.count)return NO;*rect=src[i].imagePixelBounds;return YES;}
- (BOOL)renderDestinationImage:(FxImageTile*)dst sourceImages:(NSArray*)src pluginState:(NSData*)s atTime:(CMTime)t error:(NSError**)e{
- if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] colorManagement:p[@"colorManagement"] hostPrimaries:p[@"hostPrimaries"]?[p[@"hostPrimaries"]integerValue]:-1 error:e];DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",@{@"error_domain":(e&&*e)?(*e).domain:@"unknown",@"error_code":@((e&&*e)?(*e).code:0)});if(ok){[_renderer captureScopeTile:dst atTime:t];@synchronized(self){
+ if(!src.count||!src[0].ioSurface||!dst.ioSurface||!s.length)return NO;NSDictionary*p=[NSPropertyListSerialization propertyListWithData:s options:NSPropertyListImmutable format:NULL error:e];if(![p isKindOfClass:NSDictionary.class])return NO;NSData*b=p[@"uniforms"];if(![@[@1,@2]containsObject:p[@"schema"]]||![b isKindOfClass:NSData.class]||b.length!=sizeof(DYUniforms)||![p[@"paths"]isKindOfClass:NSDictionary.class])return NO;DYUniforms u;[b getBytes:&u length:sizeof(u)];uint64_t renderSpan=DYBetaSpanBegin(@"render",@{@"width":@(IOSurfaceGetWidth(src[0].ioSurface)),@"height":@(IOSurfaceGetHeight(src[0].ioSurface)),@"layer_count":@([p[@"tools"][@"layers"]count])});uint64_t beta=!_betaFirstRenderStarted.exchange(true)?DYBetaSpanBegin(@"first_render",nil):0;BOOL ok=NO;@try{ok=[_renderer renderSource:src[0] destination:dst uniforms:u paths:p[@"paths"] spider:p[@"spider"] tools:p[@"tools"] colorManagement:p[@"colorManagement"] hostPrimaries:p[@"hostPrimaries"]?[p[@"hostPrimaries"]integerValue]:-1 error:e];}@finally{DYBetaSpanEnd(renderSpan,@{@"status":ok?@"passed":@"failed"});}DYBetaSpanEnd(beta,@{@"status":ok?@"passed":@"failed"});if(!ok)DYBetaEvent(@"render_error",DYBetaErrorFields((e&&*e)?*e:nil,@"render_source"));if(ok){[_renderer captureScopeTile:dst atTime:t];@synchronized(self){
FxRect image=src[0].imagePixelBounds;
double aspect=src[0].pixelAspect,height=image.top-image.bottom,width=image.right-image.left;
_toolSourceAspect=width>0&&height>0&&std::isfinite(aspect)&&aspect>0?width*aspect/height:0;
diff --git a/大鱼调色/Plugin/DYToolHostMethods.inc.h b/大鱼调色/Plugin/DYToolHostMethods.inc.h
index b8f3426..69148a0 100644
--- a/大鱼调色/Plugin/DYToolHostMethods.inc.h
+++ b/大鱼调色/Plugin/DYToolHostMethods.inc.h
@@ -232,7 +232,7 @@
return [self finishToolAnalysis:[NSString stringWithFormat:@"%@,已保留 %lu 帧可信轨迹;可调整区域后从此处继续",detail,(unsigned long)_trackingSamples.count] error:error];
}
- (BOOL)analyzeFrame:(FxImageTile*)tile atTime:(CMTime)time error:(NSError**)error {
- if(!_trackingActive.load()||_trackingFinishing.load()){if(error)*error=[NSError errorWithDomain:FxPlugErrorDomain code:kFxError_UserCancelled userInfo:nil];return NO;}_trackingInFrame.store(true);@try{
+ if(!_trackingActive.load()||_trackingFinishing.load()){if(error)*error=[NSError errorWithDomain:FxPlugErrorDomain code:kFxError_UserCancelled userInfo:nil];return NO;}_trackingInFrame.store(true);uint64_t trackingSpan=DYBetaSpanBegin(@"tracking_frame",nil);@try{
if(_trackingCancelled.load())return [self finishToolAnalysis:@"已取消;保留最后连续可信轨迹" error:error];if(_trackingSingle&&_trackingSamples.count>=2)return [self finishToolAnalysis:nil error:error];if(_trackingSamples.count>=DYToolKeyLimit)return [self finishToolAnalysis:@"轨迹已到数量上限,保留已完成部分" error:error];
CMTime expected=CMTIME_IS_NUMERIC(_trackingPreviousTime)?(_trackingBackward?CMTimeSubtract(_trackingPreviousTime,_trackingFrameDuration):CMTimeAdd(_trackingPreviousTime,_trackingFrameDuration)):_trackingReferenceTime;if(!CMTIME_IS_NUMERIC(time)||time.epoch!=expected.epoch||CMTimeCompare(time,expected)!=0)return [self stopToolAnalysis:@"宿主帧序列不连续,停在最后可信帧" error:error];
NSDictionary *preview=nil;
@@ -302,7 +302,7 @@
if(stamp)os_log(OS_LOG_DEFAULT,"dayu_stamp_track_pair time=%{public}.6f target=%{public}.5f,%{public}.5f source=%{public}.5f,%{public}.5f target_scale=%{public}.4f,%{public}.4f source_scale=%{public}.4f,%{public}.4f",CMTimeGetSeconds(time),target.cx,target.cy,source.cx,source.cy,motion.targetScaleX,motion.targetScaleY,motion.sourceScaleX,motion.sourceScaleY);
}
return YES;
- }@finally{_trackingInFrame.store(false);}
+ }@finally{DYBetaSpanEnd(trackingSpan,nil);_trackingInFrame.store(false);}
}
- (BOOL)cleanupAnalysis:(NSError**)error {
if(!_trackingActive.load()||_trackingFinishing.exchange(true))return YES;BOOL changed=_trackingSamples.count>1;if(changed&&!DYMergeTracking(_trackingCandidate,_trackingSamples,_trackingFrameDuration)){[_trackingMessage release];_trackingMessage=[@"轨迹合并失败,原蒙版已保留" copy];_trackingDiscard=YES;}
diff --git a/大鱼调色/Plugin/Info.plist b/大鱼调色/Plugin/Info.plist
index f4051be..2d72628 100644
--- a/大鱼调色/Plugin/Info.plist
+++ b/大鱼调色/Plugin/Info.plist
@@ -17,9 +17,9 @@
CFBundlePackageType
XPC!
CFBundleShortVersionString
- 1.17.1
+ 1.18.0
CFBundleVersion
- 103
+ 104
NSHumanReadableCopyright
PlugInKit
@@ -71,7 +71,7 @@
uuid
1C17B73B-F229-4C09-A434-EAF6DFF5F22A
version
- 1.17.1
+ 1.18.0
className
diff --git a/大鱼调色/Shared/DYBetaDiagnostics.h b/大鱼调色/Shared/DYBetaDiagnostics.h
index b50504c..9d0a16a 100644
--- a/大鱼调色/Shared/DYBetaDiagnostics.h
+++ b/大鱼调色/Shared/DYBetaDiagnostics.h
@@ -13,3 +13,7 @@ FOUNDATION_EXPORT void DYBetaSetEnabled(BOOL enabled);
FOUNDATION_EXPORT NSDictionary *DYBetaStatus(void);
FOUNDATION_EXPORT void DYBetaSendSummary(void);
FOUNDATION_EXPORT BOOL DYBetaAllowedURL(NSURL *url, BOOL download);
+// Pure evidence parsing also used by offline regression checks; never transmits input.
+FOUNDATION_EXPORT NSDictionary *DYBetaCrashEvidence(NSDictionary *header, NSDictionary *body);
+FOUNDATION_EXPORT NSString *DYBetaSampleFrames(NSString *sample);
+FOUNDATION_EXPORT NSDictionary *DYBetaErrorFields(NSError *error, NSString *stage);
diff --git a/大鱼调色/Shared/DYBetaDiagnostics.mm b/大鱼调色/Shared/DYBetaDiagnostics.mm
index fd8bc54..5d0257c 100644
--- a/大鱼调色/Shared/DYBetaDiagnostics.mm
+++ b/大鱼调色/Shared/DYBetaDiagnostics.mm
@@ -7,6 +7,8 @@
#include
#include
#include
+#include
+#include
NSString *const DYBetaDiagnosticsChanged = @"DYBetaDiagnosticsChanged";
static NSString *const DYBetaPreferenceDomain = @"com.dayu.color.preferences";
@@ -14,7 +16,8 @@ static std::atomic_bool gEnabled(true);
static std::atomic_uint_fast64_t gSpan(0);
static std::atomic gMainReply(0);
static NSObject *gSpanLock, *gStatusLock;
-static NSMutableDictionary *gActive;
+static NSMutableDictionary *gActive, *gMetrics;
+static void mainPulse(CFRunLoopTimerRef timer,void *context){gMainReply.store(NSProcessInfo.processInfo.systemUptime);}
static NSDictionary *gStatus;
static BOOL gProduct;
@@ -26,7 +29,7 @@ BOOL DYBetaAllowedURL(NSURL *url, BOOL download) {
}
NSDictionary *DYBetaSafeFields(NSDictionary *fields) {
static NSSet *allowed; static dispatch_once_t once;
- dispatch_once(&once,^{allowed=[[NSSet alloc]initWithArray:@[@"phase",@"stage",@"pipeline",@"duration_ms",@"status",@"error_domain",@"error_code",@"exception",@"signal",@"frames",@"report_time",@"count",@"pending",@"model",@"os_version",@"fcp_version",@"cpu_cores",@"memory_gb",@"gpu",@"main_delay_ms",@"active_stages",@"source_version"]];});
+ dispatch_once(&once,^{allowed=[[NSSet alloc]initWithArray:@[@"phase",@"stage",@"pipeline",@"duration_ms",@"status",@"error_domain",@"error_code",@"exception",@"signal",@"frames",@"report_time",@"count",@"pending",@"model",@"os_version",@"fcp_version",@"cpu_cores",@"memory_gb",@"gpu",@"main_delay_ms",@"active_stages",@"source_version",@"source_build",@"process_role",@"termination_namespace",@"termination_code",@"pid",@"resource_kind",@"memory_mb",@"cpu_percent",@"thread_count",@"uptime_s",@"max_duration_ms",@"average_ms",@"width",@"height",@"layer_count",@"mask_count",@"sample_status"]];});
NSMutableDictionary *out=[NSMutableDictionary dictionary];
if(![fields isKindOfClass:NSDictionary.class])return @{};
for (NSString *key in fields) {
@@ -43,9 +46,11 @@ NSDictionary *DYBetaSafeFields(NSDictionary *fields) {
return out;
}
+#include "DYBetaEvidence.inc.h"
+
@interface DYBetaTransport : NSObject {
@public
- dispatch_queue_t queue;
+ dispatch_queue_t queue, evidenceQueue;
dispatch_source_t timer;
NSMutableArray *pending;
NSMutableSet *seenCrashes;
@@ -56,13 +61,18 @@ NSDictionary *DYBetaSafeFields(NSDictionary *fields) {
NSNumber *build;
NSURL *folder, *journal;
NSDictionary *environment;
- NSTimeInterval nextAttempt, lastTick, lastStall;
+ NSTimeInterval nextAttempt, lastTick, lastStall, lastMaintenance, lastSample, sampleWindow, previousCPU, previousResourceTime, startedAt;
+ NSUInteger sampleCount;
+ BOOL sampling;
BOOL ready;
}
- (void)enqueue:(NSString *)event fields:(NSDictionary *)fields;
- (void)drain;
- (void)persist;
- (void)scanCrashSummaries;
+- (NSUInteger)recoverPending;
+- (NSDictionary *)resources:(double)now;
+- (void)captureSample:(NSString *)stage;
@end
static DYBetaTransport *transport;
static void publishStatus(NSDictionary *values) {
@@ -79,6 +89,8 @@ static NSString *sysctlString(const char *key) {
- (instancetype)init {
if((self=[super init])) {
queue=dispatch_queue_create("com.dayu.color.beta-diagnostics",DISPATCH_QUEUE_SERIAL);
+ evidenceQueue=dispatch_queue_create("com.dayu.color.beta-evidence",DISPATCH_QUEUE_SERIAL);
+ dispatch_set_target_queue(evidenceQueue,dispatch_get_global_queue(QOS_CLASS_UTILITY,0));
pending=[NSMutableArray new];seenCrashes=[NSMutableSet new];lastEvents=[NSMutableDictionary new];sessionID=[NSUUID.UUID.UUIDString.lowercaseString copy];
source=[([NSBundle.mainBundle.bundleIdentifier isEqual:@"com.dayu.color.XPC"]?@"plugin":@"app")copy];
version=[[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]copy];build=@([[NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"]integerValue]);[build retain];
@@ -108,12 +120,25 @@ static NSString *sysctlString(const char *key) {
for(NSString *ID in @[@"com.apple.FinalCut",@"com.apple.FinalCutApp"]){NSURL *url=[NSWorkspace.sharedWorkspace URLForApplicationWithBundleIdentifier:ID];if(url){fcp=[[NSBundle bundleWithURL:url]objectForInfoDictionaryKey:@"CFBundleShortVersionString"]?:@"unknown";break;}}
environment=[@{@"model":sysctlString("hw.model"),@"os_version":NSProcessInfo.processInfo.operatingSystemVersionString,@"fcp_version":fcp,@"cpu_cores":@(NSProcessInfo.processInfo.processorCount),@"memory_gb":@(double(memory)/(1024*1024*1024))}copy];
journal=[[folder URLByAppendingPathComponent:[NSString stringWithFormat:@"pending-%d-%@.json",getpid(),sessionID]]retain];
+ NSArray *seen=[NSArray arrayWithContentsOfURL:[folder URLByAppendingPathComponent:@"seen-crashes.plist"]];
+ for(id key in seen)if([key isKindOfClass:NSString.class]&&[[[NSUUID alloc]initWithUUIDString:key]autorelease])[seenCrashes addObject:key];
+ NSUInteger recovered=[self recoverPending];
+ ready=YES;gMainReply.store(NSProcessInfo.processInfo.systemUptime);lastTick=gMainReply.load();startedAt=lastTick;
+ NSMutableDictionary *start=[[environment mutableCopy]autorelease];start[@"pid"]=@(getpid());[self enqueue:@"process_start" fields:start];if(recovered)[self enqueue:@"previous_session_pending" fields:@{@"count":@(recovered)}];
+ publishStatus(@{@"installation_id":installationID,@"enabled":@(gEnabled.load()),@"pending":@(pending.count)});
+ timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
+ dispatch_source_set_timer(timer,dispatch_time(DISPATCH_TIME_NOW,2*NSEC_PER_SEC),3*NSEC_PER_SEC,NSEC_PER_SEC/4);
+ dispatch_source_set_event_handler(timer,^{@autoreleasepool{[self tick];}});dispatch_resume(timer);
+ [NSDistributedNotificationCenter.defaultCenter addObserver:self selector:@selector(settingsChanged:) name:@"com.dayu.color.beta.preferences" object:nil];
+ if([source isEqual:@"app"])[self scanCrashSummaries];
+}
+- (NSUInteger)recoverPending {
NSArray *files=[NSFileManager.defaultManager contentsOfDirectoryAtURL:folder includingPropertiesForKeys:@[NSURLContentModificationDateKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
NSUInteger recovered=0;
for(NSURL *url in files){if(![url.lastPathComponent hasPrefix:@"pending-"]||![url.pathExtension isEqual:@"json"])continue;
NSNumber *bytes=nil;[url getResourceValue:&bytes forKey:NSURLFileSizeKey error:nil];if(bytes.unsignedLongLongValue>384*1024)continue;
NSDictionary *old=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:url]?:[NSData data] options:0 error:nil];if(![old isKindOfClass:NSDictionary.class])continue;
- if(![old[@"pid"]isKindOfClass:NSNumber.class])continue;int pid=[old[@"pid"]intValue];if(pid>0&&kill(pid,0)==0)continue;
+ if(![old[@"pid"]isKindOfClass:NSNumber.class])continue;int pid=[old[@"pid"]intValue];if(pid==getpid()||pid<=0||kill(pid,0)==0||errno!=ESRCH)continue;
NSDate *date=nil;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];
if(gEnabled.load()&&date.timeIntervalSinceNow> -7*86400&&[old[@"events"]isKindOfClass:NSArray.class])for(NSDictionary *event in old[@"events"]){if(pending.count>=256)break;
if(![event isKindOfClass:NSDictionary.class]||![event[@"event_id"]isKindOfClass:NSString.class]||![event[@"session_id"]isKindOfClass:NSString.class]||
@@ -123,36 +148,32 @@ static NSString *sysctlString(const char *key) {
NSMutableDictionary *safe=[[event mutableCopy]autorelease];safe[@"fields"]=DYBetaSafeFields(event[@"fields"]);[pending addObject:safe];recovered++;}
[NSFileManager.defaultManager removeItemAtURL:url error:nil];
}
- ready=YES;gMainReply.store(NSProcessInfo.processInfo.systemUptime);lastTick=gMainReply.load();
- [self enqueue:@"process_start" fields:environment];if(recovered)[self enqueue:@"previous_session_pending" fields:@{@"count":@(recovered)}];
- publishStatus(@{@"installation_id":installationID,@"enabled":@(gEnabled.load()),@"pending":@(pending.count)});
- timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
- dispatch_source_set_timer(timer,dispatch_time(DISPATCH_TIME_NOW,2*NSEC_PER_SEC),3*NSEC_PER_SEC,NSEC_PER_SEC/4);
- dispatch_source_set_event_handler(timer,^{@autoreleasepool{[self tick];}});dispatch_resume(timer);
- [NSDistributedNotificationCenter.defaultCenter addObserver:self selector:@selector(settingsChanged:) name:@"com.dayu.color.beta.preferences" object:nil];
- if([source isEqual:@"app"])[self scanCrashSummaries];
+ return recovered;
}
- (void)enqueue:(NSString *)event fields:(NSDictionary *)fields {
if(!ready||!gEnabled.load())return;
// A bad render must not turn diagnostics into per-frame disk writes.
- if([@[@"render_error",@"inspector_refresh"]containsObject:event]){
- double now=NSProcessInfo.processInfo.systemUptime;if(now-[lastEvents[event]doubleValue]<5)return;lastEvents[event]=@(now);
+ if([@[@"render_error",@"inspector_refresh",@"render",@"plugin_state",@"tracking_frame"]containsObject:event]){
+ double now=NSProcessInfo.processInfo.systemUptime;if(now-[lastEvents[event]doubleValue]<([event isEqual:@"render_error"]?5:30))return;lastEvents[event]=@(now);
}
if(pending.count>=256)[pending removeObjectsInRange:NSMakeRange(0,32)];
- [pending addObject:@{@"event_id":NSUUID.UUID.UUIDString.lowercaseString,@"session_id":sessionID,@"source":source,@"version":version?:@"0.0",@"build":build?:@1,@"event":event,@"occurred_at":@(NSDate.date.timeIntervalSince1970),@"fields":DYBetaSafeFields(fields?:@{})}];
+ NSMutableDictionary *context=[[DYBetaSafeFields(fields?:@{})mutableCopy]autorelease];if(!context[@"pid"])context[@"pid"]=@(getpid());
+ if([NSProcessInfo.processInfo.arguments containsObject:@"--diagnostics-probe"])context[@"phase"]=@"verification";
+ [pending addObject:@{@"event_id":NSUUID.UUID.UUIDString.lowercaseString,@"session_id":sessionID,@"source":source,@"version":version?:@"0.0",@"build":build?:@1,@"event":event,@"occurred_at":@(NSDate.date.timeIntervalSince1970),@"fields":context}];
[self persist];
}
- (void)persist {
if(!journal)return;
NSData *data=[NSJSONSerialization dataWithJSONObject:@{@"pid":@(getpid()),@"events":pending} options:0 error:nil];
- if(data.length>384*1024){while(pending.count>64)[pending removeObjectAtIndex:0];data=[NSJSONSerialization dataWithJSONObject:@{@"pid":@(getpid()),@"events":pending} options:0 error:nil];}
+ while(data.length>384*1024&&pending.count>1){[pending removeObjectAtIndex:0];data=[NSJSONSerialization dataWithJSONObject:@{@"pid":@(getpid()),@"events":pending} options:0 error:nil];}
[data writeToURL:journal options:NSDataWritingAtomic error:nil];chmod(journal.fileSystemRepresentation,0600);
}
- (void)drain {
if(!ready||!gEnabled.load()||sending||!pending.count||NSDate.date.timeIntervalSince197098304){[pending removeObjectAtIndex:0];[batch release];[self persist];return;}
+ while(data.length>98304&&batch.count>1){NSArray *smaller=[[batch subarrayWithRange:NSMakeRange(0,batch.count-1)]copy];[batch release];batch=smaller;data=[NSJSONSerialization dataWithJSONObject:@{@"bundle_id":@"com.dayu.color",@"installation_id":installationID,@"events":batch} options:0 error:nil];}
+ if(!data||data.length>98304){[pending removeObjectAtIndex:0];[batch release];[self persist];return;}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://dayu.media/wp-json/dayu-color/v1/diagnostics"]];request.HTTPMethod=@"POST";request.HTTPBody=data;[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
sending=[[session dataTaskWithRequest:request completionHandler:^(NSData *body,NSURLResponse *response,NSError *error){
dispatch_async(self->queue,^{@autoreleasepool{
@@ -160,20 +181,65 @@ static NSString *sysctlString(const char *key) {
NSSet *accepted=[reply[@"event_ids"]isKindOfClass:NSArray.class]?[NSSet setWithArray:reply[@"event_ids"]]:[NSSet set];
NSSet *expected=[NSSet setWithArray:[batch valueForKey:@"event_id"]];
BOOL ok=!error&&[(NSHTTPURLResponse*)response statusCode]==200&&[reply[@"accepted"]isKindOfClass:NSNumber.class]&&[reply[@"accepted"]boolValue]&&[accepted isEqualToSet:expected];
- if(ok){NSIndexSet *remove=[self->pending indexesOfObjectsPassingTest:^BOOL(NSDictionary *event,NSUInteger i,BOOL *stop){return [accepted containsObject:event[@"event_id"]];}];[self->pending removeObjectsAtIndexes:remove];self->nextAttempt=0;
+ if(ok){
+ BOOL acknowledgedCrash=NO;
+ for(NSDictionary *event in batch)if([event[@"event"]isEqual:@"crash_summary"]){[self->seenCrashes addObject:event[@"event_id"]];acknowledgedCrash=YES;}
+ if(acknowledgedCrash){NSArray *seen=self->seenCrashes.allObjects;if(seen.count>1024){seen=[seen subarrayWithRange:NSMakeRange(seen.count-1024,1024)];[self->seenCrashes setSet:[NSSet setWithArray:seen]];}
+ NSURL *seenURL=[self->folder URLByAppendingPathComponent:@"seen-crashes.plist"];[seen writeToURL:seenURL atomically:YES];chmod(seenURL.fileSystemRepresentation,0600);}
+ NSIndexSet *remove=[self->pending indexesOfObjectsPassingTest:^BOOL(NSDictionary *event,NSUInteger i,BOOL *stop){return [accepted containsObject:event[@"event_id"]];}];[self->pending removeObjectsAtIndexes:remove];self->nextAttempt=0;
publishStatus(@{@"installation_id":self->installationID,@"enabled":@(gEnabled.load()),@"pending":@(self->pending.count),@"last_upload":@([NSDate.date timeIntervalSince1970])});
}else self->nextAttempt=NSDate.date.timeIntervalSince1970+30;
[self->sending release];self->sending=nil;[batch release];[self persist];
}});
}]retain];[sending resume];
}
+- (NSDictionary *)resources:(double)now {
+ struct proc_taskinfo info={};NSMutableDictionary *result=[NSMutableDictionary dictionaryWithDictionary:@{@"pid":@(getpid()),@"uptime_s":@(now-startedAt)}];
+ if(proc_pidinfo(getpid(),PROC_PIDTASKINFO,0,&info,sizeof(info))==sizeof(info)) {
+ result[@"memory_mb"]=@(double(info.pti_resident_size)/(1024*1024));result[@"thread_count"]=@(info.pti_threadnum);
+ double cpu=(info.pti_total_user+info.pti_total_system)/1e9;
+ if(previousResourceTime>0&&now>previousResourceTime)result[@"cpu_percent"]=@(MAX(0.,(cpu-previousCPU)/(now-previousResourceTime)*100));
+ previousCPU=cpu;previousResourceTime=now;
+ }return result;
+}
+- (void)captureSample:(NSString *)stage {
+ double now=NSProcessInfo.processInfo.systemUptime;
+ if(sampling||now-lastSample<120)return;
+ if(now-sampleWindow>3600){sampleWindow=now;sampleCount=0;}if(sampleCount>=6)return;
+ sampling=YES;lastSample=now;sampleCount++;
+ dispatch_async(evidenceQueue,^{@autoreleasepool{
+ NSURL *output=[self->folder URLByAppendingPathComponent:[@"sample-" stringByAppendingString:NSUUID.UUID.UUIDString]];
+ NSTask *task=[[[NSTask alloc]init]autorelease];task.executableURL=[NSURL fileURLWithPath:@"/usr/bin/sample"];
+ task.arguments=@[[@(getpid())stringValue],@"1",@"10",@"-mayDie",@"-file",output.path];
+ task.standardOutput=[NSFileHandle fileHandleWithNullDevice];task.standardError=[NSFileHandle fileHandleWithNullDevice];
+ NSString *result=@"unavailable",*frames=@"";NSError *error=nil;
+ if(gEnabled.load()&&[task launchAndReturnError:&error]) {
+ double deadline=NSProcessInfo.processInfo.systemUptime+8;
+ while(task.running&&gEnabled.load()&&NSProcessInfo.processInfo.systemUptimequeue,^{@autoreleasepool{self->sampling=NO;[self enqueue:@"hang_sample" fields:@{@"stage":stage,@"sample_status":result,@"frames":frames,@"pid":@(getpid())}];[self drain];}});
+ }});
+}
- (void)tick {
double now=NSProcessInfo.processInfo.systemUptime;
- if(now-lastTick>15)gMainReply.store(now); // Sleep/wake and timer coalescing are not proof of a hang.
- lastTick=now;
- if(gEnabled.load()&&now-gMainReply.load()>6&&now-lastStall>30){lastStall=now;[self enqueue:@"main_thread_stall" fields:@{@"status":@"suspected",@"main_delay_ms":@((now-gMainReply.load())*1000),@"active_stages":[self activeStages:now]}];}
- else if(gEnabled.load()&&now-lastStall>30){NSString *stages=[self activeStages:now];if(stages.length){lastStall=now;[self enqueue:@"operation_stall" fields:@{@"status":@"suspected",@"active_stages":stages}];}}
- dispatch_async(dispatch_get_main_queue(),^{gMainReply.store(NSProcessInfo.processInfo.systemUptime);});
+ BOOL suspended=now-lastTick>15;lastTick=now;
+ if(suspended)gMainReply.store(now); // Sleep/wake or process suspension isn't a measured hang.
+ if(gEnabled.load()) {
+ NSString *stages=[self activeStages:now];double delay=now-gMainReply.load();
+ if((delay>6||stages.length)&&now-lastStall>30){lastStall=now;NSMutableDictionary *fields=[[[self resources:now]mutableCopy]autorelease];
+ fields[@"status"]=@"suspected";fields[@"main_delay_ms"]=@(delay*1000);fields[@"active_stages"]=stages;
+ NSString *event=delay>6?@"main_thread_stall":@"operation_stall";[self enqueue:event fields:fields];[self captureSample:event];
+ }
+ if(now-lastMaintenance>=60){lastMaintenance=now;
+ [self enqueue:@"process_health" fields:[self resources:now]];
+ NSDictionary *metrics;@synchronized(gSpanLock){metrics=[[gMetrics copy]autorelease];[gMetrics removeAllObjects];}
+ for(NSString *stage in metrics){NSMutableDictionary *fields=[[metrics[stage]mutableCopy]autorelease];fields[@"stage"]=stage;fields[@"average_ms"]=@([fields[@"duration_ms"]doubleValue]/MAX(1,[fields[@"count"]integerValue]));[self enqueue:@"performance_summary" fields:fields];}
+ if([source isEqual:@"app"]){NSUInteger recovered=[self recoverPending];if(recovered)[self enqueue:@"previous_session_pending" fields:@{@"count":@(recovered)}];[self scanCrashSummaries];}
+ }
+ }
[self drain];
}
- (NSString *)activeStages:(double)now {
@@ -183,7 +249,7 @@ static NSString *sysctlString(const char *key) {
}
- (void)settingsChanged:(NSNotification *)note {
dispatch_async(queue,^{@autoreleasepool{NSUserDefaults *prefs=preferences();[prefs synchronize];gEnabled.store([prefs objectForKey:@"betaDiagnosticsEnabled"]?[prefs boolForKey:@"betaDiagnosticsEnabled"]:YES);
- if(!gEnabled.load()){[self->sending cancel];[self->pending removeAllObjects];[self persist];}
+ if(!gEnabled.load()){[self->sending cancel];[self->pending removeAllObjects];[self persist];@synchronized(gSpanLock){[gActive removeAllObjects];[gMetrics removeAllObjects];}}
publishStatus(@{@"installation_id":self->installationID?:@"",@"enabled":@(gEnabled.load()),@"pending":@(self->pending.count)});
}});
}
@@ -191,34 +257,44 @@ static NSString *sysctlString(const char *key) {
completionHandler(DYBetaAllowedURL(request.URL,NO)?request:nil);
}
- (void)scanCrashSummaries {
- if(!gEnabled.load())return;
+ if(!gEnabled.load()||![source isEqual:@"app"])return;
NSURL *reports=[NSFileManager.defaultManager.homeDirectoryForCurrentUser URLByAppendingPathComponent:@"Library/Logs/DiagnosticReports"];
NSArray *files=[NSFileManager.defaultManager contentsOfDirectoryAtURL:reports includingPropertiesForKeys:@[NSURLContentModificationDateKey,NSURLFileSizeKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
- NSUInteger count=0;
- for(NSURL *url in files){if(count>=12)break;if(![url.pathExtension isEqual:@"ips"])continue;
+ files=[files sortedArrayUsingComparator:^NSComparisonResult(NSURL *a,NSURL *b){NSDate *ad=nil,*bd=nil;[a getResourceValue:&ad forKey:NSURLContentModificationDateKey error:nil];[b getResourceValue:&bd forKey:NSURLContentModificationDateKey error:nil];return [(bd?:NSDate.distantPast) compare:ad?:NSDate.distantPast];}];
+ NSUInteger count=0,examined=0;
+ NSMutableSet *queued=[NSMutableSet setWithArray:[pending valueForKey:@"event_id"]];
+ for(NSURL *url in files){if(count>=12||examined++>=512||pending.count>=240)break;
+ if(![url.pathExtension isEqual:@"ips"]||![url.lastPathComponent hasPrefix:@"大鱼调色"])continue;
NSNumber *size=nil;[url getResourceValue:&size forKey:NSURLFileSizeKey error:nil];if(size.unsignedLongLongValue>8*1024*1024)continue;
- NSDate *date=nil;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];if(date.timeIntervalSinceNow< -7*86400)continue;
- NSFileHandle *handle=[NSFileHandle fileHandleForReadingFromURL:url error:nil];NSData *head=[handle readDataUpToLength:8192 error:nil];[handle closeFile];
- if(!head.length)continue;NSString *prefix=[[[NSString alloc]initWithData:head encoding:NSUTF8StringEncoding]autorelease];NSRange first=[prefix rangeOfString:@"\n"];if(!prefix||first.location==NSNotFound)continue;
- NSDictionary *header=[NSJSONSerialization JSONObjectWithData:[[prefix substringToIndex:first.location]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];if(![header isKindOfClass:NSDictionary.class]||![header[@"bundleID"]isEqual:@"com.dayu.color.XPC"])continue;
- NSData *data=[NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:nil];if(!data.length)continue;NSString *text=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];NSRange newline=[text rangeOfString:@"\n"];if(!text||newline.location==NSNotFound)continue;
- NSString *key=header[@"incident_id"];if(![key isKindOfClass:NSString.class]||![[[NSUUID alloc]initWithUUIDString:key]autorelease])continue;if([seenCrashes containsObject:key])continue;[seenCrashes addObject:key];
- NSDictionary *body=[NSJSONSerialization JSONObjectWithData:[[text substringFromIndex:newline.location+1]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
- if(![body isKindOfClass:NSDictionary.class])continue;NSDictionary *exception=[body[@"exception"]isKindOfClass:NSDictionary.class]?body[@"exception"]:@{};
- NSInteger fault=[body[@"faultingThread"]isKindOfClass:NSNumber.class]?[body[@"faultingThread"]integerValue]:-1;NSArray *threads=body[@"threads"];NSMutableArray *frames=[NSMutableArray array];
- if([threads isKindOfClass:NSArray.class]&&fault>=0&&fault=30)break;if(![frame isKindOfClass:NSDictionary.class])continue;NSString *symbol=frame[@"symbol"];if([symbol isKindOfClass:NSString.class]&&![symbol containsString:@"/"])[frames addObject:symbol];}
- [self enqueue:@"crash_summary" fields:@{@"source_version":header[@"app_version"]?:@"unknown",@"report_time":header[@"timestamp"]?:@"unknown",@"exception":exception[@"type"]?:@"unknown",@"signal":exception[@"signal"]?:@"unknown",@"frames":[frames componentsJoinedByString:@"\n"]}];
- if(pending.count){NSMutableDictionary *event=[[pending.lastObject mutableCopy]autorelease];event[@"event_id"]=key.lowercaseString;[pending replaceObjectAtIndex:pending.count-1 withObject:event];[self persist];}count++;
+ NSDate *date=nil;[url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil];if(!date||date.timeIntervalSinceNow< -7*86400)continue;
+ NSData *data=[NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:nil];if(!data.length)continue;
+ NSString *text=[[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease];if(!text)continue;
+ NSRange newline=[text rangeOfString:@"\n"];if(newline.location==NSNotFound)continue;
+ NSDictionary *header=DYBetaDictionary([NSJSONSerialization JSONObjectWithData:[[text substringToIndex:newline.location]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]);
+ NSString *key=DYBetaString(header[@"incident_id"]).lowercaseString;
+ if(![[[NSUUID alloc]initWithUUIDString:key]autorelease]||[seenCrashes containsObject:key]||[queued containsObject:key])continue;
+ NSDictionary *body=DYBetaDictionary([NSJSONSerialization JSONObjectWithData:[[text substringFromIndex:newline.location+1]dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]);
+ if(!body.count)continue;NSDictionary *fields=DYBetaCrashEvidence(header,body);if(!fields)continue;
+ NSUInteger before=pending.count;[self enqueue:@"crash_summary" fields:fields];
+ if(pending.count==before+1){NSMutableDictionary *event=[[pending.lastObject mutableCopy]autorelease];event[@"event_id"]=key;[pending replaceObjectAtIndex:pending.count-1 withObject:event];[queued addObject:key];[self persist];count++;}
}
}
+
@end
void DYBetaStart(void) {
static dispatch_once_t once;dispatch_once(&once,^{
NSString *ID=NSBundle.mainBundle.bundleIdentifier;
gProduct=([ID isEqual:@"com.dayu.color"]||[ID isEqual:@"com.dayu.color.XPC"])&&![NSProcessInfo.processInfo.arguments containsObject:@"--self-test"];
- gSpanLock=[NSObject new];gStatusLock=[NSObject new];gActive=[NSMutableDictionary new];
- if(gProduct)transport=[DYBetaTransport new];
+ gSpanLock=[NSObject new];gStatusLock=[NSObject new];gActive=[NSMutableDictionary new];gMetrics=[NSMutableDictionary new];
+ if(gProduct){
+ NSUserDefaults *prefs=preferences();gEnabled.store([prefs objectForKey:@"betaDiagnosticsEnabled"]?[prefs boolForKey:@"betaDiagnosticsEnabled"]:YES);
+ gMainReply.store(NSProcessInfo.processInfo.systemUptime);
+ // Common modes continue to pulse while menus / file panels run nested loops.
+ CFRunLoopTimerRef pulse=CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent()+1,1,0,0,mainPulse,NULL);
+ CFRunLoopAddTimer(CFRunLoopGetMain(),pulse,kCFRunLoopCommonModes);CFRelease(pulse);
+ transport=[DYBetaTransport new];
+ }
});
}
BOOL DYBetaEnabled(void){DYBetaStart();return gEnabled.load();}
@@ -226,8 +302,15 @@ void DYBetaSetEnabled(BOOL enabled){DYBetaStart();gEnabled.store(enabled);NSUser
NSDictionary *DYBetaStatus(void){DYBetaStart();return statusSnapshot();}
void DYBetaEvent(NSString *event,NSDictionary *fields){DYBetaStart();if(!gProduct||!gEnabled.load())return;NSDictionary *safe=DYBetaSafeFields(fields?:@{});dispatch_async(transport->queue,^{@autoreleasepool{[transport enqueue:event fields:safe];}});}
uint64_t DYBetaSpanBegin(NSString *stage,NSDictionary *fields){DYBetaStart();if(!gProduct||!gEnabled.load())return 0;uint64_t token=++gSpan;NSDictionary *value=@{@"stage":stage,@"start":@(NSProcessInfo.processInfo.systemUptime),@"fields":DYBetaSafeFields(fields?:@{})};@synchronized(gSpanLock){if(gActive.count>=128)return 0;gActive[@(token)]=value;}
- if(![stage isEqual:@"inspector_refresh"]){NSMutableDictionary *begin=[[value[@"fields"]mutableCopy]autorelease];begin[@"phase"]=@"begin";DYBetaEvent(stage,begin);}return token;
+ if(![@[@"inspector_refresh",@"render",@"tracking_frame",@"plugin_state"]containsObject:stage]){NSMutableDictionary *begin=[[value[@"fields"]mutableCopy]autorelease];begin[@"phase"]=@"begin";DYBetaEvent(stage,begin);}return token;
}
-void DYBetaSpanEnd(uint64_t token,NSDictionary *fields){if(!token)return;NSDictionary *span;@synchronized(gSpanLock){span=[[gActive[@(token)]retain]autorelease];[gActive removeObjectForKey:@(token)];}if(!span)return;double elapsed=(NSProcessInfo.processInfo.systemUptime-[span[@"start"]doubleValue])*1000;if([span[@"stage"]isEqual:@"inspector_refresh"]&&elapsed<100)return;NSMutableDictionary *result=[[span[@"fields"]mutableCopy]autorelease];[result addEntriesFromDictionary:fields?:@{}];result[@"duration_ms"]=@(elapsed);result[@"phase"]=@"end";DYBetaEvent(span[@"stage"],result);}
-void DYBetaStop(void){DYBetaEvent(@"process_exit",@{@"status":@"normal"});}
+void DYBetaSpanEnd(uint64_t token,NSDictionary *fields){
+ if(!token)return;NSDictionary *span;
+ @synchronized(gSpanLock){span=[[gActive[@(token)]retain]autorelease];[gActive removeObjectForKey:@(token)];}
+ if(!span||!gEnabled.load())return;double elapsed=(NSProcessInfo.processInfo.systemUptime-[span[@"start"]doubleValue])*1000;
+ NSString *stage=span[@"stage"];BOOL frequent=[@[@"inspector_refresh",@"render",@"tracking_frame",@"plugin_state"]containsObject:stage];
+ if(frequent){@synchronized(gSpanLock){NSDictionary *old=gMetrics[stage];gMetrics[stage]=@{@"count":@([old[@"count"]integerValue]+1),@"duration_ms":@([old[@"duration_ms"]doubleValue]+elapsed),@"max_duration_ms":@(MAX([old[@"max_duration_ms"]doubleValue],elapsed))};}if(elapsed<100)return;}
+ NSMutableDictionary *result=[[span[@"fields"]mutableCopy]autorelease];[result addEntriesFromDictionary:fields?:@{}];result[@"duration_ms"]=@(elapsed);result[@"phase"]=@"end";DYBetaEvent(stage,result);
+}
+void DYBetaStop(void){DYBetaStart();if(!gProduct)return;dispatch_group_t group=dispatch_group_create();dispatch_group_async(group,transport->queue,^{@autoreleasepool{[transport enqueue:@"process_exit" fields:@{@"status":@"normal"}];[transport persist];[transport drain];}});dispatch_group_wait(group,dispatch_time(DISPATCH_TIME_NOW,NSEC_PER_SEC/2));dispatch_release(group);}
void DYBetaSendSummary(void){DYBetaStart();if(!gProduct)return;dispatch_async(transport->queue,^{@autoreleasepool{[transport enqueue:@"diagnostic_summary" fields:transport->environment];[transport scanCrashSummaries];[transport drain];}});}
diff --git a/大鱼调色/Shared/DYBetaEvidence.inc.h b/大鱼调色/Shared/DYBetaEvidence.inc.h
new file mode 100644
index 0000000..6efe999
--- /dev/null
+++ b/大鱼调色/Shared/DYBetaEvidence.inc.h
@@ -0,0 +1,78 @@
+// Only structured, product-owned evidence leaves the computer. No raw IPS/sample upload.
+static NSString *DYBetaString(id value) { return [value isKindOfClass:NSString.class]?value:@""; }
+static NSDictionary *DYBetaDictionary(id value) { return [value isKindOfClass:NSDictionary.class]?value:@{}; }
+static NSArray *DYBetaArray(id value) { return [value isKindOfClass:NSArray.class]?value:@[]; }
+static NSString *DYBetaImageName(NSDictionary *image) {
+ NSString *name=DYBetaString(image[@"name"]);
+ if([@[@"大鱼调色",@"大鱼调色 XPC Service",@"FxPlug",@"PluginManager"]containsObject:name])return name;
+ NSString *path=DYBetaString(image[@"path"]);
+ if([path hasPrefix:@"/System/Library/"]||[path hasPrefix:@"/usr/lib/"])return name.lastPathComponent;
+ return @"other-image";
+}
+NSDictionary *DYBetaCrashEvidence(NSDictionary *header,NSDictionary *body) {
+ header=DYBetaDictionary(header);body=DYBetaDictionary(body);
+ NSString *bundle=DYBetaString(header[@"bundleID"]);
+ if(![@[@"com.dayu.color",@"com.dayu.color.XPC"]containsObject:bundle])return nil;
+ NSArray *threads=DYBetaArray(body[@"threads"]),*images=DYBetaArray(body[@"usedImages"]);
+ // Development self-tests must not be presented as users' crashes.
+ for(id t in threads)for(id f in DYBetaArray(DYBetaDictionary(t)[@"frames"])) {
+ NSString *symbol=DYBetaString(DYBetaDictionary(f)[@"symbol"]);
+ if([symbol containsString:@"DYRunDiagnostics"]||[symbol containsString:@"__asan"]||[symbol containsString:@"__sanitizer"])return nil;
+ }
+ NSInteger fault=[body[@"faultingThread"]isKindOfClass:NSNumber.class]?[body[@"faultingThread"]integerValue]:-1;
+ if(fault<0||fault>=threads.count)for(NSUInteger i=0;i=0&&fault=32)break;NSDictionary *frame=DYBetaDictionary(item);
+ NSInteger index=[frame[@"imageIndex"]isKindOfClass:NSNumber.class]?[frame[@"imageIndex"]integerValue]:-1;
+ NSDictionary *image=index>=0&&index300)symbol=[symbol substringToIndex:300];
+ if([symbol containsString:@"/"])symbol=@"[symbol omitted]";
+ [frames addObject:[NSString stringWithFormat:@"%@ | %@ + %@ | %@",symbol.length?symbol:@"unsymbolicated",DYBetaImageName(image),[frame[@"imageOffset"]isKindOfClass:NSNumber.class]?frame[@"imageOffset"]:@0,uuid]];
+ }
+ NSDictionary *exception=DYBetaDictionary(body[@"exception"]),*termination=DYBetaDictionary(body[@"termination"]),*info=DYBetaDictionary(body[@"bundleInfo"]);
+ NSMutableDictionary *out=[@{@"source_version":DYBetaString(header[@"app_version"]).length?header[@"app_version"]:DYBetaString(info[@"CFBundleShortVersionString"]),
+ @"source_build":DYBetaString(header[@"build_version"]).length?header[@"build_version"]:DYBetaString(info[@"CFBundleVersion"]),
+ @"process_role":[bundle hasSuffix:@".XPC"]?@"plugin":@"app",@"report_time":DYBetaString(header[@"timestamp"]),
+ @"exception":DYBetaString(exception[@"type"]),@"signal":DYBetaString(exception[@"signal"]),
+ @"termination_namespace":DYBetaString(termination[@"namespace"]),@"frames":[frames componentsJoinedByString:@"\n"],
+ @"os_version":DYBetaString(DYBetaDictionary(body[@"osVersion"])[@"train"])}mutableCopy];
+ if([termination[@"code"]isKindOfClass:NSNumber.class])out[@"termination_code"]=termination[@"code"];
+ if([body[@"pid"]isKindOfClass:NSNumber.class])out[@"pid"]=body[@"pid"];
+ // Full dyld reason may contain user paths. Retain only a fixed classification.
+ NSString *reason=[[DYBetaArray(termination[@"details"]) description]stringByAppendingString:DYBetaString(termination[@"indicator"])];
+ out[@"status"]=[reason localizedCaseInsensitiveContainsString:@"Library not loaded"]?@"library_missing":
+ [reason localizedCaseInsensitiveContainsString:@"Symbol not found"]?@"symbol_missing":
+ [reason localizedCaseInsensitiveContainsString:@"signature"]?@"signature_rejected":@"system_report";
+ NSDictionary *safe=DYBetaSafeFields(out);[out release];return safe;
+}
+NSString *DYBetaSampleFrames(NSString *sample) {
+ if(![sample isKindOfClass:NSString.class]||sample.length>4*1024*1024)return @"";
+ NSMutableArray *main=[NSMutableArray array],*other=[NSMutableArray array];BOOL graph=NO,mainThread=NO;
+ for(NSString *line in [sample componentsSeparatedByString:@"\n"]) {
+ if([line isEqual:@"Call graph:"]){graph=YES;continue;}
+ if([line hasPrefix:@"Total number in stack"]||[line hasPrefix:@"Binary Images:"])break;
+ if(!graph)continue;
+ if([line containsString:@"Thread_"]){mainThread=[line containsString:@"com.apple.main-thread"];continue;}
+ NSRange marker=[line rangeOfString:@" (in "];if(marker.location==NSNotFound)continue;
+ NSString *frame=[line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
+ if(frame.length>500)frame=[frame substringToIndex:500];
+ if([frame containsString:@"/"])continue;
+ if(mainThread)[main addObject:frame];
+ else if(other.count<25&&([frame containsString:@"DY"]||[frame containsString:@"大鱼调色"]||[frame containsString:@"Metal"]||[frame containsString:@"Vision"]||[frame containsString:@"cv::"]))[other addObject:frame];
+ }
+ // Keep the deepest main-thread frames, which contain the actual wait/work.
+ if(main.count>28)[main removeObjectsInRange:NSMakeRange(0,main.count-28)];
+ NSString *result=[NSString stringWithFormat:@"main:\n%@\nproduct/work:\n%@",[main componentsJoinedByString:@"\n"],[other componentsJoinedByString:@"\n"]];
+ return main.count||other.count?DYBetaSafeFields(@{@"frames":result})[@"frames"]:@"";
+}
+NSDictionary *DYBetaErrorFields(NSError *error,NSString *stage) {
+ NSMutableDictionary *fields=[NSMutableDictionary dictionaryWithDictionary:@{@"stage":stage?:@"unknown",@"error_domain":error.domain?:@"unknown",@"error_code":@(error.code)}];
+ id url=error.userInfo[NSURLErrorKey];NSString *path=[url isKindOfClass:NSURL.class]?[url path]:DYBetaString(error.userInfo[NSFilePathErrorKey]);
+ NSString *ext=path.pathExtension.lowercaseString;
+ if([@[@"cube",@"dylut",@"metallib",@"bin"]containsObject:ext])fields[@"resource_kind"]=ext;
+ else if(path.length)fields[@"resource_kind"]=@"other_file";
+ return fields;
+}
diff --git a/大鱼调色/Wrapper Application/AppDelegate.m b/大鱼调色/Wrapper Application/AppDelegate.m
index 9f9a388..d75afa6 100644
--- a/大鱼调色/Wrapper Application/AppDelegate.m
+++ b/大鱼调色/Wrapper Application/AppDelegate.m
@@ -121,9 +121,8 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
@property(assign) NSProgressIndicator *progress;
@property(assign) DYSurface *registrationCard;
@property DYRegistrationState registrationState;
-@property BOOL keepOpen, terminating;
-@property NSInteger secondsRemaining;
-@property(retain) NSTimer *exitTimer;
+@property BOOL terminating;
+@property(retain) NSStatusItem *statusItem;
@property(retain) NSMutableDictionary *diagnostics;
@property(retain) DYBetaUpdater *updater;
@property(assign) NSTextField *updateTitle, *updateDetail, *diagnosticDetail, *reportID;
@@ -137,18 +136,16 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
- self.keepOpen = [NSProcessInfo.processInfo.arguments containsObject:@"--show-introduction"];
self.window.title = @"大鱼调色";
self.window.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
self.window.titlebarAppearsTransparent = YES; self.window.backgroundColor = DYColor(.105,.14,.20);
self.window.contentMinSize = NSMakeSize(760,620); [self.window setContentSize:NSMakeSize(920,850)]; [self.window center];
DYBetaStart();
- [self buildInterface]; [self buildMenu];
+ [self buildInterface]; [self buildMenu]; [self buildStatusItem];
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(refreshDiagnostics:) name:DYBetaDiagnosticsChanged object:nil];
self.updater = [[[DYBetaUpdater alloc] init] autorelease];
__block AppDelegate *owner = self;
self.updater.changed = ^(NSDictionary *state) { [owner updateChanged:state]; };
- self.updateProgressTimer = [NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(refreshUpdateProgress:) userInfo:nil repeats:YES];
NSInteger expected=[NSUserDefaults.standardUserDefaults integerForKey:@"betaPendingUpdateBuild"];
if(expected>0 && [NSBundle.mainBundle.infoDictionary[@"CFBundleVersion"]integerValue]>=expected){
DYBetaEvent(@"update_installer",@{@"status":@"completed",@"count":@(expected)});
@@ -157,6 +154,14 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
[NSWorkspace.sharedWorkspace.notificationCenter addObserver:self selector:@selector(accessibilityChanged:)
name:NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification object:nil];
[self.window makeKeyAndOrderFront:nil]; [self refreshDiagnostics:nil]; [self checkRegistration:nil]; [self.updater check];
+ // Explicit QA opt-in on the signed, installed wrapper only. Never stalls the host.
+ if([NSProcessInfo.processInfo.arguments containsObject:@"--diagnostics-probe"])
+ [self performSelector:@selector(runDiagnosticsProbe) withObject:nil afterDelay:5];
+}
+- (void)runDiagnosticsProbe {
+ DYBetaEvent(@"diagnostic_summary",@{@"status":@"probe_begin"});
+ [NSThread sleepForTimeInterval:12];
+ DYBetaEvent(@"diagnostic_summary",@{@"status":@"probe_recovered"});
}
- (void)buildMenu {
NSMenu *menu = [[[NSMenu alloc] initWithTitle:@"大鱼调色"] autorelease];
@@ -203,12 +208,12 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
self.progress.style = NSProgressIndicatorStyleBar; self.progress.indeterminate = YES; self.progress.translatesAutoresizingMaskIntoConstraints = NO;
self.retryButton = DYButton(@"检查中…",DYBlue(),NO,self,@selector(checkRegistration:));
self.keepButton = DYButton(@"查看功能介绍",DYColor(.20,.46,.94),YES,self,@selector(keepIntroduction:));
- self.exitDetail = DYLabel(@"注册成功后,将显示 3 秒退出倒计时。",15,NSFontWeightSemibold,DYGreen());
+ self.exitDetail = DYLabel(@"应用会保持运行,关闭窗口后继续后台诊断。",15,NSFontWeightSemibold,DYGreen());
[self.exitDetail.heightAnchor constraintGreaterThanOrEqualToConstant:38].active = YES;
NSStackView *registration = DYStack(@[DYHeading(@"puzzlepiece.extension",@"插件连接",DYBlue()),self.statusTitle,self.statusDetail,self.progress,
self.exitDetail,DYStack(@[self.retryButton,self.keepButton],NSUserInterfaceLayoutOrientationHorizontal,8)],NSUserInterfaceLayoutOrientationVertical,13);
self.registrationCard = DYCard(DYBlue(),registration);
- self.confirmationButton = DYButton(@"已确认正常,退出",DYGreen(),NO,self,@selector(confirmHost:));
+ self.confirmationButton = DYButton(@"已确认,后台运行",DYGreen(),NO,self,@selector(confirmHost:));
self.confirmationButton.enabled = NO;
self.confirmationButton.toolTip = @"请先在 Final Cut Pro 中应用大鱼调色并确认效果正常,再点击此按钮。";
NSStackView *host = DYStack(@[DYHeading(@"play.rectangle",@"在 Final Cut Pro 中检查",DYGreen()),
@@ -237,7 +242,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
self.reportID=DYLabel(@"报告标识准备中…",10,NSFontWeightRegular,DYSecondary());self.reportID.selectable=YES;
self.sendSummaryButton=DYButton(@"发送诊断摘要",DYColor(.67,.59,1),NO,self,@selector(sendSummary:));
DYSurface *diagnosticCard=DYCard(DYColor(.67,.59,1),DYStack(@[DYHeading(@"waveform.path.ecg",@"一起完善大鱼调色",DYColor(.67,.59,1)),self.diagnosticToggle,
- DYLabel(@"仅发送版本、系统环境、加载耗时和本插件错误摘要;不发送素材、预设或账号。可随时关闭,诊断保留 30 天。",12,NSFontWeightRegular,DYSecondary()),
+ DYLabel(@"后台自动发送版本、系统环境、阶段耗时、内存及本产品崩溃/卡顿调用栈摘要到 dayu.media;不发送素材、预设或账号。可随时关闭,保留 30 天。",12,NSFontWeightRegular,DYSecondary()),
self.reportID,self.diagnosticDetail,self.sendSummaryButton],NSUserInterfaceLayoutOrientationVertical,10));
NSStackView *beta=DYStack(@[updateCard,diagnosticCard],NSUserInterfaceLayoutOrientationHorizontal,14);
[updateCard.heightAnchor constraintEqualToAnchor:diagnosticCard.heightAnchor].active=YES;
@@ -326,7 +331,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
- (void)checkRegistration:(id)sender {
if (self.integrityRejected) return;
if (self.diagnostics && (self.registrationState == DYChecking || self.registrationState == DYRegistering)) return;
- [self.exitTimer invalidate]; self.exitTimer = nil; self.registrationState = DYChecking;
+ self.registrationState = DYChecking;
self.retryButton.enabled = NO; self.retryButton.title = @"检查中…";
self.statusTitle.stringValue = @"正在检查插件…"; self.statusTitle.textColor = NSColor.whiteColor;
self.statusDetail.stringValue = @"正在检查本机插件登记,随后自动提交注册。";
@@ -400,17 +405,25 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
NSAccessibilityPostNotificationWithUserInfo(self.window,NSAccessibilityAnnouncementRequestedNotification,
@{NSAccessibilityAnnouncementKey:self.statusTitle.stringValue,NSAccessibilityPriorityKey:@(NSAccessibilityPriorityHigh)});
DYBetaEvent(@"registration",@{@"status":success?@"registered":@"failed"});
- if(success)[self maybeStartCountdown];
+ if(success)[self refreshBackgroundState];
else self.exitDetail.stringValue=@"注册尚未完成,应用会保留此窗口以便重试。";
}
-- (void)maybeStartCountdown {
- if(self.terminating || self.registrationState!=DYReady)return;
- if(self.keepOpen){self.exitDetail.stringValue=@"插件已就绪。关闭此窗口后,可继续在宿主中使用。";return;}
- if(!self.updateCheckDone){self.exitDetail.stringValue=@"注册成功,正在检查公测更新…";return;}
- if(self.exitTimer)return;
- self.secondsRemaining=3;[self updateCountdown];
- self.exitTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(exitTick:) userInfo:nil repeats:YES];
+- (void)refreshBackgroundState {
+ if(self.registrationState==DYReady)self.exitDetail.stringValue=DYBetaEnabled()?@"后台诊断已开启。关闭窗口后继续运行,可从菜单栏重新打开或退出。":@"诊断已关闭。应用保持运行,可从菜单栏退出。";
}
+- (void)buildStatusItem {
+ self.statusItem=[NSStatusBar.systemStatusBar statusItemWithLength:NSVariableStatusItemLength];
+ self.statusItem.button.image=[NSImage imageWithSystemSymbolName:@"slider.horizontal.3" accessibilityDescription:@"大鱼调色后台诊断"];
+ self.statusItem.button.toolTip=@"大鱼调色 · 后台运行";
+ NSMenu *menu=[[[NSMenu alloc]initWithTitle:@"大鱼调色"]autorelease];
+ NSMenuItem *show=[menu addItemWithTitle:@"打开大鱼调色" action:@selector(showMainWindow:) keyEquivalent:@""];show.target=self;
+ NSMenuItem *send=[menu addItemWithTitle:@"发送诊断摘要" action:@selector(sendSummary:) keyEquivalent:@""];send.target=self;
+ [menu addItem:NSMenuItem.separatorItem];
+ NSMenuItem *quit=[menu addItemWithTitle:@"退出大鱼调色" action:@selector(terminate:) keyEquivalent:@""];quit.target=NSApp;
+ self.statusItem.menu=menu;
+}
+- (void)showMainWindow:(id)sender { [self.window makeKeyAndOrderFront:nil];[NSApp activateIgnoringOtherApps:YES]; }
+- (BOOL)applicationShouldHandleReopen:(NSApplication *)app hasVisibleWindows:(BOOL)visible { if(!visible)[self showMainWindow:nil];return YES; }
- (void)updateChanged:(NSDictionary *)state {
if(self.terminating)return;
NSString *phase=state[@"phase"];
@@ -425,10 +438,12 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
self.updateInstallButton.enabled=[@[@"available",@"ready",@"host_wait",@"installer"]containsObject:phase];
self.updateInstallButton.title=[phase isEqual:@"available"]?@"下载更新":@"安装更新";
self.updateCancelButton.hidden=![phase isEqual:@"downloading"];
+ [self.updateProgressTimer invalidate];self.updateProgressTimer=nil;
+ if([phase isEqual:@"downloading"])self.updateProgressTimer=[NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(refreshUpdateProgress:) userInfo:nil repeats:YES];
self.updateProgress.indeterminate=[@[@"checking",@"validating"]containsObject:phase];
if(self.updateProgress.indeterminate)[self.updateProgress startAnimation:nil];else [self.updateProgress stopAnimation:nil];
self.updateProgress.doubleValue=[@[@"ready",@"host_wait",@"installer"]containsObject:phase]?1:0;
- [self maybeStartCountdown];
+ [self refreshBackgroundState];
}
- (void)refreshUpdateProgress:(NSTimer *)timer {
if([self.updater.state[@"phase"]isEqual:@"downloading"])self.updateProgress.doubleValue=self.updater.downloadFraction;
@@ -441,7 +456,7 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
- (void)cancelUpdate:(id)sender { [self keepIntroduction:nil];[self.updater cancel]; }
- (void)refreshDiagnostics:(NSNotification *)note {
NSDictionary *state=DYBetaStatus();BOOL enabled=DYBetaEnabled();self.diagnosticToggle.state=enabled?NSControlStateValueOn:NSControlStateValueOff;
- self.sendSummaryButton.enabled=enabled;
+ self.sendSummaryButton.enabled=enabled; [self refreshBackgroundState];
self.reportID.stringValue=[NSString stringWithFormat:@"报告标识:%@",state[@"installation_id"]?:@"准备中…"];
NSNumber *uploaded=state[@"last_upload"];
if(!enabled)self.diagnosticDetail.stringValue=@"诊断已关闭。不会继续上传,待发送摘要已清除。";
@@ -451,23 +466,14 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
}
- (void)toggleDiagnostics:(id)sender { [self keepIntroduction:nil];DYBetaSetEnabled(self.diagnosticToggle.state==NSControlStateValueOn);[self refreshDiagnostics:nil]; }
- (void)sendSummary:(id)sender { [self keepIntroduction:nil];DYBetaSendSummary();self.diagnosticDetail.stringValue=@"已加入后台发送队列,送达后会显示时间。"; }
-- (void)updateCountdown { self.exitDetail.stringValue = [NSString stringWithFormat:@"%ld 秒后自动退出\n点击“查看功能介绍”可保留窗口",(long)self.secondsRemaining]; }
-- (void)exitTick:(NSTimer *)timer {
- if (--self.secondsRemaining <= 0) {
- [timer invalidate]; self.exitTimer = nil; self.diagnostics[@"terminationReason"] = @"registration-succeeded"; [self writeDiagnostics]; [NSApp terminate:nil];
- } else [self updateCountdown];
-}
- (void)keepIntroduction:(id)sender {
- self.keepOpen = YES; [self.exitTimer invalidate]; self.exitTimer = nil;
- self.keepButton.title = @"正在浏览介绍"; self.keepButton.enabled = NO;
- self.exitDetail.stringValue = @"已保留功能介绍窗口。插件可独立在宿主中使用。";
+ [self showMainWindow:sender]; [self refreshBackgroundState];
}
- (void)confirmHost:(id)sender {
if (self.registrationState != DYReady) return;
DYBetaEvent(@"host_confirmed",@{@"status":@"user_confirmed"});
self.diagnostics[@"hostVerification"] = @"user-confirmed";
- self.diagnostics[@"terminationReason"] = @"user-confirmed-host";
- [self writeDiagnostics]; [NSApp terminate:nil];
+ [self writeDiagnostics]; [self.window orderOut:nil];
}
- (void)writeDiagnostics {
NSURL *base = [NSFileManager.defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask].firstObject;
@@ -493,13 +499,14 @@ typedef NS_ENUM(NSInteger,DYRegistrationState) { DYChecking, DYRegistering, DYRe
}
- (void)closeWindow:(id)sender { [self.window performClose:sender]; }
- (void)accessibilityChanged:(NSNotification *)note { [self.window.contentView setNeedsDisplay:YES]; }
-- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app { return YES; }
+- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)app { return NO; }
- (void)applicationWillTerminate:(NSNotification *)note {
- self.terminating = YES; [self.exitTimer invalidate]; self.exitTimer = nil;
+ self.terminating = YES;
+ [NSStatusBar.systemStatusBar removeStatusItem:self.statusItem];
self.updater.changed=nil; [self.updater cancel];DYBetaStop();
[self.updateProgressTimer invalidate];self.updateProgressTimer=nil;
[NSNotificationCenter.defaultCenter removeObserver:self];
[NSWorkspace.sharedWorkspace.notificationCenter removeObserver:self];
}
-- (void)dealloc { [_exitTimer invalidate]; [_exitTimer release]; [_diagnostics release]; [_updater release]; [_updateProgressTimer invalidate]; [_updateProgressTimer release]; [super dealloc]; }
+- (void)dealloc { [_statusItem release]; [_diagnostics release]; [_updater release]; [_updateProgressTimer invalidate]; [_updateProgressTimer release]; [super dealloc]; }
@end
diff --git a/大鱼调色/Wrapper Application/Info.plist b/大鱼调色/Wrapper Application/Info.plist
index f04cbc3..fbec002 100644
--- a/大鱼调色/Wrapper Application/Info.plist
+++ b/大鱼调色/Wrapper Application/Info.plist
@@ -17,9 +17,9 @@
CFBundlePackageType
APPL
CFBundleShortVersionString
- 1.17.1
+ 1.18.0
CFBundleVersion
- 103
+ 104
LSMinimumSystemVersion
$(MACOSX_DEPLOYMENT_TARGET)
NSHumanReadableCopyright