@cloud411716/fancy-webnovel 4.10.0 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,7 +34,11 @@ import {
34
34
  updateAccountProfile,
35
35
  } from './state.js';
36
36
  import { analysisPrompt, articlePrompt, capabilityPrompt, helpText, loginQuestion, summaryText, videoAnalysisPrompt, videoRelevancePrompt } from './templates.js';
37
- import { createSerialLock, getSubagentRuntime, runJobPool, subagentWorkerCount } from './subagents.js';
37
+ import { createJobQueue, createSerialLock, getSubagentRuntime, subagentWorkerCount } from './subagents.js';
38
+ import {
39
+ countJobsByAccount, createJob, jobKeyFor, jobRelDir,
40
+ listJobsForAccount, migrateCrawledJobs, openJobStore, updateJob,
41
+ } from './jobs.js';
38
42
 
39
43
  export const inject = ['commands', 'userQuestions'];
40
44
 
@@ -769,6 +773,43 @@ async function runLocalAnalysisJob(ctx, invocation, session, job, {
769
773
  });
770
774
  }
771
775
 
776
+ function readJsonArtifact(dir, name) {
777
+ try {
778
+ return JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'));
779
+ } catch {
780
+ return null;
781
+ }
782
+ }
783
+
784
+ function reusableNote(dir) {
785
+ const note = readJsonArtifact(dir, 'note.json');
786
+ if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) return null;
787
+ if (!note.screenshots.every((shot) => shot && shot.file && fs.existsSync(shot.file))) return null;
788
+ return note;
789
+ }
790
+
791
+ function reusableVideo(dir) {
792
+ const video = readJsonArtifact(dir, 'video.json');
793
+ if (!video || !Array.isArray(video.frames) || !video.frames.length) return null;
794
+ if (!video.frames.every((frame) => frame && frame.file && fs.existsSync(frame.file))) return null;
795
+ return video;
796
+ }
797
+
798
+ function reusableArticle(dir) {
799
+ const article = readJsonArtifact(dir, 'article.json');
800
+ if (!article || !article.body || String(article.body).trim().length < 50) return null;
801
+ return article;
802
+ }
803
+
804
+ function materialFileReady(dir) {
805
+ const file = path.join(dir, 'materials.jsonl');
806
+ try {
807
+ return fs.statSync(file).size > 0;
808
+ } catch {
809
+ return false;
810
+ }
811
+ }
812
+
772
813
  async function runCrawl(ctx, invocation, session, taskList) {
773
814
  const root = workspaceOf(session);
774
815
  const paths = ensureDouyinDir(root);
@@ -779,6 +820,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
779
820
 
780
821
  const runDir = path.join(paths.output, stampOfNow());
781
822
  fs.mkdirSync(runDir, { recursive: true });
823
+ fs.mkdirSync(paths.jobs, { recursive: true });
782
824
 
783
825
  // 先做能力自检:如果模型既不能看图也不能看视频,直接退出,
784
826
  // 不启动 Chrome,也不扫描账号。
@@ -803,9 +845,21 @@ async function runCrawl(ctx, invocation, session, taskList) {
803
845
  return notify(session, 'error', '❌ 部署素材校验脚本失败:\n' + (materialTools.problems.join('\n') || '未知错误'));
804
846
  }
805
847
 
848
+ let jobStore;
849
+ let queue = null;
850
+ let workerPromises = [];
851
+ try {
852
+ jobStore = await openJobStore(root);
853
+ await migrateCrawledJobs(jobStore.db, root);
854
+ } catch (err) {
855
+ if (jobStore) await jobStore.close();
856
+ return notify(session, 'error', '❌ 初始化抖音任务状态表失败:' + (err && err.message ? err.message : String(err)));
857
+ }
858
+
806
859
  const mode = hasDouyinLogin(paths) ? 'headless' : 'headed';
807
860
  const started = await startChrome(root, tools, paths, mode);
808
861
  if (!started.ok) {
862
+ await jobStore.close();
809
863
  return notify(session, 'error', '❌ 启动 Chrome 失败:' + started.error);
810
864
  }
811
865
  const browser = { cdp: started.cdp, mode: started.mode };
@@ -827,7 +881,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
827
881
  else invocation.signal.addEventListener('abort', () => abortController.abort(), { once: true });
828
882
  }
829
883
  const jobSignal = abortController.signal;
830
- const markJobFailed = (job, reason) => {
884
+ const markJobFailedLocked = async (job, reason, { crawl = false } = {}) => {
831
885
  if (!job || !job.id) return;
832
886
  markCrawled(root, job.id, {
833
887
  account_url: job.accountUrl,
@@ -849,7 +903,51 @@ async function runCrawl(ctx, invocation, session, taskList) {
849
903
  reason,
850
904
  });
851
905
  crawled[job.id] = true;
906
+ if (job.jobKey) {
907
+ await updateJob(jobStore.db, job.jobKey, {
908
+ ...(crawl ? { crawl_status: 'failed' } : { analysis_status: 'failed' }),
909
+ import_status: 'failed',
910
+ reason,
911
+ error: reason,
912
+ });
913
+ }
914
+ };
915
+ const markJobFailed = async (job, reason, options) => withStateLock(
916
+ () => markJobFailedLocked(job, reason, options),
917
+ );
918
+
919
+ const markJobSkippedLocked = async (job, reason, { crawl = false } = {}) => {
920
+ if (!job || !job.id) return;
921
+ markCrawled(root, job.id, {
922
+ account_url: job.accountUrl,
923
+ url: job.url || (job.card && job.card.href) || '',
924
+ title: job.title || (job.card && job.card.text) || '',
925
+ type: job.type,
926
+ duration: job.duration,
927
+ dir: job.dir,
928
+ inserted: 0,
929
+ skipped: 0,
930
+ skip: true,
931
+ reason,
932
+ });
933
+ crawled[job.id] = true;
934
+ if (job.jobKey) {
935
+ await updateJob(jobStore.db, job.jobKey, {
936
+ ...(crawl ? { crawl_status: 'crawled' } : {}),
937
+ analysis_status: 'analyzed',
938
+ import_status: 'skipped',
939
+ reason,
940
+ error: '',
941
+ imported_at: new Date(),
942
+ });
943
+ }
852
944
  };
945
+ const markJobSkipped = async (job, reason, options) => withStateLock(
946
+ () => markJobSkippedLocked(job, reason, options),
947
+ );
948
+
949
+ queue = useSubagents ? createJobQueue() : null;
950
+ const queueStats = { queued: 0, finished: 0 };
853
951
  let scannedAccounts = 0;
854
952
  let foundNotes = 0;
855
953
  let foundVideos = 0;
@@ -865,26 +963,169 @@ async function runCrawl(ctx, invocation, session, taskList) {
865
963
  let skippedMaterials = 0;
866
964
  let aborted = false;
867
965
 
966
+ const progressText = () => queue
967
+ ? `子 Agent 并行分析(${queueStats.finished}/${queueStats.queued},并发 ${subagentWorkers})`
968
+ : `LLM 整理素材(${queueStats.finished}/${jobs.length})`;
969
+
970
+ const jobRecord = (job, extra = {}) => ({
971
+ account_url: job.accountUrl,
972
+ url: job.url,
973
+ title: job.title || (job.card && job.card.text) || '',
974
+ type: job.type,
975
+ duration: job.duration,
976
+ screenshots: job.type === 'note' && Array.isArray(job.screenshots)
977
+ ? job.screenshots.map((shot) => shot.file)
978
+ : undefined,
979
+ body_file: job.article && job.article.body_file,
980
+ reading_time: job.article && job.article.reading_time,
981
+ body_length: job.article && job.article.body_length,
982
+ dir: job.dir,
983
+ ...extra,
984
+ });
985
+
986
+ const finalizeJob = async (job, analyzed) => {
987
+ await withStateLock(async () => {
988
+ if (analyzed && analyzed.needsFinalize) {
989
+ analyzed = await finalizeMaterialFile({
990
+ root,
991
+ target: job.target,
992
+ title: job.title,
993
+ materialTools,
994
+ });
995
+ }
996
+ if (analyzed && analyzed.aborted) {
997
+ aborted = true;
998
+ if (job.jobKey) {
999
+ await updateJob(jobStore.db, job.jobKey, { analysis_status: 'pending' });
1000
+ }
1001
+ return;
1002
+ }
1003
+ if (!analyzed || !analyzed.ok) {
1004
+ const reason = (analyzed && (analyzed.error || analyzed.detail)) || '素材没有通过校验';
1005
+ failures.push({ id: job.id, url: job.url, reason });
1006
+ await markJobFailedLocked(job, reason);
1007
+ queueStats.finished += 1;
1008
+ taskList.progress(progressText());
1009
+ return;
1010
+ }
1011
+ if (analyzed.skipped) {
1012
+ skippedIrrelevant += 1;
1013
+ markCrawled(root, job.id, jobRecord(job, {
1014
+ inserted: 0,
1015
+ skipped: 0,
1016
+ skip: true,
1017
+ reason: analyzed.reason || '与网文创作无关',
1018
+ }));
1019
+ if (job.jobKey) {
1020
+ await updateJob(jobStore.db, job.jobKey, {
1021
+ analysis_status: 'analyzed',
1022
+ import_status: 'skipped',
1023
+ material_count: 0,
1024
+ reason: analyzed.reason || '与网文创作无关',
1025
+ error: '',
1026
+ imported_at: new Date(),
1027
+ });
1028
+ }
1029
+ } else {
1030
+ inserted += analyzed.inserted || 0;
1031
+ skippedMaterials += analyzed.skipped || 0;
1032
+ markCrawled(root, job.id, jobRecord(job, {
1033
+ inserted: analyzed.inserted || 0,
1034
+ skipped: analyzed.skipped || 0,
1035
+ }));
1036
+ if (job.jobKey) {
1037
+ await updateJob(jobStore.db, job.jobKey, {
1038
+ analysis_status: 'analyzed',
1039
+ import_status: 'imported',
1040
+ material_count: analyzed.inserted || 0,
1041
+ reason: '',
1042
+ error: '',
1043
+ imported_at: new Date(),
1044
+ });
1045
+ }
1046
+ }
1047
+ crawled[job.id] = true;
1048
+ queueStats.finished += 1;
1049
+ taskList.progress(progressText());
1050
+ });
1051
+ };
1052
+
1053
+ const enqueueJob = async (job) => {
1054
+ if (job.jobKey) {
1055
+ await updateJob(jobStore.db, job.jobKey, {
1056
+ crawl_status: 'crawled',
1057
+ analysis_status: job.finalizeOnly ? 'analyzed' : 'pending',
1058
+ dir_rel: job.dirRel,
1059
+ title: job.title || '',
1060
+ work_url: job.url,
1061
+ error: '',
1062
+ reason: '',
1063
+ });
1064
+ }
1065
+ if (queue) {
1066
+ queueStats.queued += 1;
1067
+ queue.push(job);
1068
+ taskList.progress(progressText());
1069
+ } else {
1070
+ jobs.push(job);
1071
+ }
1072
+ };
1073
+
1074
+ const runWorker = async () => {
1075
+ while (true) {
1076
+ if (abortRequested(invocation)) { aborted = true; return; }
1077
+ const job = await queue.next();
1078
+ if (!job) return;
1079
+ let analyzed;
1080
+ if (job.finalizeOnly) {
1081
+ analyzed = { ok: true, needsFinalize: true };
1082
+ } else {
1083
+ try {
1084
+ analyzed = await runSubagentAnalysisJob({
1085
+ subagents: subagentRuntime,
1086
+ provider: 'spawn',
1087
+ invocation,
1088
+ job,
1089
+ root,
1090
+ materialTools,
1091
+ signal: jobSignal,
1092
+ });
1093
+ } catch (err) {
1094
+ analyzed = {
1095
+ ok: false,
1096
+ error: '子 Agent 分析失败:' + (err && err.message ? err.message : String(err)),
1097
+ };
1098
+ }
1099
+ }
1100
+ await finalizeJob(job, analyzed);
1101
+ }
1102
+ };
1103
+
1104
+ workerPromises = queue
1105
+ ? Array.from({ length: subagentWorkers }, () => runWorker())
1106
+ : [];
1107
+ if (queue) {
1108
+ taskList.progress(progressText());
1109
+ }
1110
+
868
1111
  outer:
869
1112
  for (const account of accounts) {
870
1113
  if (abortRequested(invocation)) { aborted = true; break; }
871
1114
  const accountDir = path.join(runDir, accountSlug(account.url));
872
- const markFailed = (id, card, data, reason) => {
1115
+ const markFailed = async (id, card, data, reason) => {
873
1116
  if (!id) return;
874
- markCrawled(root, id, {
875
- account_url: account.url,
1117
+ const job = {
1118
+ id,
1119
+ jobKey: jobKeyFor(account.url, id),
1120
+ accountUrl: account.url,
876
1121
  url: data.url || card.href,
877
1122
  title: data.title || card.text || '',
878
1123
  type: data.type,
879
1124
  duration: data.duration,
880
1125
  dir: data.dir,
881
- inserted: 0,
882
- skipped: 0,
883
- skip: true,
884
- failed: true,
885
- reason,
886
- });
887
- crawled[id] = true;
1126
+ card,
1127
+ };
1128
+ await markJobFailed(job, reason, { crawl: true });
888
1129
  };
889
1130
  const scan = await runWithLogin(
890
1131
  ctx, invocation, session, root, tools.scripts.scan,
@@ -906,7 +1147,41 @@ async function runCrawl(ctx, invocation, session, taskList) {
906
1147
  scannedAccounts += 1;
907
1148
  if (scan.json.profile) {
908
1149
  updateAccountProfile(root, account.url, scan.json.profile);
1150
+ account.name = scan.json.profile.name || account.name || '';
1151
+ account.douyin_id = scan.json.profile.douyin_id || account.douyin_id || '';
1152
+ account.sec_uid = scan.json.profile.sec_uid || account.sec_uid || '';
909
1153
  }
1154
+ const existingJobs = new Map((await listJobsForAccount(jobStore.db, account.url))
1155
+ .map((job) => [String(job.work_id), job]));
1156
+ const ensureJob = async (workId, type, card, dirRel, title = '') => {
1157
+ const key = jobKeyFor(account.url, workId);
1158
+ let row = existingJobs.get(String(workId)) || null;
1159
+ if (!row) {
1160
+ row = await createJob(jobStore.db, {
1161
+ job_key: key,
1162
+ account_url: account.url,
1163
+ account_name: account.name || '',
1164
+ douyin_id: account.douyin_id || '',
1165
+ account_sec_uid: account.sec_uid || '',
1166
+ work_id: String(workId),
1167
+ work_type: type,
1168
+ work_url: card.href,
1169
+ title: title || card.text || '',
1170
+ dir_rel: dirRel,
1171
+ });
1172
+ existingJobs.set(String(workId), row);
1173
+ } else {
1174
+ await updateJob(jobStore.db, row.job_key || key, {
1175
+ account_name: account.name || '',
1176
+ douyin_id: account.douyin_id || '',
1177
+ account_sec_uid: account.sec_uid || '',
1178
+ title: title || row.title || '',
1179
+ work_url: card.href,
1180
+ dir_rel: dirRel,
1181
+ });
1182
+ }
1183
+ return row.job_key || key;
1184
+ };
910
1185
  const notes = Array.isArray(scan.json.notes) ? scan.json.notes : [];
911
1186
  const videos = Array.isArray(scan.json.videos) ? scan.json.videos : [];
912
1187
  const articles = Array.isArray(scan.json.articles) ? scan.json.articles : [];
@@ -917,50 +1192,114 @@ async function runCrawl(ctx, invocation, session, taskList) {
917
1192
 
918
1193
  for (const card of notes) {
919
1194
  if (abortRequested(invocation)) { aborted = true; break outer; }
920
- if (!capabilities.image_supported) {
921
- skippedNotesByCapability += 1;
922
- continue;
923
- }
924
1195
  const noteId = noteIdFromUrl(card.href);
925
1196
  if (!noteId) continue;
926
- if (crawled[noteId] || queued.has(noteId)) {
1197
+ const existing = existingJobs.get(String(noteId)) || null;
1198
+ if (existing && existing.import_status !== 'pending') {
927
1199
  skippedNotes += 1;
928
1200
  continue;
929
1201
  }
930
- const noteDir = path.join(accountDir, noteId);
931
- const noteResult = await runWithLogin(
932
- ctx, invocation, session, root, tools.scripts.note,
933
- ['--workspace', root, '--note', card.href, '--cdp', browser.cdp,
934
- '--out', noteDir, '--login-state', paths.loginState],
935
- noteDir,
936
- paths,
937
- '采集图文作品',
938
- tools.nodePath,
939
- browser,
940
- tools,
941
- );
942
- if (!noteResult.ok) {
943
- failures.push({ id: noteId, url: card.href, reason: noteResult.error });
944
- if (noteResult.cancelled || authFailureText(noteResult.error)) { aborted = true; break outer; }
945
- markFailed(noteId, card, { type: 'note', dir: noteDir }, noteResult.error);
1202
+ if ((!existing && crawled[noteId]) || queued.has(noteId)) {
1203
+ skippedNotes += 1;
946
1204
  continue;
947
1205
  }
948
- const note = noteResult.json.note;
949
- if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) {
950
- failures.push({ id: noteId, url: card.href, reason: '没有截图' });
951
- markFailed(noteId, card, { type: 'note', dir: noteDir }, '没有截图');
1206
+
1207
+ const dirRel = existing && existing.dir_rel ? existing.dir_rel : jobRelDir(account.url, noteId);
1208
+ const noteDir = path.join(paths.jobs, dirRel);
1209
+ const jobKey = await ensureJob(noteId, 'note', card, dirRel, existing && existing.title);
1210
+ const target = path.join(noteDir, 'materials.jsonl');
1211
+
1212
+ if (materialFileReady(noteDir)) {
1213
+ processedWorks += 1;
1214
+ await enqueueJob({
1215
+ type: 'note',
1216
+ id: noteId,
1217
+ jobKey,
1218
+ card,
1219
+ accountUrl: account.url,
1220
+ url: (existing && existing.work_url) || card.href,
1221
+ dir: noteDir,
1222
+ dirRel,
1223
+ target,
1224
+ title: (existing && existing.title) || card.text || '',
1225
+ screenshots: [],
1226
+ finalizeOnly: true,
1227
+ });
1228
+ queued.add(noteId);
1229
+ if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
1230
+ const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
1231
+ await sleep(delay);
1232
+ }
952
1233
  continue;
953
1234
  }
1235
+
1236
+ if (!capabilities.image_supported) {
1237
+ skippedNotesByCapability += 1;
1238
+ continue;
1239
+ }
1240
+
1241
+ let note = reusableNote(noteDir);
1242
+ if (note) {
1243
+ note.account_url = account.url;
1244
+ await updateJob(jobStore.db, jobKey, {
1245
+ crawl_status: 'crawled',
1246
+ analysis_status: 'pending',
1247
+ dir_rel: dirRel,
1248
+ title: note.title || card.text || '',
1249
+ work_url: note.url || card.href,
1250
+ error: '',
1251
+ });
1252
+ } else {
1253
+ await updateJob(jobStore.db, jobKey, {
1254
+ crawl_status: 'crawling',
1255
+ analysis_status: 'pending',
1256
+ dir_rel: dirRel,
1257
+ attempts: (Number(existing && existing.attempts) || 0) + 1,
1258
+ error: '',
1259
+ });
1260
+ const noteResult = await runWithLogin(
1261
+ ctx, invocation, session, root, tools.scripts.note,
1262
+ ['--workspace', root, '--note', card.href, '--cdp', browser.cdp,
1263
+ '--out', noteDir, '--login-state', paths.loginState],
1264
+ noteDir,
1265
+ paths,
1266
+ '采集图文作品',
1267
+ tools.nodePath,
1268
+ browser,
1269
+ tools,
1270
+ );
1271
+ if (!noteResult.ok) {
1272
+ failures.push({ id: noteId, url: card.href, reason: noteResult.error });
1273
+ if (noteResult.cancelled || authFailureText(noteResult.error)) { aborted = true; break outer; }
1274
+ await markFailed(noteId, card, { type: 'note', dir: noteDir }, noteResult.error);
1275
+ continue;
1276
+ }
1277
+ note = noteResult.json.note;
1278
+ if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) {
1279
+ failures.push({ id: noteId, url: card.href, reason: '没有截图' });
1280
+ await markFailed(noteId, card, { type: 'note', dir: noteDir }, '没有截图');
1281
+ continue;
1282
+ }
1283
+ await updateJob(jobStore.db, jobKey, {
1284
+ crawl_status: 'crawled',
1285
+ title: note.title || '',
1286
+ work_url: note.url || card.href,
1287
+ dir_rel: dirRel,
1288
+ error: '',
1289
+ });
1290
+ }
1291
+
954
1292
  processedWorks += 1;
955
1293
  note.account_url = account.url;
956
- const target = path.join(noteDir, 'materials.jsonl');
957
- jobs.push({
1294
+ await enqueueJob({
958
1295
  type: 'note',
959
1296
  id: noteId,
1297
+ jobKey,
960
1298
  card,
961
1299
  accountUrl: account.url,
962
1300
  url: note.url || card.href,
963
1301
  dir: noteDir,
1302
+ dirRel,
964
1303
  note,
965
1304
  screenshots: note.screenshots,
966
1305
  target,
@@ -975,62 +1314,122 @@ async function runCrawl(ctx, invocation, session, taskList) {
975
1314
 
976
1315
  for (const card of videos) {
977
1316
  if (abortRequested(invocation)) { aborted = true; break outer; }
978
- if (!capabilities.video_supported) {
979
- skippedVideosByCapability += 1;
980
- continue;
981
- }
982
1317
  const videoId = noteIdFromUrl(card.href);
983
1318
  if (!videoId) continue;
984
- if (crawled[videoId] || queued.has(videoId)) {
1319
+ const existing = existingJobs.get(String(videoId)) || null;
1320
+ if (existing && existing.import_status !== 'pending') {
985
1321
  skippedNotes += 1;
986
1322
  continue;
987
1323
  }
988
- const videoDir = path.join(accountDir, videoId);
989
- const videoResult = await runWithLogin(
990
- ctx, invocation, session, root, tools.scripts.video,
991
- ['--workspace', root, '--video', card.href, '--cdp', browser.cdp,
992
- '--out', videoDir, '--login-state', paths.loginState,
993
- '--max-seconds', String(MAX_VIDEO_SECONDS)],
994
- videoDir,
995
- paths,
996
- '采集视频作品',
997
- tools.nodePath,
998
- browser,
999
- tools,
1000
- VIDEO_SCRIPT_TIMEOUT_MS,
1001
- );
1002
- if (!videoResult.ok) {
1003
- failures.push({ id: videoId, url: card.href, reason: videoResult.error });
1004
- if (videoResult.cancelled || authFailureText(videoResult.error)) { aborted = true; break outer; }
1005
- markFailed(videoId, card, { type: 'video', dir: videoDir }, videoResult.error);
1324
+ if ((!existing && crawled[videoId]) || queued.has(videoId)) {
1325
+ skippedNotes += 1;
1006
1326
  continue;
1007
1327
  }
1008
- const video = videoResult.json.video || {};
1009
- if (videoResult.json.skip) {
1010
- skippedLongVideos += 1;
1011
- markCrawled(root, videoId, {
1012
- account_url: account.url,
1013
- url: video.url || card.href,
1014
- title: video.title || card.text || '',
1328
+
1329
+ const dirRel = existing && existing.dir_rel ? existing.dir_rel : jobRelDir(account.url, videoId);
1330
+ const videoDir = path.join(paths.jobs, dirRel);
1331
+ const jobKey = await ensureJob(videoId, 'video', card, dirRel, existing && existing.title);
1332
+ const target = path.join(videoDir, 'materials.jsonl');
1333
+
1334
+ if (materialFileReady(videoDir)) {
1335
+ processedWorks += 1;
1336
+ await enqueueJob({
1015
1337
  type: 'video',
1016
- duration: video.duration,
1338
+ id: videoId,
1339
+ jobKey,
1340
+ card,
1341
+ accountUrl: account.url,
1342
+ url: (existing && existing.work_url) || card.href,
1017
1343
  dir: videoDir,
1018
- inserted: 0,
1019
- skipped: 0,
1020
- skip: true,
1021
- reason: videoResult.json.reason || '视频时长超过 1 分钟',
1344
+ dirRel,
1345
+ target,
1346
+ title: (existing && existing.title) || card.text || '',
1347
+ duration: existing && existing.duration,
1348
+ video: null,
1349
+ finalizeOnly: true,
1022
1350
  });
1023
- crawled[videoId] = true;
1351
+ queued.add(videoId);
1352
+ if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
1353
+ const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
1354
+ await sleep(delay);
1355
+ }
1024
1356
  continue;
1025
1357
  }
1026
- if (!video || !Array.isArray(video.frames) || !video.frames.length) {
1027
- failures.push({ id: videoId, url: card.href, reason: '没有视频关键帧' });
1028
- markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title }, '没有视频关键帧');
1358
+
1359
+ if (!capabilities.video_supported) {
1360
+ skippedVideosByCapability += 1;
1029
1361
  continue;
1030
1362
  }
1363
+
1364
+ let video = reusableVideo(videoDir);
1365
+ if (!video) {
1366
+ await updateJob(jobStore.db, jobKey, {
1367
+ crawl_status: 'crawling',
1368
+ analysis_status: 'pending',
1369
+ dir_rel: dirRel,
1370
+ attempts: (Number(existing && existing.attempts) || 0) + 1,
1371
+ error: '',
1372
+ });
1373
+ const videoResult = await runWithLogin(
1374
+ ctx, invocation, session, root, tools.scripts.video,
1375
+ ['--workspace', root, '--video', card.href, '--cdp', browser.cdp,
1376
+ '--out', videoDir, '--login-state', paths.loginState,
1377
+ '--max-seconds', String(MAX_VIDEO_SECONDS)],
1378
+ videoDir,
1379
+ paths,
1380
+ '采集视频作品',
1381
+ tools.nodePath,
1382
+ browser,
1383
+ tools,
1384
+ VIDEO_SCRIPT_TIMEOUT_MS,
1385
+ );
1386
+ if (!videoResult.ok) {
1387
+ failures.push({ id: videoId, url: card.href, reason: videoResult.error });
1388
+ if (videoResult.cancelled || authFailureText(videoResult.error)) { aborted = true; break outer; }
1389
+ await markFailed(videoId, card, { type: 'video', dir: videoDir }, videoResult.error);
1390
+ continue;
1391
+ }
1392
+ video = videoResult.json.video || {};
1393
+ if (videoResult.json.skip) {
1394
+ skippedLongVideos += 1;
1395
+ await markJobSkipped({
1396
+ id: videoId,
1397
+ jobKey,
1398
+ accountUrl: account.url,
1399
+ url: video.url || card.href,
1400
+ title: video.title || card.text || '',
1401
+ type: 'video',
1402
+ duration: video.duration,
1403
+ dir: videoDir,
1404
+ card,
1405
+ }, videoResult.json.reason || '视频时长超过 1 分钟', { crawl: true });
1406
+ continue;
1407
+ }
1408
+ if (!video || !Array.isArray(video.frames) || !video.frames.length) {
1409
+ failures.push({ id: videoId, url: card.href, reason: '没有视频关键帧' });
1410
+ await markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title }, '没有视频关键帧');
1411
+ continue;
1412
+ }
1413
+ await updateJob(jobStore.db, jobKey, {
1414
+ crawl_status: 'crawled',
1415
+ title: video.title || '',
1416
+ work_url: video.url || card.href,
1417
+ dir_rel: dirRel,
1418
+ error: '',
1419
+ });
1420
+ } else {
1421
+ await updateJob(jobStore.db, jobKey, {
1422
+ crawl_status: 'crawled',
1423
+ analysis_status: 'pending',
1424
+ dir_rel: dirRel,
1425
+ title: video.title || '',
1426
+ work_url: video.url || card.href,
1427
+ error: '',
1428
+ });
1429
+ }
1430
+
1031
1431
  processedWorks += 1;
1032
1432
  video.account_url = account.url;
1033
- const target = path.join(videoDir, 'materials.jsonl');
1034
1433
  taskList.advance(4);
1035
1434
  taskList.progress(`LLM 判断视频前 5 秒(${video.title || videoId})`);
1036
1435
  const relevance = await analyzeVideoRelevance(ctx, invocation, session, {
@@ -1043,34 +1442,34 @@ async function runCrawl(ctx, invocation, session, taskList) {
1043
1442
  if (!relevance.ok) {
1044
1443
  failures.push({ id: videoId, url: card.href, reason: relevance.error });
1045
1444
  if (relevance.aborted) { aborted = true; break outer; }
1046
- markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
1445
+ await markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
1047
1446
  continue;
1048
1447
  }
1049
1448
  if (relevance.skip) {
1050
1449
  skippedIrrelevant += 1;
1051
- markCrawled(root, videoId, {
1052
- account_url: account.url,
1450
+ await markJobSkipped({
1451
+ id: videoId,
1452
+ jobKey,
1453
+ accountUrl: account.url,
1053
1454
  url: video.url || card.href,
1054
1455
  title: video.title || card.text || '',
1055
1456
  type: 'video',
1056
1457
  duration: video.duration,
1057
1458
  dir: videoDir,
1058
- inserted: 0,
1059
- skipped: 0,
1060
- skip: true,
1061
- reason: relevance.reason || '前 5 秒与网文创作无关',
1062
- });
1063
- crawled[videoId] = true;
1459
+ card,
1460
+ }, relevance.reason || '前 5 秒与网文创作无关');
1064
1461
  continue;
1065
1462
  }
1066
1463
 
1067
- jobs.push({
1464
+ await enqueueJob({
1068
1465
  type: 'video',
1069
1466
  id: videoId,
1467
+ jobKey,
1070
1468
  card,
1071
1469
  accountUrl: account.url,
1072
1470
  url: video.url || card.href,
1073
1471
  dir: videoDir,
1472
+ dirRel,
1074
1473
  video,
1075
1474
  target,
1076
1475
  title: video.title,
@@ -1087,44 +1486,106 @@ async function runCrawl(ctx, invocation, session, taskList) {
1087
1486
  if (abortRequested(invocation)) { aborted = true; break outer; }
1088
1487
  const articleId = noteIdFromUrl(card.href);
1089
1488
  if (!articleId) continue;
1090
- if (crawled[articleId] || queued.has(articleId)) {
1489
+ const existing = existingJobs.get(String(articleId)) || null;
1490
+ if (existing && existing.import_status !== 'pending') {
1091
1491
  skippedArticles += 1;
1092
1492
  continue;
1093
1493
  }
1094
- const articleDir = path.join(accountDir, articleId);
1095
- const articleResult = await runWithLogin(
1096
- ctx, invocation, session, root, tools.scripts.article,
1097
- ['--workspace', root, '--article', card.href, '--cdp', browser.cdp,
1098
- '--out', articleDir, '--login-state', paths.loginState],
1099
- articleDir,
1100
- paths,
1101
- '采集文章',
1102
- tools.nodePath,
1103
- browser,
1104
- tools,
1105
- );
1106
- if (!articleResult.ok) {
1107
- failures.push({ id: articleId, url: card.href, reason: articleResult.error });
1108
- if (articleResult.cancelled || authFailureText(articleResult.error)) { aborted = true; break outer; }
1109
- markFailed(articleId, card, { type: 'article', dir: articleDir }, articleResult.error);
1494
+ if ((!existing && crawled[articleId]) || queued.has(articleId)) {
1495
+ skippedArticles += 1;
1110
1496
  continue;
1111
1497
  }
1112
- const article = articleResult.json.article || {};
1113
- if (!article || !article.body || String(article.body).trim().length < 50) {
1114
- failures.push({ id: articleId, url: card.href, reason: '文章正文为空' });
1115
- markFailed(articleId, card, { type: 'article', dir: articleDir, title: article.title }, '文章正文为空');
1498
+
1499
+ const dirRel = existing && existing.dir_rel ? existing.dir_rel : jobRelDir(account.url, articleId);
1500
+ const articleDir = path.join(paths.jobs, dirRel);
1501
+ const jobKey = await ensureJob(articleId, 'article', card, dirRel, existing && existing.title);
1502
+ const target = path.join(articleDir, 'materials.jsonl');
1503
+
1504
+ if (materialFileReady(articleDir)) {
1505
+ processedWorks += 1;
1506
+ await enqueueJob({
1507
+ type: 'article',
1508
+ id: articleId,
1509
+ jobKey,
1510
+ card,
1511
+ accountUrl: account.url,
1512
+ url: (existing && existing.work_url) || card.href,
1513
+ dir: articleDir,
1514
+ dirRel,
1515
+ target,
1516
+ title: (existing && existing.title) || card.text || '',
1517
+ article: null,
1518
+ finalizeOnly: true,
1519
+ });
1520
+ queued.add(articleId);
1521
+ if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
1522
+ const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
1523
+ await sleep(delay);
1524
+ }
1116
1525
  continue;
1117
1526
  }
1527
+
1528
+ let article = reusableArticle(articleDir);
1529
+ if (!article) {
1530
+ await updateJob(jobStore.db, jobKey, {
1531
+ crawl_status: 'crawling',
1532
+ analysis_status: 'pending',
1533
+ dir_rel: dirRel,
1534
+ attempts: (Number(existing && existing.attempts) || 0) + 1,
1535
+ error: '',
1536
+ });
1537
+ const articleResult = await runWithLogin(
1538
+ ctx, invocation, session, root, tools.scripts.article,
1539
+ ['--workspace', root, '--article', card.href, '--cdp', browser.cdp,
1540
+ '--out', articleDir, '--login-state', paths.loginState],
1541
+ articleDir,
1542
+ paths,
1543
+ '采集文章',
1544
+ tools.nodePath,
1545
+ browser,
1546
+ tools,
1547
+ );
1548
+ if (!articleResult.ok) {
1549
+ failures.push({ id: articleId, url: card.href, reason: articleResult.error });
1550
+ if (articleResult.cancelled || authFailureText(articleResult.error)) { aborted = true; break outer; }
1551
+ await markFailed(articleId, card, { type: 'article', dir: articleDir }, articleResult.error);
1552
+ continue;
1553
+ }
1554
+ article = articleResult.json.article || {};
1555
+ if (!article || !article.body || String(article.body).trim().length < 50) {
1556
+ failures.push({ id: articleId, url: card.href, reason: '文章正文为空' });
1557
+ await markFailed(articleId, card, { type: 'article', dir: articleDir, title: article.title }, '文章正文为空');
1558
+ continue;
1559
+ }
1560
+ await updateJob(jobStore.db, jobKey, {
1561
+ crawl_status: 'crawled',
1562
+ title: article.title || '',
1563
+ work_url: article.url || card.href,
1564
+ dir_rel: dirRel,
1565
+ error: '',
1566
+ });
1567
+ } else {
1568
+ await updateJob(jobStore.db, jobKey, {
1569
+ crawl_status: 'crawled',
1570
+ analysis_status: 'pending',
1571
+ dir_rel: dirRel,
1572
+ title: article.title || '',
1573
+ work_url: article.url || card.href,
1574
+ error: '',
1575
+ });
1576
+ }
1577
+
1118
1578
  processedWorks += 1;
1119
1579
  article.account_url = account.url;
1120
- const target = path.join(articleDir, 'materials.jsonl');
1121
- jobs.push({
1580
+ await enqueueJob({
1122
1581
  type: 'article',
1123
1582
  id: articleId,
1583
+ jobKey,
1124
1584
  card,
1125
1585
  accountUrl: account.url,
1126
1586
  url: article.url || card.href,
1127
1587
  dir: articleDir,
1588
+ dirRel,
1128
1589
  article,
1129
1590
  target,
1130
1591
  title: article.title,
@@ -1137,115 +1598,22 @@ async function runCrawl(ctx, invocation, session, taskList) {
1137
1598
  }
1138
1599
  }
1139
1600
 
1140
- if (jobs.length) {
1601
+ if (queue) {
1602
+ queue.close();
1603
+ await Promise.all(workerPromises);
1604
+ } else if (jobs.length) {
1141
1605
  taskList.advance(4);
1142
- let finishedJobs = 0;
1143
- const progressText = () => useSubagents
1144
- ? `子 Agent 并行分析(${finishedJobs}/${jobs.length})`
1145
- : `LLM 整理素材(${finishedJobs}/${jobs.length})`;
1146
1606
  taskList.progress(progressText());
1147
-
1148
- const finalizeJob = async (job, analyzed) => {
1149
- await withStateLock(async () => {
1150
- if (analyzed && analyzed.needsFinalize) {
1151
- analyzed = await finalizeMaterialFile({
1152
- root,
1153
- target: job.target,
1154
- title: job.title,
1155
- materialTools,
1156
- });
1157
- }
1158
- if (analyzed && analyzed.aborted) {
1159
- aborted = true;
1160
- return;
1161
- }
1162
- if (!analyzed || !analyzed.ok) {
1163
- const reason = (analyzed && (analyzed.error || analyzed.detail)) || '素材没有通过校验';
1164
- failures.push({ id: job.id, url: job.url, reason });
1165
- markJobFailed(job, reason);
1166
- return;
1167
- }
1168
- if (analyzed.skipped) {
1169
- skippedIrrelevant += 1;
1170
- markCrawled(root, job.id, {
1171
- account_url: job.accountUrl,
1172
- url: job.url,
1173
- title: job.title || (job.card && job.card.text) || '',
1174
- type: job.type,
1175
- duration: job.duration,
1176
- screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1177
- ? job.screenshots.map((shot) => shot.file)
1178
- : undefined,
1179
- body_file: job.article && job.article.body_file,
1180
- reading_time: job.article && job.article.reading_time,
1181
- body_length: job.article && job.article.body_length,
1182
- dir: job.dir,
1183
- inserted: 0,
1184
- skipped: 0,
1185
- skip: true,
1186
- reason: analyzed.reason || '与网文创作无关',
1187
- });
1188
- } else {
1189
- inserted += analyzed.inserted || 0;
1190
- skippedMaterials += analyzed.skipped || 0;
1191
- markCrawled(root, job.id, {
1192
- account_url: job.accountUrl,
1193
- url: job.url,
1194
- title: job.title || (job.card && job.card.text) || '',
1195
- type: job.type,
1196
- duration: job.duration,
1197
- screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1198
- ? job.screenshots.map((shot) => shot.file)
1199
- : undefined,
1200
- body_file: job.article && job.article.body_file,
1201
- reading_time: job.article && job.article.reading_time,
1202
- body_length: job.article && job.article.body_length,
1203
- dir: job.dir,
1204
- inserted: analyzed.inserted || 0,
1205
- skipped: analyzed.skipped || 0,
1206
- });
1207
- }
1208
- crawled[job.id] = true;
1209
- finishedJobs += 1;
1210
- taskList.progress(progressText());
1211
- });
1212
- };
1213
-
1214
- if (useSubagents) {
1215
- taskList.progress(`子 Agent 并行分析(0/${jobs.length},并发 ${subagentWorkers})`);
1216
- await runJobPool(jobs, subagentWorkers, async (job) => {
1217
- if (abortRequested(invocation)) { aborted = true; return; }
1218
- let analyzed;
1219
- try {
1220
- analyzed = await runSubagentAnalysisJob({
1221
- subagents: subagentRuntime,
1222
- provider: 'spawn',
1223
- invocation,
1224
- job,
1225
- root,
1226
- materialTools,
1227
- signal: jobSignal,
1228
- });
1229
- } catch (err) {
1230
- analyzed = {
1231
- ok: false,
1232
- error: '子 Agent 分析失败:' + (err && err.message ? err.message : String(err)),
1233
- };
1234
- }
1235
- await finalizeJob(job, analyzed);
1607
+ for (const job of jobs) {
1608
+ if (abortRequested(invocation)) { aborted = true; break; }
1609
+ const analyzed = await runLocalAnalysisJob(ctx, invocation, session, job, {
1610
+ root,
1611
+ materialTools,
1612
+ paths,
1613
+ taskList,
1236
1614
  });
1237
- } else {
1238
- for (const job of jobs) {
1239
- if (abortRequested(invocation)) { aborted = true; break; }
1240
- const analyzed = await runLocalAnalysisJob(ctx, invocation, session, job, {
1241
- root,
1242
- materialTools,
1243
- paths,
1244
- taskList,
1245
- });
1246
- await finalizeJob(job, analyzed);
1247
- if (analyzed && analyzed.fatal) { aborted = true; break; }
1248
- }
1615
+ await finalizeJob(job, analyzed);
1616
+ if (analyzed && analyzed.fatal) { aborted = true; break; }
1249
1617
  }
1250
1618
  }
1251
1619
 
@@ -1274,7 +1642,12 @@ async function runCrawl(ctx, invocation, session, taskList) {
1274
1642
  subagentWorkers,
1275
1643
  }));
1276
1644
  } finally {
1645
+ if (queue) {
1646
+ queue.close();
1647
+ await Promise.allSettled(workerPromises);
1648
+ }
1277
1649
  await stopChrome(root, tools, paths);
1650
+ if (jobStore) await jobStore.close();
1278
1651
  }
1279
1652
  }
1280
1653
 
@@ -1296,7 +1669,17 @@ async function runAdd(session, rawUrl) {
1296
1669
 
1297
1670
  async function runList(session) {
1298
1671
  const root = workspaceOf(session);
1299
- return notify(session, 'success', accountListText(root));
1672
+ let counts = null;
1673
+ try {
1674
+ const store = await openJobStore(root);
1675
+ try {
1676
+ await migrateCrawledJobs(store.db, root);
1677
+ counts = await countJobsByAccount(store.db);
1678
+ } finally {
1679
+ await store.close();
1680
+ }
1681
+ } catch { /* fall back to local crawled.json */ }
1682
+ return notify(session, 'success', accountListText(root, counts));
1300
1683
  }
1301
1684
 
1302
1685
  async function runRemove(session, selector, taskList) {