poi-plugin-kca-next 1.0.4 → 1.0.6

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.
Files changed (2) hide show
  1. package/dist/index.js +1025 -177
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -56,8 +56,8 @@ __export(index_exports, {
56
56
  scoreTemplateAgainstRoi: () => scoreTemplateAgainstRoi
57
57
  });
58
58
  module.exports = __toCommonJS(index_exports);
59
- var import_node_fs4 = __toESM(require("fs"));
60
- var import_node_path3 = __toESM(require("path"));
59
+ var import_node_fs5 = __toESM(require("fs"));
60
+ var import_node_path4 = __toESM(require("path"));
61
61
  var import_react12 = __toESM(require("react"));
62
62
 
63
63
  // src/data/coords.ts
@@ -808,7 +808,7 @@ function createDefaultSettings() {
808
808
  rememberKiraByExpedition: true,
809
809
  expeditionKiraPresets: [],
810
810
  kiraEnabled: [false, true, true, true],
811
- kiraForSupport: [true, false, false, false],
811
+ kiraForSupport: [false, false, false, false],
812
812
  kiraCount: [6, 6, 6, 6],
813
813
  kiraTargetCond: [75, 75, 75, 75],
814
814
  kiraOrder: ["level", "level", "level", "level"],
@@ -821,7 +821,8 @@ function createDefaultSettings() {
821
821
  kiraSupplyEscort: false,
822
822
  kiraClearEscortEquips: true,
823
823
  kiraExcludeLockedEscort: true,
824
- kiraAutoDissolution: false
824
+ kiraAutoDissolution: false,
825
+ kiraUseFleet1: true
825
826
  },
826
827
  sortie: {
827
828
  activeProfileId: defaultSortie.id,
@@ -1481,7 +1482,7 @@ function importLegacyAssistantSettings(input) {
1481
1482
  kiraEnabled: boolVal(kpNode, "AutoKiraOpen", true),
1482
1483
  kiraForSupport: boolVal(kpNode, "KiraForSupport", false),
1483
1484
  kiraCount: intVal(kpNode, "AutoKiraCount", 6),
1484
- kiraTargetCond: intVal(kpNode, "AutoKiraTargetCond", 75),
1485
+ kiraTargetCond: Math.max(50, Math.min(85, intVal(kpNode, "AutoKiraTargetCond", 75))),
1485
1486
  kiraOrder: strVal(kpNode, "AutoKiraFilter", "\u7B49\u7EA7") === "\u987A\u5E8F" ? "slot" : "level"
1486
1487
  });
1487
1488
  }
@@ -1507,7 +1508,7 @@ function importLegacyAssistantSettings(input) {
1507
1508
  }
1508
1509
  const kiraCond = children(child(expNode, "AutoKiraTargetCond"), "int").map((n) => {
1509
1510
  const v = parseInt(n.text.trim(), 10);
1510
- return Number.isFinite(v) ? v : 75;
1511
+ return Number.isFinite(v) ? Math.max(50, Math.min(85, v)) : 75;
1511
1512
  });
1512
1513
  if (kiraCond.length >= 4) {
1513
1514
  settings.expedition.kiraTargetCond = [kiraCond[0], kiraCond[1], kiraCond[2], kiraCond[3]];
@@ -2416,10 +2417,12 @@ var SettingsStore = class {
2416
2417
  filePath;
2417
2418
  backupDir;
2418
2419
  customTemplatesPath;
2420
+ kiraRestorePath;
2419
2421
  constructor(baseDir) {
2420
2422
  this.filePath = import_node_path2.default.join(baseDir, "settings.v1.json");
2421
2423
  this.backupDir = import_node_path2.default.join(baseDir, "backups");
2422
2424
  this.customTemplatesPath = import_node_path2.default.join(baseDir, "custom-templates.json");
2425
+ this.kiraRestorePath = import_node_path2.default.join(baseDir, "kira-restore.json");
2423
2426
  }
2424
2427
  get settingsFilePath() {
2425
2428
  return this.filePath;
@@ -2509,6 +2512,51 @@ var SettingsStore = class {
2509
2512
  } catch {
2510
2513
  }
2511
2514
  }
2515
+ loadKiraRestoreSnapshot() {
2516
+ try {
2517
+ if (!import_node_fs2.default.existsSync(this.kiraRestorePath)) return null;
2518
+ const raw = JSON.parse(import_node_fs2.default.readFileSync(this.kiraRestorePath, "utf8"));
2519
+ if (!raw || raw.version !== 1 || typeof raw.runnerFleetId !== "number" || raw.runnerFleetId < 1 || raw.runnerFleetId > 4 || !Array.isArray(raw.originalRunnerShipIds)) {
2520
+ return null;
2521
+ }
2522
+ const runnerIds = raw.originalRunnerShipIds.filter((x) => typeof x === "number" && x > 0);
2523
+ const sourceFleetId = typeof raw.sourceFleetId === "number" && raw.sourceFleetId >= 1 && raw.sourceFleetId <= 4 ? raw.sourceFleetId : 0;
2524
+ const sourceIds = Array.isArray(raw.originalSourceShipIds) ? raw.originalSourceShipIds.filter((x) => typeof x === "number" && x > 0) : [];
2525
+ if (runnerIds.length === 0 && sourceIds.length === 0) return null;
2526
+ return {
2527
+ version: 1,
2528
+ savedAtMs: typeof raw.savedAtMs === "number" ? raw.savedAtMs : Date.now(),
2529
+ runnerFleetId: raw.runnerFleetId,
2530
+ originalRunnerShipIds: runnerIds,
2531
+ sourceFleetId,
2532
+ originalSourceShipIds: sourceIds
2533
+ };
2534
+ } catch {
2535
+ return null;
2536
+ }
2537
+ }
2538
+ saveKiraRestoreSnapshot(snapshot) {
2539
+ try {
2540
+ import_node_fs2.default.mkdirSync(import_node_path2.default.dirname(this.kiraRestorePath), { recursive: true });
2541
+ const serialized = JSON.stringify(snapshot, null, 2);
2542
+ const tmpPath = `${this.kiraRestorePath}.tmp`;
2543
+ try {
2544
+ import_node_fs2.default.writeFileSync(tmpPath, serialized, "utf8");
2545
+ import_node_fs2.default.renameSync(tmpPath, this.kiraRestorePath);
2546
+ } catch {
2547
+ import_node_fs2.default.writeFileSync(this.kiraRestorePath, serialized, "utf8");
2548
+ }
2549
+ } catch {
2550
+ }
2551
+ }
2552
+ clearKiraRestoreSnapshot() {
2553
+ try {
2554
+ if (import_node_fs2.default.existsSync(this.kiraRestorePath)) {
2555
+ import_node_fs2.default.unlinkSync(this.kiraRestorePath);
2556
+ }
2557
+ } catch {
2558
+ }
2559
+ }
2512
2560
  };
2513
2561
 
2514
2562
  // src/core/scheduler.ts
@@ -2683,8 +2731,8 @@ var ActionScheduler = class {
2683
2731
  };
2684
2732
 
2685
2733
  // src/core/primitives.ts
2686
- function normalizeApiPath(path4) {
2687
- const trimmed = path4.trim();
2734
+ function normalizeApiPath(path5) {
2735
+ const trimmed = path5.trim();
2688
2736
  if (trimmed.startsWith("/kcsapi/")) return trimmed;
2689
2737
  if (trimmed.startsWith("kcsapi/")) return `/${trimmed}`;
2690
2738
  if (trimmed.startsWith("/api_")) return `/kcsapi${trimmed}`;
@@ -5020,12 +5068,12 @@ var BattleSimulator = class {
5020
5068
  }
5021
5069
  return taiha;
5022
5070
  }
5023
- processDayOrSpMidnight(path4, body) {
5071
+ processDayOrSpMidnight(path5, body) {
5024
5072
  try {
5025
- const isCombined = path4.includes("combined_battle") && !path4.includes("/ec_battle") && !path4.includes("/ec_night_to_day");
5026
- const isWater = path4.includes("battle_water");
5027
- const isEach = path4.includes("each_battle") || path4.includes("ec_battle") || path4.includes("ec_night_to_day");
5028
- const isSpMidnight = path4.includes("sp_midnight");
5073
+ const isCombined = path5.includes("combined_battle") && !path5.includes("/ec_battle") && !path5.includes("/ec_night_to_day");
5074
+ const isWater = path5.includes("battle_water");
5075
+ const isEach = path5.includes("each_battle") || path5.includes("ec_battle") || path5.includes("ec_night_to_day");
5076
+ const isSpMidnight = path5.includes("sp_midnight");
5029
5077
  const fNow = toNumArray(body.api_f_nowhps);
5030
5078
  const fMax = toNumArray(body.api_f_maxhps);
5031
5079
  const eNow = toNumArray(body.api_e_nowhps);
@@ -5199,7 +5247,7 @@ var BattleSimulator = class {
5199
5247
  this.state.parseError = err instanceof Error ? err.message : String(err);
5200
5248
  }
5201
5249
  }
5202
- processMidnight(path4, body) {
5250
+ processMidnight(path5, body) {
5203
5251
  try {
5204
5252
  const s = this.state;
5205
5253
  if (Array.isArray(body.api_f_nowhps)) s.fNowHps = toNumArray(body.api_f_nowhps);
@@ -5210,8 +5258,8 @@ var BattleSimulator = class {
5210
5258
  if (Array.isArray(body.api_f_maxhps_combined)) s.fCombinedMaxHps = toNumArray(body.api_f_maxhps_combined);
5211
5259
  if (Array.isArray(body.api_e_nowhps_combined)) s.eCombinedNowHps = toNumArray(body.api_e_nowhps_combined);
5212
5260
  if (Array.isArray(body.api_e_maxhps_combined)) s.eCombinedMaxHps = toNumArray(body.api_e_maxhps_combined);
5213
- const isCombinedNight = path4.includes("combined_battle/midnight_battle");
5214
- const isEcNight = path4.includes("ec_midnight_battle");
5261
+ const isCombinedNight = path5.includes("combined_battle/midnight_battle");
5262
+ const isEcNight = path5.includes("ec_midnight_battle");
5215
5263
  const activeEnemyMain = Array.isArray(body.api_active_deck) && Number(body.api_active_deck[1]) === 2;
5216
5264
  const eTarget = activeEnemyMain && s.eCombinedNowHps.length > 0 ? s.eCombinedNowHps : s.eNowHps;
5217
5265
  if (body.api_friendly_battle?.api_hougeki) {
@@ -6073,6 +6121,62 @@ function planClosedLoopPageMove(currentPage, targetPage, totalPages, options = {
6073
6121
  }
6074
6122
 
6075
6123
  // src/modules/organization.ts
6124
+ var REMODEL_SUFFIX_RE = /(?:\s*(?:mod\.?\s*2|mk\.?\s*ii|zwei|drei|due|tre|two)|(?:航改二[甲乙丙丁戊特護]?|航改|改二[甲乙丙丁戊特航護]?|改[甲乙丙丁戊特航護]?|[甲航]))$/i;
6125
+ var REMODEL_ALIAS_GROUPS = [
6126
+ ["\u97FF", "\u0412\u0435\u0440\u043D\u044B\u0439"],
6127
+ ["\u5927\u9BE8", "\u9F8D\u9CF3"],
6128
+ ["U-511", "\u5442500"],
6129
+ ["Luigi Torelli", "UIT-25", "\u4F0A504"],
6130
+ ["\u6625\u65E5\u4E38", "\u5927\u9DF9"],
6131
+ ["\u516B\u5E61\u4E38", "\u96F2\u9DF9"],
6132
+ ["\u0413\u0430\u043D\u0433\u0443\u0442", "\u041E\u043A\u0442\u044F\u0431\u0440\u044C\u0441\u043A\u0430\u044F \u0440\u0435\u0432\u043E\u043B\u044E\u0446\u0438\u044F"]
6133
+ ];
6134
+ function normalizeShipBaseName(name) {
6135
+ let cur = name.trim();
6136
+ for (let i = 0; i < 3; i++) {
6137
+ const next = cur.replace(REMODEL_SUFFIX_RE, "").trim();
6138
+ if (!next || next === cur) break;
6139
+ cur = next;
6140
+ }
6141
+ return cur;
6142
+ }
6143
+ function shipsMayCollideInSameFleet(a, b) {
6144
+ if (a.id === b.id) return true;
6145
+ if (a.masterId > 0 && a.masterId === b.masterId) return true;
6146
+ const baseA = normalizeShipBaseName(a.name).toLowerCase();
6147
+ const baseB = normalizeShipBaseName(b.name).toLowerCase();
6148
+ if (baseA && baseB && baseA === baseB) return true;
6149
+ for (const group of REMODEL_ALIAS_GROUPS) {
6150
+ const lowerGroup = group.map((g) => g.toLowerCase());
6151
+ if (lowerGroup.includes(baseA) && lowerGroup.includes(baseB)) {
6152
+ return true;
6153
+ }
6154
+ }
6155
+ return false;
6156
+ }
6157
+ function findSafeCrossFleetSpacer(state, excludeIds, avoidFleetIds) {
6158
+ const inAnyFleet = /* @__PURE__ */ new Set();
6159
+ for (const f of Object.values(state.fleets)) {
6160
+ for (const sid of f.shipIds) inAnyFleet.add(sid);
6161
+ }
6162
+ const avoidShips = [];
6163
+ for (const fid of avoidFleetIds) {
6164
+ const f = state.fleets[fid];
6165
+ if (!f) continue;
6166
+ for (const sid of f.shipIds) {
6167
+ if (excludeIds.has(sid)) continue;
6168
+ const s = state.ships[sid];
6169
+ if (s) avoidShips.push(s);
6170
+ }
6171
+ }
6172
+ const candidates = Object.values(state.ships).filter((s) => {
6173
+ if (excludeIds.has(s.id) || inAnyFleet.has(s.id) || s.isRepairing) return false;
6174
+ return !avoidShips.some((other) => shipsMayCollideInSameFleet(s, other));
6175
+ });
6176
+ if (candidates.length === 0) return null;
6177
+ candidates.sort((a, b) => b.level - a.level || a.sortId - b.sortId || a.id - b.id);
6178
+ return candidates[0];
6179
+ }
6076
6180
  function fleetNeedsShipChange(state, fleetId, targetShipIds) {
6077
6181
  const fleet = state.fleets[fleetId];
6078
6182
  const current = fleet?.shipIds ?? [];
@@ -6083,8 +6187,8 @@ function fleetNeedsShipChange(state, fleetId, targetShipIds) {
6083
6187
  }
6084
6188
  return false;
6085
6189
  }
6086
- async function selectOrgFleetTab(fleetId, actions, vision, ctx) {
6087
- if (fleetId === 1) return;
6190
+ async function switchOrgFleetTab(currentTab, fleetId, actions, vision, ctx) {
6191
+ if (fleetId === currentTab) return currentTab;
6088
6192
  const tabPos = {
6089
6193
  x: COORDS.org.fleet1.x + (fleetId - 1) * COORDS.org.fleetOffsetX,
6090
6194
  y: COORDS.org.fleet1.y
@@ -6096,9 +6200,13 @@ async function selectOrgFleetTab(fleetId, actions, vision, ctx) {
6096
6200
  { randomRange: 10, delayMs: 800, desc: `\u7F16\u6210\uFF1A\u5207\u6362\u81F3\u7B2C${fleetId}\u8230\u961F` },
6097
6201
  ctx
6098
6202
  );
6099
- const fleet1StillColored = await vision.checkChroma(COORDS.org.fleet1ActivePixel);
6100
- if (!fleet1StillColored) return;
6203
+ const fleet1Colored = await vision.checkChroma(COORDS.org.fleet1ActivePixel);
6204
+ if (fleetId === 1 ? fleet1Colored : !fleet1Colored) return fleetId;
6101
6205
  }
6206
+ return fleetId;
6207
+ }
6208
+ async function selectOrgFleetTab(fleetId, actions, vision, ctx) {
6209
+ await switchOrgFleetTab(1, fleetId, actions, vision, ctx);
6102
6210
  }
6103
6211
  async function executeClosedLoopPageMove(bridge, actions, currentPage, targetPage, totalPages, controls, ctx) {
6104
6212
  const move = planClosedLoopPageMove(currentPage, targetPage, totalPages, {
@@ -6279,7 +6387,7 @@ async function changeSingleOrgShip(bridge, actions, fleetId, slotIndex, targetSh
6279
6387
  ctx
6280
6388
  );
6281
6389
  }
6282
- async function executeChangeOrganization(bridge, actions, vision, logger, fleetId, targetShipIds, forceClearAll, ctx) {
6390
+ async function executeChangeOrganization(bridge, actions, vision, logger, fleetId, targetShipIds, forceClearAll, ctx, options) {
6283
6391
  const desired = targetShipIds.filter((id) => id > 0);
6284
6392
  if (desired.length === 0) return;
6285
6393
  const unique = new Set(desired);
@@ -6312,7 +6420,7 @@ async function executeChangeOrganization(bridge, actions, vision, logger, fleetI
6312
6420
  await selectOrgFleetTab(fleetId, actions, vision, ctx);
6313
6421
  const curFleet = bridge.getState().fleets[fleetId];
6314
6422
  const curCount = curFleet?.shipIds.length ?? 0;
6315
- if (curCount > 1 && (forceClearAll || curCount > desired.length)) {
6423
+ if (curCount > 1 && (forceClearAll || options?.clearEscortsFirst || curCount > desired.length)) {
6316
6424
  await actions.clickWaitApi(
6317
6425
  COORDS.org.clearShips,
6318
6426
  "/kcsapi/api_req_hensei/change",
@@ -6320,6 +6428,12 @@ async function executeChangeOrganization(bridge, actions, vision, logger, fleetI
6320
6428
  ctx
6321
6429
  );
6322
6430
  }
6431
+ if (pass === 0 && options?.spacerShipId && options.spacerShipId > 0 && bridge.getState().ships[options.spacerShipId]) {
6432
+ const latestFleet = bridge.getState().fleets[fleetId];
6433
+ if (latestFleet?.shipIds[0] !== desired[0] && latestFleet?.shipIds[0] !== options.spacerShipId) {
6434
+ await changeSingleOrgShip(bridge, actions, fleetId, 0, options.spacerShipId, ctx);
6435
+ }
6436
+ }
6323
6437
  for (let i = 0; i < desired.length; i++) {
6324
6438
  const latestFleet = bridge.getState().fleets[fleetId];
6325
6439
  if (latestFleet?.shipIds[i] === desired[i]) continue;
@@ -6336,6 +6450,100 @@ async function executeChangeOrganization(bridge, actions, vision, logger, fleetI
6336
6450
  logger.warn("organization", `\u7B2C${fleetId}\u8230\u961F\u7F16\u6210\u7ECF\u8FC7\u591A\u6B21\u5C1D\u8BD5\u540E\u4ECD\u5B58\u5728\u5DEE\u5F02`);
6337
6451
  }
6338
6452
  }
6453
+ async function executeBatchRestoreOrganizations(bridge, actions, vision, logger, tasks, ctx, options) {
6454
+ const buildActiveTasks = (snap) => {
6455
+ const out = [];
6456
+ for (const t of tasks) {
6457
+ const fleet = snap.fleets[t.fleetId];
6458
+ if (!fleet || fleet.isInSortie || fleet.expedition.state !== 0) {
6459
+ if (fleet && (fleet.isInSortie || fleet.expedition.state !== 0)) {
6460
+ logger.warn("organization", `\u7B2C${t.fleetId}\u8230\u961F\u6B63\u5728\u51FA\u51FB\u6216\u8FDC\u5F81\u4E2D\uFF0C\u8DF3\u8FC7\u81EA\u52A8\u8FD8\u539F\u7F16\u6210`);
6461
+ }
6462
+ continue;
6463
+ }
6464
+ const desired = t.targetShipIds.filter((id) => id > 0 && Boolean(snap.ships[id]));
6465
+ if (desired.length === 0) continue;
6466
+ const blockedByExpedition = desired.some(
6467
+ (sid) => Object.values(snap.fleets).some(
6468
+ (other) => other.id !== t.fleetId && other.expedition.state !== 0 && other.shipIds.includes(sid)
6469
+ )
6470
+ );
6471
+ if (blockedByExpedition) {
6472
+ logger.warn("organization", `\u7B2C${t.fleetId}\u8230\u961F\u90E8\u5206\u539F\u8230\u5A18\u6B63\u5728\u8FDC\u5F81\u4E2D\uFF0C\u6682\u8DF3\u8FC7\u8FD8\u539F`);
6473
+ continue;
6474
+ }
6475
+ out.push({ fleetId: t.fleetId, desired, forceClearAll: Boolean(t.forceClearAll) });
6476
+ }
6477
+ return out;
6478
+ };
6479
+ const seenStates = /* @__PURE__ */ new Set();
6480
+ for (let pass = 0; pass < 4; pass++) {
6481
+ const snap = bridge.getState();
6482
+ const activeTasks = buildActiveTasks(snap);
6483
+ if (activeTasks.length === 0) return;
6484
+ const pendingTasks = activeTasks.filter((t) => fleetNeedsShipChange(snap, t.fleetId, t.desired));
6485
+ if (pendingTasks.length === 0) return;
6486
+ const sig = activeTasks.map((t) => `${t.fleetId}:${(snap.fleets[t.fleetId]?.shipIds ?? []).join(",")}`).join("|");
6487
+ if (seenStates.has(sig)) {
6488
+ throw new Error(`\u6279\u91CF\u8FD8\u539F\u7F16\u6210\u8FDB\u5165\u91CD\u590D\u72B6\u6001 (${sig})\uFF0C\u5DF2\u4E2D\u6B62\u9632\u6B62\u6B7B\u5FAA\u73AF`);
6489
+ }
6490
+ seenStates.add(sig);
6491
+ await actions.clickWaitApi(
6492
+ COORDS.organization,
6493
+ "/kcsapi/api_get_member/preset_deck",
6494
+ { randomRange: 30, delayMs: 1400, desc: "\u7F16\u6210\uFF1A\u8FDB\u5165\u7F16\u6210\u754C\u9762\u8FD8\u539F\u539F\u7F16\u6210" },
6495
+ ctx
6496
+ );
6497
+ let currentTab = 1;
6498
+ const runnerClearId = options?.clearRunnerEscortsFleetId;
6499
+ if (runnerClearId && runnerClearId >= 1 && runnerClearId <= 4) {
6500
+ const liveRunner = bridge.getState().fleets[runnerClearId];
6501
+ const runnerTask = activeTasks.find((t) => t.fleetId === runnerClearId);
6502
+ const runnerAlreadyRestored = runnerTask && !fleetNeedsShipChange(bridge.getState(), runnerClearId, runnerTask.desired);
6503
+ if (liveRunner && liveRunner.shipIds.length > 1 && !runnerAlreadyRestored) {
6504
+ currentTab = await switchOrgFleetTab(currentTab, runnerClearId, actions, vision, ctx);
6505
+ await actions.clickWaitApi(
6506
+ COORDS.org.clearShips,
6507
+ "/kcsapi/api_req_hensei/change",
6508
+ { randomRange: 14, delayMs: 1100, desc: `\u7F16\u6210\uFF1A\u89E3\u9664\u7B2C${runnerClearId}\u8230\u961F\u4E34\u65F6\u4F34\u968F\u8230` },
6509
+ ctx
6510
+ );
6511
+ }
6512
+ }
6513
+ for (const task of activeTasks) {
6514
+ const liveSnap = bridge.getState();
6515
+ if (!fleetNeedsShipChange(liveSnap, task.fleetId, task.desired)) continue;
6516
+ currentTab = await switchOrgFleetTab(currentTab, task.fleetId, actions, vision, ctx);
6517
+ const curFleet = bridge.getState().fleets[task.fleetId];
6518
+ const curCount = curFleet?.shipIds.length ?? 0;
6519
+ if (curCount > 1 && (task.forceClearAll || curCount > task.desired.length)) {
6520
+ await actions.clickWaitApi(
6521
+ COORDS.org.clearShips,
6522
+ "/kcsapi/api_req_hensei/change",
6523
+ { randomRange: 14, delayMs: 1100, desc: `\u7F16\u6210\uFF1A\u6E05\u7406\u7B2C${task.fleetId}\u8230\u961F\u591A\u4F59\u69FD\u4F4D` },
6524
+ ctx
6525
+ );
6526
+ }
6527
+ for (let i = 0; i < task.desired.length; i++) {
6528
+ const latestFleet = bridge.getState().fleets[task.fleetId];
6529
+ if (latestFleet?.shipIds[i] === task.desired[i]) continue;
6530
+ await changeSingleOrgShip(bridge, actions, task.fleetId, i, task.desired[i], ctx);
6531
+ }
6532
+ }
6533
+ await actions.clickWaitApi(
6534
+ COORDS.homeport,
6535
+ "/kcsapi/api_port/port",
6536
+ { randomRange: 40, delayMs: 1500, desc: "\u7F16\u6210\uFF1A\u8FD4\u56DE\u6BCD\u6E2F\u9A8C\u8BC1\u8FD8\u539F\u7ED3\u679C" },
6537
+ ctx
6538
+ );
6539
+ }
6540
+ const finalSnap = bridge.getState();
6541
+ for (const t of buildActiveTasks(finalSnap)) {
6542
+ if (fleetNeedsShipChange(finalSnap, t.fleetId, t.desired)) {
6543
+ logger.warn("organization", `\u7B2C${t.fleetId}\u8230\u961F\u8FD8\u539F\u7F16\u6210\u7ECF\u8FC7\u591A\u6B21\u5C1D\u8BD5\u540E\u4ECD\u5B58\u5728\u5DEE\u5F02`);
6544
+ }
6545
+ }
6546
+ }
6339
6547
  async function executeClearShipEquips(bridge, actions, fleetId, shipIndex, ctx) {
6340
6548
  const snap = bridge.getState();
6341
6549
  const shipId = snap.fleets[fleetId]?.shipIds[shipIndex];
@@ -7013,13 +7221,40 @@ var AutoOrganizationModule = class extends AutomationModule {
7013
7221
  };
7014
7222
 
7015
7223
  // src/modules/kira.ts
7016
- function selectKiraEscortShip(state, flagship, cfg) {
7224
+ var KIRA_START_COND = 50;
7225
+ var KIRA_MAX_TARGET_COND = 85;
7226
+ function getEffectiveKiraTargetCond(rawTargetCond) {
7227
+ const val = typeof rawTargetCond === "number" && Number.isFinite(rawTargetCond) ? Math.round(rawTargetCond) : 75;
7228
+ return Math.max(KIRA_START_COND, Math.min(KIRA_MAX_TARGET_COND, val));
7229
+ }
7230
+ function getKiraThresholds(cfg, fleetId) {
7231
+ const idx = fleetId - 1;
7232
+ const targetCond = getEffectiveKiraTargetCond(cfg.kiraTargetCond[idx]);
7233
+ const isSupportMode = Boolean(cfg.kiraForSupport[idx]);
7234
+ const triggerCond = isSupportMode ? targetCond : KIRA_START_COND;
7235
+ return { triggerCond, targetCond, isSupportMode };
7236
+ }
7237
+ function canUseFleet1AsKiraRunner(state) {
7238
+ if (state.combinedType > 0) {
7239
+ return { ok: false, reason: "\u8054\u5408\u8230\u961F\u7F16\u6210\u4E2D\uFF0C\u6682\u7F13\u501F\u7528\u7B2C1\u8230\u961F\u5237\u95EA" };
7240
+ }
7241
+ const f1 = state.fleets[1];
7242
+ if (!f1 || f1.shipIds.length === 0) {
7243
+ return { ok: false, reason: "\u7B2C1\u8230\u961F\u4E3A\u7A7A\uFF0C\u6682\u65E0\u6CD5\u4EE3\u5237" };
7244
+ }
7245
+ if (f1.isInSortie || f1.expedition.state !== 0) {
7246
+ return { ok: false, reason: "\u7B2C1\u8230\u961F\u6B63\u5FD9\uFF0C\u7B49\u5F85\u7A7A\u95F2\u540E\u518D\u4EE3\u5237" };
7247
+ }
7248
+ return { ok: true };
7249
+ }
7250
+ function selectKiraEscortShip(state, flagship, cfg, reservedShipIds) {
7017
7251
  const inFleetIds = /* @__PURE__ */ new Set();
7018
7252
  for (const f of Object.values(state.fleets)) {
7019
7253
  for (const sid of f.shipIds) inFleetIds.add(sid);
7020
7254
  }
7021
7255
  const candidates = Object.values(state.ships).filter((s) => {
7022
7256
  if (s.id === flagship.id) return false;
7257
+ if (reservedShipIds?.has(s.id)) return false;
7023
7258
  if (s.stype !== 2) return false;
7024
7259
  if (s.isRepairing || inFleetIds.has(s.id)) return false;
7025
7260
  if (cfg.kiraExcludeLockedEscort && s.locked) return false;
@@ -7028,35 +7263,157 @@ function selectKiraEscortShip(state, flagship, cfg) {
7028
7263
  if (Math.floor(s.hp / Math.max(1, s.maxHp) * 100) < cfg.kiraEscortMinHpPercent) return false;
7029
7264
  if (s.maxFuel > 0 && s.fuel / s.maxFuel < 0.3) return false;
7030
7265
  if (s.maxBull > 0 && s.bull / s.maxBull < 0.3) return false;
7031
- if (flagship.name.includes(s.name) || s.name.includes(flagship.name)) return false;
7032
- if (flagship.masterId === 147 && s.name.includes("\u97FF")) return false;
7266
+ if (shipsMayCollideInSameFleet(flagship, s)) return false;
7033
7267
  return true;
7034
7268
  });
7035
7269
  if (candidates.length === 0) return null;
7036
7270
  candidates.sort((a, b) => a.level - b.level || b.hp - a.hp || a.id - b.id);
7037
7271
  return candidates[0];
7038
7272
  }
7273
+ function buildRestoreTasksFromSnapshot(state, snap, includeRunnerFleet = true) {
7274
+ const tasks = [];
7275
+ if (snap.sourceFleetId >= 1 && snap.sourceFleetId <= 4 && snap.originalSourceShipIds.length > 0) {
7276
+ const existingSource = snap.originalSourceShipIds.filter((id) => Boolean(state.ships[id]));
7277
+ if (existingSource.length > 0 && fleetNeedsShipChange(state, snap.sourceFleetId, existingSource)) {
7278
+ tasks.push({
7279
+ fleetId: snap.sourceFleetId,
7280
+ targetShipIds: existingSource,
7281
+ forceClearAll: false
7282
+ });
7283
+ }
7284
+ }
7285
+ if (includeRunnerFleet && snap.runnerFleetId >= 1 && snap.runnerFleetId <= 4 && snap.runnerFleetId !== snap.sourceFleetId && snap.originalRunnerShipIds.length > 0) {
7286
+ const existingRunner = snap.originalRunnerShipIds.filter((id) => Boolean(state.ships[id]));
7287
+ if (existingRunner.length > 0 && fleetNeedsShipChange(state, snap.runnerFleetId, existingRunner)) {
7288
+ tasks.push({
7289
+ fleetId: snap.runnerFleetId,
7290
+ targetShipIds: existingRunner,
7291
+ forceClearAll: false
7292
+ });
7293
+ }
7294
+ }
7295
+ return tasks;
7296
+ }
7039
7297
  var AutoKiraModule = class extends AutomationModule {
7040
- constructor(runtime, practiceNeedsAction, onKiraSortieFinished) {
7298
+ constructor(runtime, practiceNeedsAction, onKiraSortieFinished, restorePersistence) {
7041
7299
  super(runtime);
7042
7300
  this.practiceNeedsAction = practiceNeedsAction;
7043
7301
  this.onKiraSortieFinished = onKiraSortieFinished;
7302
+ this.restorePersistence = restorePersistence;
7303
+ const loaded = this.restorePersistence?.load() ?? null;
7304
+ if (loaded) {
7305
+ this.pendingRestore = loaded;
7306
+ if (loaded.runnerFleetId === 1 && loaded.originalRunnerShipIds.length > 0) {
7307
+ this.originalRunnerShipIds = [...loaded.originalRunnerShipIds];
7308
+ }
7309
+ }
7044
7310
  }
7045
7311
  id = "kira";
7046
7312
  category = "kira";
7047
7313
  displayName = "\u81EA\u52A8\u5237\u95EA";
7048
- currentFleet = -1;
7049
- originalShipIds = [];
7314
+ /** Fleet whose ships are currently being sparkled (1..4, or -1 when idle). */
7315
+ sourceFleet = -1;
7316
+ /** Fleet executing 1-1 sorties (1 in Fleet-1 cross-fleet mode, otherwise equals `sourceFleet`). */
7317
+ runnerFleet = -1;
7318
+ originalSourceShipIds = [];
7319
+ originalRunnerShipIds = [];
7050
7320
  kiraQueue = [];
7051
7321
  activePlanJobId = "";
7322
+ pendingRestore = null;
7323
+ /**
7324
+ * Returns the source fleet ID currently being sparkled (used by AutoExpedition
7325
+ * to prevent dispatching that fleet while its ships are being sparkled on Fleet 1).
7326
+ */
7052
7327
  getCurrentFleet() {
7053
- return this.currentFleet;
7328
+ return this.sourceFleet;
7329
+ }
7330
+ getRunnerFleet() {
7331
+ return this.runnerFleet;
7332
+ }
7333
+ /**
7334
+ * True whenever AutoKira currently owns Fleet 1 (either actively sparkling on Fleet 1
7335
+ * or holding an unrestored Fleet 1 snapshot) so AutoPractice yields instead of colliding.
7336
+ */
7337
+ isUsingFleet1() {
7338
+ if (this.sourceFleet >= 1 && this.runnerFleet === 1) return true;
7339
+ const state = this.runtime.bridge.getState();
7340
+ if (this.pendingRestore && this.pendingRestore.runnerFleetId === 1) {
7341
+ return this.syncAndCheckPendingRestore(state);
7342
+ }
7343
+ return false;
7344
+ }
7345
+ getPendingRestoreSnapshot() {
7346
+ const state = this.runtime.bridge.getState();
7347
+ if (state.loaded) {
7348
+ this.syncAndCheckPendingRestore(state);
7349
+ }
7350
+ return this.pendingRestore ? {
7351
+ ...this.pendingRestore,
7352
+ originalRunnerShipIds: [...this.pendingRestore.originalRunnerShipIds],
7353
+ originalSourceShipIds: [...this.pendingRestore.originalSourceShipIds]
7354
+ } : null;
7355
+ }
7356
+ discardPendingRestoreSnapshot() {
7357
+ this.pendingRestore = null;
7358
+ if (this.sourceFleet < 1) {
7359
+ this.originalRunnerShipIds = [];
7360
+ this.originalSourceShipIds = [];
7361
+ this.runnerFleet = -1;
7362
+ }
7363
+ this.restorePersistence?.clear();
7364
+ this.runtime.notifyStateChanged();
7054
7365
  }
7055
7366
  setPlanJobId(jobId) {
7056
7367
  this.activePlanJobId = jobId;
7057
7368
  }
7369
+ getReservedShipIdSet() {
7370
+ const set = /* @__PURE__ */ new Set();
7371
+ for (const id of this.originalSourceShipIds) set.add(id);
7372
+ for (const id of this.originalRunnerShipIds) set.add(id);
7373
+ for (const id of this.kiraQueue) set.add(id);
7374
+ if (this.pendingRestore) {
7375
+ for (const id of this.pendingRestore.originalSourceShipIds) set.add(id);
7376
+ for (const id of this.pendingRestore.originalRunnerShipIds) set.add(id);
7377
+ }
7378
+ return set;
7379
+ }
7058
7380
  isShipReserved(shipId) {
7059
- return this.originalShipIds.includes(shipId) || this.kiraQueue.includes(shipId);
7381
+ return this.getReservedShipIdSet().has(shipId);
7382
+ }
7383
+ saveRestoreSnapshot(snap) {
7384
+ this.pendingRestore = {
7385
+ ...snap,
7386
+ originalRunnerShipIds: [...snap.originalRunnerShipIds],
7387
+ originalSourceShipIds: [...snap.originalSourceShipIds]
7388
+ };
7389
+ this.restorePersistence?.save(this.pendingRestore);
7390
+ this.runtime.notifyStateChanged();
7391
+ }
7392
+ clearRestoreSnapshot() {
7393
+ this.pendingRestore = null;
7394
+ this.restorePersistence?.clear();
7395
+ this.runtime.notifyStateChanged();
7396
+ }
7397
+ /**
7398
+ * Verifies whether `pendingRestore` still differs from live game state.
7399
+ * Automatically clears stale snapshots when fleets already match (e.g. solo Fleet 1
7400
+ * restored automatically by a single cross-fleet swap, or manual user restore).
7401
+ */
7402
+ syncAndCheckPendingRestore(state) {
7403
+ if (!this.pendingRestore) return false;
7404
+ if (!state.loaded) return true;
7405
+ const tasks = buildRestoreTasksFromSnapshot(state, this.pendingRestore, true);
7406
+ if (tasks.length === 0) {
7407
+ this.pendingRestore = null;
7408
+ if (this.sourceFleet < 1) {
7409
+ this.originalRunnerShipIds = [];
7410
+ this.originalSourceShipIds = [];
7411
+ this.runnerFleet = -1;
7412
+ }
7413
+ this.restorePersistence?.clear();
7414
+ return false;
7415
+ }
7416
+ return true;
7060
7417
  }
7061
7418
  doesFleetViolateKiraCondition(fleetId) {
7062
7419
  const state = this.runtime.bridge.getState();
@@ -7066,9 +7423,8 @@ var AutoKiraModule = class extends AutomationModule {
7066
7423
  const idx = fleetId - 1;
7067
7424
  const required = Math.min(cfg.kiraCount[idx] ?? 6, fleet.shipIds.length);
7068
7425
  if (required <= 0) return false;
7069
- const useSupportThreshold = fleetId === 1 || Boolean(cfg.kiraForSupport[idx]);
7070
- const threshold = useSupportThreshold ? cfg.kiraTargetCond[idx] ?? 75 : 50;
7071
- const readyCount = fleet.shipIds.filter((sid) => (state.ships[sid]?.cond ?? 0) >= threshold).length;
7426
+ const { triggerCond } = getKiraThresholds(cfg, fleetId);
7427
+ const readyCount = fleet.shipIds.filter((sid) => (state.ships[sid]?.cond ?? 0) >= triggerCond).length;
7072
7428
  return readyCount < required;
7073
7429
  }
7074
7430
  needsKiraForFleet(fleetId) {
@@ -7080,6 +7436,10 @@ var AutoKiraModule = class extends AutomationModule {
7080
7436
  const fleet = state.fleets[fleetId];
7081
7437
  if (!fleet || fleet.shipIds.length === 0) return false;
7082
7438
  if (fleet.isInSortie || fleet.expedition.state !== 0) return false;
7439
+ if (fleetId > 1 && cfg.kiraUseFleet1) {
7440
+ const check = canUseFleet1AsKiraRunner(state);
7441
+ if (!check.ok) return false;
7442
+ }
7083
7443
  const advanceMs = Math.max(0, this.runtime.getSettings().general.operationAdvanceSec) * 1e3;
7084
7444
  const now = Date.now();
7085
7445
  const hasBlockingRepair = fleet.shipIds.some((sid) => {
@@ -7093,81 +7453,263 @@ var AutoKiraModule = class extends AutomationModule {
7093
7453
  }
7094
7454
  needsAction() {
7095
7455
  if (!this.enabled) return false;
7096
- if (this.currentFleet >= 1) return true;
7456
+ if (this.sourceFleet >= 1) return true;
7457
+ const state = this.runtime.bridge.getState();
7458
+ if (this.pendingRestore && this.syncAndCheckPendingRestore(state)) return true;
7097
7459
  return [2, 3, 4, 1].some((fid) => this.needsKiraForFleet(fid));
7098
7460
  }
7099
7461
  requestKiraFleet(fleetId) {
7100
- if (this.currentFleet >= 1) return;
7462
+ if (this.sourceFleet >= 1) return;
7101
7463
  const state = this.runtime.bridge.getState();
7102
7464
  const fleet = state.fleets[fleetId];
7103
7465
  if (!fleet || fleet.shipIds.length === 0) return;
7104
7466
  const cfg = this.runtime.getSettings().expedition;
7105
7467
  const idx = fleetId - 1;
7106
7468
  const required = Math.min(cfg.kiraCount[idx] ?? 6, fleet.shipIds.length);
7107
- const useSupportThreshold = fleetId === 1 || Boolean(cfg.kiraForSupport[idx]);
7108
- const triggerThreshold = useSupportThreshold ? cfg.kiraTargetCond[idx] ?? 75 : 50;
7469
+ const { triggerCond, targetCond, isSupportMode } = getKiraThresholds(cfg, fleetId);
7109
7470
  const ships = fleet.shipIds.map((sid) => state.ships[sid]).filter((s) => Boolean(s));
7110
- const alreadyOk = ships.filter((s) => s.cond >= triggerThreshold).length;
7471
+ const alreadyOk = ships.filter((s) => s.cond >= triggerCond).length;
7111
7472
  const shortfall = Math.max(0, required - alreadyOk);
7112
7473
  if (shortfall <= 0) return;
7113
- const needing = ships.filter((s) => s.cond < triggerThreshold);
7474
+ const useCrossFleet1 = Boolean(cfg.kiraUseFleet1) && fleetId > 1;
7475
+ if (useCrossFleet1) {
7476
+ const check = canUseFleet1AsKiraRunner(state);
7477
+ if (!check.ok) {
7478
+ this.setStatus(check.reason ?? "\u7B2C1\u8230\u961F\u6682\u4E0D\u53EF\u7528", "waiting");
7479
+ return;
7480
+ }
7481
+ }
7482
+ const needing = ships.filter((s) => s.cond < triggerCond);
7114
7483
  if (cfg.kiraOrder[idx] === "level") {
7115
7484
  needing.sort((a, b) => b.level - a.level || a.cond - b.cond);
7116
7485
  }
7117
- this.currentFleet = fleetId;
7118
- this.originalShipIds = [...fleet.shipIds];
7486
+ const nextRunner = useCrossFleet1 ? 1 : fleetId;
7487
+ this.sourceFleet = fleetId;
7488
+ this.runnerFleet = nextRunner;
7489
+ this.originalSourceShipIds = [...fleet.shipIds];
7490
+ if (useCrossFleet1) {
7491
+ if (this.pendingRestore?.runnerFleetId === 1 && this.pendingRestore.originalRunnerShipIds.length > 0) {
7492
+ this.originalRunnerShipIds = [...this.pendingRestore.originalRunnerShipIds];
7493
+ } else {
7494
+ this.originalRunnerShipIds = [...state.fleets[1]?.shipIds ?? []];
7495
+ }
7496
+ } else {
7497
+ this.originalRunnerShipIds = [];
7498
+ }
7119
7499
  this.kiraQueue = needing.slice(0, shortfall).map((s) => s.id);
7500
+ this.saveRestoreSnapshot({
7501
+ version: 1,
7502
+ savedAtMs: Date.now(),
7503
+ runnerFleetId: nextRunner,
7504
+ originalRunnerShipIds: useCrossFleet1 ? this.originalRunnerShipIds : this.originalSourceShipIds,
7505
+ sourceFleetId: fleetId,
7506
+ originalSourceShipIds: this.originalSourceShipIds
7507
+ });
7508
+ const modeLabel = isSupportMode ? `\u652F\u63F4\u6A21\u5F0F <${triggerCond}` : `\u5E38\u89C4 <${KIRA_START_COND}`;
7509
+ const prefix = useCrossFleet1 ? `\u5F00\u59CB\u5728\u7B2C1\u8230\u961F\u4E3A\u7B2C${fleetId}\u8230\u961F\u8DE8\u961F\u5237\u95EA (\u4E0D\u89E3\u6563\u539F\u961F \xB7 ${modeLabel} \u2192 \u76EE\u6807 ${targetCond})` : `\u5F00\u59CB\u4E3A\u7B2C${fleetId}\u8230\u961F\u5237\u95EA (${modeLabel} \u2192 \u76EE\u6807 ${targetCond})`;
7120
7510
  this.runtime.logger.info(
7121
7511
  "kira",
7122
- `\u5F00\u59CB\u4E3A\u7B2C${fleetId}\u8230\u961F\u5237\u95EA\uFF0C\u5F85\u5237 ${this.kiraQueue.length} \u8258: ${needing.slice(0, shortfall).map((s) => s.name).join(", ")}`
7512
+ `${prefix}\uFF0C\u5F85\u5237 ${this.kiraQueue.length} \u8258: ${needing.slice(0, shortfall).map((s) => `${s.name}(${s.cond})`).join(", ")}`
7123
7513
  );
7124
7514
  }
7515
+ /**
7516
+ * Manually restore any persisted unrestored fleets (usable from UI even when AutoKira is toggled OFF).
7517
+ */
7518
+ async restoreSavedFleetsNow() {
7519
+ const state = this.runtime.bridge.getState();
7520
+ if (!state.loaded || state.inSortie) return false;
7521
+ if (!this.pendingRestore) return false;
7522
+ const snap = this.pendingRestore;
7523
+ const tasks = buildRestoreTasksFromSnapshot(state, snap, true);
7524
+ if (tasks.length === 0) {
7525
+ this.sourceFleet = -1;
7526
+ this.runnerFleet = -1;
7527
+ this.originalSourceShipIds = [];
7528
+ this.originalRunnerShipIds = [];
7529
+ this.kiraQueue = [];
7530
+ this.clearRestoreSnapshot();
7531
+ return true;
7532
+ }
7533
+ if (!this.runtime.scheduler.canAcquire(this.id)) return false;
7534
+ await this.runLocked(async (ctx) => {
7535
+ const fleetDesc = tasks.map((t) => `\u7B2C${t.fleetId}\u8230\u961F`).join("\u3001");
7536
+ this.setStatus(`\u6B63\u5728\u8FD8\u539F\u5237\u95EA\u539F\u7F16\u6210 (${fleetDesc})`);
7537
+ await executeBatchRestoreOrganizations(
7538
+ this.runtime.bridge,
7539
+ this.runtime.actions,
7540
+ this.runtime.vision,
7541
+ this.runtime.logger,
7542
+ tasks,
7543
+ ctx,
7544
+ {
7545
+ clearRunnerEscortsFleetId: snap.sourceFleetId > 0 && snap.runnerFleetId !== snap.sourceFleetId ? snap.runnerFleetId : void 0
7546
+ }
7547
+ );
7548
+ this.sourceFleet = -1;
7549
+ this.runnerFleet = -1;
7550
+ this.originalSourceShipIds = [];
7551
+ this.originalRunnerShipIds = [];
7552
+ this.kiraQueue = [];
7553
+ this.clearRestoreSnapshot();
7554
+ this.runtime.logger.success("kira", `\u5DF2\u8FD8\u539F\u539F\u7F16\u6210 (${fleetDesc})`);
7555
+ this.setStatus("\u539F\u7F16\u6210\u5DF2\u8FD8\u539F", "idle");
7556
+ });
7557
+ return true;
7558
+ }
7559
+ /**
7560
+ * Builds cross-fleet swap options when borrowing Fleet 1 to sparkle a ship from Fleets 2~4:
7561
+ * - Clears Fleet 1 escorts with 1 click if slot 1 is not already our desired escort
7562
+ * - Inserts a safe idle port spacer ship ONLY if Fleet 1's outgoing flagship shares a ship
7563
+ * lineage with another ship remaining in `sourceFleet` (preventing KanColle swap rejection)
7564
+ */
7565
+ computeCrossFleetSwapOptions(state, flagship, desiredFleetIds) {
7566
+ if (this.runnerFleet === this.sourceFleet) {
7567
+ return { clearEscortsFirst: false };
7568
+ }
7569
+ const curRunnerIds = state.fleets[this.runnerFleet]?.shipIds ?? [];
7570
+ const desiredEscortId = desiredFleetIds[1];
7571
+ const clearEscortsFirst = curRunnerIds.length > 1 && (desiredEscortId === void 0 || curRunnerIds[1] !== desiredEscortId);
7572
+ const outgoingId = curRunnerIds[0];
7573
+ if (!outgoingId || outgoingId === flagship.id) {
7574
+ return { clearEscortsFirst };
7575
+ }
7576
+ const outgoingShip = state.ships[outgoingId];
7577
+ if (!outgoingShip) return { clearEscortsFirst };
7578
+ const holderFleet = Object.values(state.fleets).find(
7579
+ (f) => f.id !== this.runnerFleet && f.shipIds.includes(flagship.id)
7580
+ );
7581
+ if (!holderFleet) return { clearEscortsFirst };
7582
+ const collidesWithHolder = holderFleet.shipIds.some((sid) => {
7583
+ if (sid === flagship.id) return false;
7584
+ const other = state.ships[sid];
7585
+ return Boolean(other && shipsMayCollideInSameFleet(outgoingShip, other));
7586
+ });
7587
+ if (!collidesWithHolder) {
7588
+ return { clearEscortsFirst };
7589
+ }
7590
+ const exclude = /* @__PURE__ */ new Set([outgoingId, flagship.id, ...desiredFleetIds]);
7591
+ const spacer = findSafeCrossFleetSpacer(state, exclude, [holderFleet.id, this.runnerFleet]);
7592
+ if (spacer) {
7593
+ this.runtime.logger.info(
7594
+ "kira",
7595
+ `\u68C0\u6D4B\u5230\u8DE8\u961F\u540C\u540D\u8230\u51B2\u7A81 (${outgoingShip.name} \u2194 \u7B2C${holderFleet.id}\u8230\u961F)\uFF0C\u81EA\u52A8\u501F\u7528 ${spacer.name} \u4E2D\u8F6C\u907F\u514D\u89E3\u6563\u539F\u961F`
7596
+ );
7597
+ return { clearEscortsFirst, spacerShipId: spacer.id };
7598
+ }
7599
+ return { clearEscortsFirst };
7600
+ }
7125
7601
  async tick() {
7126
7602
  if (!this.enabled || !this.runtime.scheduler.canAcquire(this.id)) return;
7127
- if (this.practiceNeedsAction()) return;
7603
+ if (!this.isUsingFleet1() && this.practiceNeedsAction()) return;
7128
7604
  const state = this.runtime.bridge.getState();
7129
7605
  if (!state.loaded || state.inSortie) return;
7130
- if (this.currentFleet < 1) {
7131
- for (const fid of [2, 3, 4, 1]) {
7132
- if (this.needsKiraForFleet(fid)) {
7133
- this.requestKiraFleet(fid);
7134
- break;
7606
+ const settings = this.runtime.getSettings();
7607
+ const cfg = settings.expedition;
7608
+ if (this.sourceFleet < 1) {
7609
+ if (this.pendingRestore && this.syncAndCheckPendingRestore(state)) {
7610
+ const snap = this.pendingRestore;
7611
+ if (snap.sourceFleetId > 0) {
7612
+ await this.restoreSavedFleetsNow();
7613
+ return;
7614
+ }
7615
+ if (snap.runnerFleetId === 1 && cfg.kiraUseFleet1 && canUseFleet1AsKiraRunner(state).ok) {
7616
+ for (const fid of [2, 3, 4]) {
7617
+ if (this.needsKiraForFleet(fid)) {
7618
+ this.requestKiraFleet(fid);
7619
+ break;
7620
+ }
7621
+ }
7622
+ }
7623
+ if (this.sourceFleet < 1) {
7624
+ await this.restoreSavedFleetsNow();
7625
+ return;
7626
+ }
7627
+ } else {
7628
+ for (const fid of [2, 3, 4, 1]) {
7629
+ if (this.needsKiraForFleet(fid)) {
7630
+ this.requestKiraFleet(fid);
7631
+ break;
7632
+ }
7633
+ }
7634
+ if (this.sourceFleet < 1) {
7635
+ this.setStatus("\u6682\u65E0\u9700\u8981\u5237\u95EA\u7684\u8230\u961F", "idle");
7636
+ return;
7135
7637
  }
7136
- }
7137
- if (this.currentFleet < 1) {
7138
- this.setStatus("\u6682\u65E0\u9700\u8981\u5237\u95EA\u7684\u8230\u961F", "idle");
7139
- return;
7140
7638
  }
7141
7639
  }
7142
- const settings = this.runtime.getSettings();
7143
- const cfg = settings.expedition;
7144
- const targetCond = Math.min(85, cfg.kiraTargetCond[this.currentFleet - 1] ?? 75);
7640
+ const targetCond = getEffectiveKiraTargetCond(cfg.kiraTargetCond[this.sourceFleet - 1]);
7145
7641
  const advanceMs = Math.max(0, settings.general.operationAdvanceSec) * 1e3;
7146
7642
  this.kiraQueue = this.kiraQueue.filter((sid) => {
7147
7643
  const s = state.ships[sid];
7148
7644
  return Boolean(s && s.cond < targetCond);
7149
7645
  });
7150
7646
  if (this.kiraQueue.length === 0) {
7151
- const fleetId2 = this.currentFleet;
7152
- const restoreIds = [...this.originalShipIds];
7647
+ const finishedSource = this.sourceFleet;
7648
+ const activeRunner2 = this.runnerFleet;
7649
+ const isCrossFleet = activeRunner2 !== finishedSource;
7650
+ const hasAnotherCrossFleet = isCrossFleet && activeRunner2 === 1 && Boolean(cfg.kiraUseFleet1) && state.combinedType === 0 && [2, 3, 4].some((fid) => fid !== finishedSource && this.needsKiraForFleet(fid));
7651
+ const restoreSnap = {
7652
+ version: 1,
7653
+ savedAtMs: Date.now(),
7654
+ runnerFleetId: activeRunner2,
7655
+ originalRunnerShipIds: isCrossFleet ? [...this.originalRunnerShipIds] : [...this.originalSourceShipIds],
7656
+ sourceFleetId: finishedSource,
7657
+ originalSourceShipIds: [...this.originalSourceShipIds]
7658
+ };
7659
+ const tasks = buildRestoreTasksFromSnapshot(state, restoreSnap, !hasAnotherCrossFleet);
7153
7660
  await this.runLocked(async (ctx) => {
7154
- this.setStatus(`\u7B2C${fleetId2}\u8230\u961F\u5237\u95EA\u5B8C\u6BD5\uFF0C\u6062\u590D\u539F\u7F16\u6210`);
7155
- await executeChangeOrganization(
7156
- this.runtime.bridge,
7157
- this.runtime.actions,
7158
- this.runtime.vision,
7159
- this.runtime.logger,
7160
- fleetId2,
7161
- restoreIds,
7162
- true,
7163
- ctx
7164
- );
7165
- this.currentFleet = -1;
7166
- this.originalShipIds = [];
7661
+ if (tasks.length > 0) {
7662
+ this.setStatus(
7663
+ hasAnotherCrossFleet ? `\u7B2C${finishedSource}\u8230\u961F\u5237\u95EA\u5B8C\u6BD5\uFF0C\u6700\u5C0F\u5DEE\u5206\u8FD8\u539F\u539F\u961F` : isCrossFleet ? `\u7B2C${finishedSource}\u8230\u961F\u5237\u95EA\u5B8C\u6BD5\uFF0C\u8FD8\u539F\u7B2C${finishedSource}\u961F\u4E0E\u7B2C1\u961F` : `\u7B2C${finishedSource}\u8230\u961F\u5237\u95EA\u5B8C\u6BD5\uFF0C\u6062\u590D\u539F\u7F16\u6210`
7664
+ );
7665
+ await executeBatchRestoreOrganizations(
7666
+ this.runtime.bridge,
7667
+ this.runtime.actions,
7668
+ this.runtime.vision,
7669
+ this.runtime.logger,
7670
+ tasks,
7671
+ ctx,
7672
+ { clearRunnerEscortsFleetId: isCrossFleet ? activeRunner2 : void 0 }
7673
+ );
7674
+ }
7675
+ this.sourceFleet = -1;
7676
+ this.runnerFleet = -1;
7677
+ this.originalSourceShipIds = [];
7167
7678
  this.kiraQueue = [];
7168
- this.runtime.logger.success("kira", `\u7B2C${fleetId2}\u8230\u961F\u5237\u95EA\u5B8C\u6210\u5E76\u6062\u590D\u539F\u7F16\u6210`);
7679
+ if (hasAnotherCrossFleet && isCrossFleet) {
7680
+ const postState = this.runtime.bridge.getState();
7681
+ const runnerStillNeedsRestore = fleetNeedsShipChange(
7682
+ postState,
7683
+ activeRunner2,
7684
+ this.originalRunnerShipIds.filter((id) => Boolean(postState.ships[id]))
7685
+ );
7686
+ if (runnerStillNeedsRestore) {
7687
+ this.saveRestoreSnapshot({
7688
+ version: 1,
7689
+ savedAtMs: Date.now(),
7690
+ runnerFleetId: activeRunner2,
7691
+ originalRunnerShipIds: [...this.originalRunnerShipIds],
7692
+ sourceFleetId: 0,
7693
+ originalSourceShipIds: []
7694
+ });
7695
+ } else {
7696
+ this.originalRunnerShipIds = [];
7697
+ this.clearRestoreSnapshot();
7698
+ }
7699
+ this.runtime.logger.success(
7700
+ "kira",
7701
+ `\u7B2C${finishedSource}\u8230\u961F\u5237\u95EA\u5B8C\u6210\u5E76\u5DF2\u8FD8\u539F\uFF08\u7EE7\u7EED\u4FDD\u7559\u7B2C1\u8230\u961F\u5904\u7406\u4E0B\u4E00\u652F\u5F85\u5237\u8230\u961F\uFF09`
7702
+ );
7703
+ } else {
7704
+ this.originalRunnerShipIds = [];
7705
+ this.clearRestoreSnapshot();
7706
+ this.runtime.logger.success(
7707
+ "kira",
7708
+ isCrossFleet ? `\u7B2C${finishedSource}\u8230\u961F\u5237\u95EA\u5B8C\u6210\uFF0C\u5DF2\u8FD8\u539F\u7B2C${finishedSource}\u8230\u961F\u4E0E\u7B2C1\u8230\u961F\u539F\u7F16\u6210` : `\u7B2C${finishedSource}\u8230\u961F\u5237\u95EA\u5B8C\u6210\u5E76\u6062\u590D\u539F\u7F16\u6210`
7709
+ );
7710
+ }
7169
7711
  if (this.activePlanJobId) {
7170
- this.runtime.notifyPlanWaitDone(`${this.activePlanJobId}${fleetId2}`);
7712
+ this.runtime.notifyPlanWaitDone(`${this.activePlanJobId}${finishedSource}`);
7171
7713
  }
7172
7714
  this.setStatus("\u5237\u95EA\u5B8C\u6210", "idle");
7173
7715
  });
@@ -7196,23 +7738,37 @@ var AutoKiraModule = class extends AutomationModule {
7196
7738
  });
7197
7739
  return;
7198
7740
  }
7199
- const fleetId2 = this.currentFleet;
7200
- const restoreIds = [...this.originalShipIds];
7741
+ const finishedSource = this.sourceFleet;
7742
+ const activeRunner2 = this.runnerFleet;
7743
+ const isCrossFleet = activeRunner2 !== finishedSource;
7744
+ const restoreSnap = {
7745
+ version: 1,
7746
+ savedAtMs: Date.now(),
7747
+ runnerFleetId: activeRunner2,
7748
+ originalRunnerShipIds: isCrossFleet ? [...this.originalRunnerShipIds] : [...this.originalSourceShipIds],
7749
+ sourceFleetId: finishedSource,
7750
+ originalSourceShipIds: [...this.originalSourceShipIds]
7751
+ };
7752
+ const tasks = buildRestoreTasksFromSnapshot(state, restoreSnap, true);
7201
7753
  await this.runLocked(async (ctx) => {
7202
- await executeChangeOrganization(
7203
- this.runtime.bridge,
7204
- this.runtime.actions,
7205
- this.runtime.vision,
7206
- this.runtime.logger,
7207
- fleetId2,
7208
- restoreIds,
7209
- true,
7210
- ctx
7211
- );
7212
- this.currentFleet = -1;
7213
- this.originalShipIds = [];
7754
+ if (tasks.length > 0) {
7755
+ await executeBatchRestoreOrganizations(
7756
+ this.runtime.bridge,
7757
+ this.runtime.actions,
7758
+ this.runtime.vision,
7759
+ this.runtime.logger,
7760
+ tasks,
7761
+ ctx,
7762
+ { clearRunnerEscortsFleetId: isCrossFleet ? activeRunner2 : void 0 }
7763
+ );
7764
+ }
7765
+ this.sourceFleet = -1;
7766
+ this.runnerFleet = -1;
7767
+ this.originalSourceShipIds = [];
7768
+ this.originalRunnerShipIds = [];
7214
7769
  this.kiraQueue = [];
7215
- this.setStatus("\u5F85\u5237\u8230\u5A18\u5747\u5728\u5165\u6E20\uFF0C\u6682\u505C\u5237\u95EA", "idle");
7770
+ this.clearRestoreSnapshot();
7771
+ this.setStatus("\u5F85\u5237\u8230\u5A18\u5747\u5728\u5165\u6E20\uFF0C\u5DF2\u8FD8\u539F\u7F16\u6210\u5E76\u6682\u505C\u5237\u95EA", "idle");
7216
7772
  });
7217
7773
  return;
7218
7774
  }
@@ -7265,66 +7821,68 @@ var AutoKiraModule = class extends AutomationModule {
7265
7821
  return;
7266
7822
  }
7267
7823
  }
7824
+ const activeRunner = this.runnerFleet;
7268
7825
  const desiredFleetIds = [flagship.id];
7826
+ const reservedIds = this.getReservedShipIdSet();
7269
7827
  if (cfg.kiraUseEscort) {
7270
- const curFleet = state.fleets[this.currentFleet];
7828
+ const curFleet = state.fleets[activeRunner];
7271
7829
  const existingEscort = curFleet && curFleet.shipIds[0] === flagship.id && curFleet.shipIds[1] ? state.ships[curFleet.shipIds[1]] : void 0;
7272
- const existingOk = existingEscort && existingEscort.stype === 2 && !existingEscort.isRepairing && Math.floor(existingEscort.hp / Math.max(1, existingEscort.maxHp) * 100) >= cfg.kiraEscortMinHpPercent && existingEscort.fuel / Math.max(1, existingEscort.maxFuel) >= 0.3 && existingEscort.bull / Math.max(1, existingEscort.maxBull) >= 0.3;
7830
+ const existingOk = existingEscort && !reservedIds.has(existingEscort.id) && existingEscort.stype === 2 && !existingEscort.isRepairing && Math.floor(existingEscort.hp / Math.max(1, existingEscort.maxHp) * 100) >= cfg.kiraEscortMinHpPercent && existingEscort.fuel / Math.max(1, existingEscort.maxFuel) >= 0.3 && existingEscort.bull / Math.max(1, existingEscort.maxBull) >= 0.3 && !shipsMayCollideInSameFleet(flagship, existingEscort);
7273
7831
  if (existingOk) {
7274
7832
  desiredFleetIds.push(existingEscort.id);
7275
7833
  } else {
7276
- const escort = selectKiraEscortShip(state, flagship, cfg);
7834
+ const escort = selectKiraEscortShip(state, flagship, cfg, reservedIds);
7277
7835
  if (escort) desiredFleetIds.push(escort.id);
7278
7836
  }
7279
7837
  }
7280
- if (fleetNeedsShipChange(state, this.currentFleet, desiredFleetIds)) {
7281
- const fleetId2 = this.currentFleet;
7838
+ if (fleetNeedsShipChange(state, activeRunner, desiredFleetIds)) {
7839
+ const swapOpts = this.computeCrossFleetSwapOptions(state, flagship, desiredFleetIds);
7840
+ const label = activeRunner !== this.sourceFleet ? `\u7B2C1\u961F\u8DE8\u961F\u7F16\u5165\u7B2C${this.sourceFleet}\u961F\u8230\u5A18: ${flagship.name}` : `\u7F16\u5165\u5237\u95EA\u7F16\u6210: ${flagship.name}`;
7282
7841
  await this.runLocked(async (ctx) => {
7283
- this.setStatus(`\u7F16\u5165\u5237\u95EA\u7F16\u6210: ${flagship.name}`);
7842
+ this.setStatus(label);
7284
7843
  await executeChangeOrganization(
7285
7844
  this.runtime.bridge,
7286
7845
  this.runtime.actions,
7287
7846
  this.runtime.vision,
7288
7847
  this.runtime.logger,
7289
- fleetId2,
7848
+ activeRunner,
7290
7849
  desiredFleetIds,
7291
7850
  false,
7292
- ctx
7851
+ ctx,
7852
+ swapOpts
7293
7853
  );
7294
7854
  });
7295
7855
  return;
7296
7856
  }
7297
7857
  if (cfg.kiraUseEscort && cfg.kiraClearEscortEquips && desiredFleetIds.length >= 2) {
7298
7858
  const escort = state.ships[desiredFleetIds[1]];
7299
- if (escort && escort.slots.some((sid) => sid > 0)) {
7300
- const fleetId2 = this.currentFleet;
7859
+ if (escort && !reservedIds.has(escort.id) && escort.slots.some((sid) => sid > 0)) {
7301
7860
  await this.runLocked(async (ctx) => {
7302
7861
  this.setStatus(`\u5378\u9664\u966A\u7EC3 ${escort.name} \u88C5\u5907`);
7303
- await executeClearShipEquips(this.runtime.bridge, this.runtime.actions, fleetId2, 1, ctx);
7862
+ await executeClearShipEquips(this.runtime.bridge, this.runtime.actions, activeRunner, 1, ctx);
7304
7863
  });
7305
7864
  return;
7306
7865
  }
7307
7866
  }
7308
7867
  const flagshipOnly = !cfg.kiraSupplyEscort;
7309
- if (fleetNeedsSupply(state, state.fleets[this.currentFleet], { thresholdRatio: 1, flagshipOnly, includeAircraft: true })) {
7310
- const fleetId2 = this.currentFleet;
7868
+ if (fleetNeedsSupply(state, state.fleets[activeRunner], { thresholdRatio: 1, flagshipOnly, includeAircraft: true })) {
7311
7869
  await this.runLocked(async (ctx) => {
7312
- this.setStatus(`\u8865\u7ED9\u5237\u95EA\u8230\u961F (\u7B2C${fleetId2}\u8230\u961F)`);
7870
+ this.setStatus(`\u8865\u7ED9\u5237\u95EA\u8230\u961F (\u7B2C${activeRunner}\u8230\u961F)`);
7313
7871
  await executeSupply(
7314
7872
  this.runtime.bridge,
7315
7873
  this.runtime.actions,
7316
7874
  this.runtime.logger,
7317
- [fleetId2],
7875
+ [activeRunner],
7318
7876
  { flagshipOnly, includeAircraft: true },
7319
7877
  ctx
7320
7878
  );
7321
7879
  });
7322
7880
  return;
7323
7881
  }
7324
- const fleetId = this.currentFleet;
7882
+ const sourceLabel = activeRunner !== this.sourceFleet ? ` [\u7B2C${activeRunner}\u961F\u4EE3\u5237\u7B2C${this.sourceFleet}\u961F]` : "";
7325
7883
  await this.runLocked(
7326
7884
  async (ctx) => {
7327
- this.setStatus(`1-1 \u5237\u95EA\u51FA\u51FB: ${flagship.name} (\u58EB\u6C14 ${flagship.cond}/${targetCond})`);
7885
+ this.setStatus(`1-1 \u5237\u95EA\u51FA\u51FB${sourceLabel}: ${flagship.name} (\u58EB\u6C14 ${flagship.cond}/${targetCond})`);
7328
7886
  this.runtime.scheduler.enterSortieClickLock(this.id);
7329
7887
  const sim = new BattleSimulator();
7330
7888
  let returnedToPort = false;
@@ -7349,13 +7907,13 @@ var AutoKiraModule = class extends AutomationModule {
7349
7907
  );
7350
7908
  await this.runtime.actions.clickDelay(COORDS.sortieUi.map1, { randomRange: 40, delayMs: 1e3, desc: "\u5237\u95EA\uFF1A\u9009\u62E9 1-1" }, ctx);
7351
7909
  await this.runtime.actions.clickDelay(COORDS.sortieUi.confirm, { randomRange: 30, delayMs: 1200, desc: "\u5237\u95EA\uFF1A\u51B3\u5B9A\u6D77\u57DF" }, ctx);
7352
- if (fleetId !== 1) {
7910
+ if (activeRunner !== 1) {
7353
7911
  await this.runtime.actions.clickDelay(
7354
7912
  {
7355
- x: COORDS.sortieUi.fleet1.x + (fleetId - 1) * COORDS.sortieUi.fleetOffsetX,
7913
+ x: COORDS.sortieUi.fleet1.x + (activeRunner - 1) * COORDS.sortieUi.fleetOffsetX,
7356
7914
  y: COORDS.sortieUi.fleet1.y
7357
7915
  },
7358
- { randomRange: 10, delayMs: 800, desc: `\u5237\u95EA\uFF1A\u9009\u62E9\u7B2C${fleetId}\u8230\u961F` },
7916
+ { randomRange: 10, delayMs: 800, desc: `\u5237\u95EA\uFF1A\u9009\u62E9\u7B2C${activeRunner}\u8230\u961F` },
7359
7917
  ctx
7360
7918
  );
7361
7919
  }
@@ -7380,7 +7938,7 @@ var AutoKiraModule = class extends AutomationModule {
7380
7938
  { randomRange: 25, delayMs: 2500, timeoutMs: 12e4, desc: "\u5237\u95EA\uFF1A\u8DF3\u8FC7\u591C\u6218\u5E76\u7ED3\u7B97" },
7381
7939
  ctx
7382
7940
  );
7383
- const safety = sim.evaluateAdvanceSafety(this.runtime.bridge.getState(), fleetId, false, {
7941
+ const safety = sim.evaluateAdvanceSafety(this.runtime.bridge.getState(), activeRunner, false, {
7384
7942
  allowSoloDamecon: false,
7385
7943
  strictTaihaGuard: true
7386
7944
  });
@@ -7406,7 +7964,7 @@ var AutoKiraModule = class extends AutomationModule {
7406
7964
  break;
7407
7965
  }
7408
7966
  }
7409
- this.runtime.logger.info("kira", `1-1 \u5237\u95EA\u5B8C\u6210\u4E00\u8F6E (${flagship.name}, \u8BC4\u4EF7 ${lastRank || "?"})`);
7967
+ this.runtime.logger.info("kira", `1-1 \u5237\u95EA\u5B8C\u6210\u4E00\u8F6E${sourceLabel} (${flagship.name}, \u8BC4\u4EF7 ${lastRank || "?"})`);
7410
7968
  } finally {
7411
7969
  unsubApi();
7412
7970
  this.runtime.scheduler.exitSortieClickLock(this.id);
@@ -7801,9 +8359,10 @@ function hasCrossedPracticeReset(lastCheckUtcMs, nowUtcMs) {
7801
8359
  return nowUtcMs >= nextResetMs;
7802
8360
  }
7803
8361
  var AutoPracticeModule = class extends AutomationModule {
7804
- constructor(runtime, onPracticeResetOrDone) {
8362
+ constructor(runtime, onPracticeResetOrDone, isFleet1Busy) {
7805
8363
  super(runtime);
7806
8364
  this.onPracticeResetOrDone = onPracticeResetOrDone;
8365
+ this.isFleet1Busy = isFleet1Busy;
7807
8366
  this.unsubApi = this.runtime.bridge.onApiResponse((ev) => {
7808
8367
  if (ev.path === "/kcsapi/api_get_member/practice" && Array.isArray(ev.body?.api_list)) {
7809
8368
  const remaining = ev.body.api_list.filter((o) => Number(o.api_state) === 0).length;
@@ -7862,6 +8421,7 @@ var AutoPracticeModule = class extends AutomationModule {
7862
8421
  }
7863
8422
  async tick() {
7864
8423
  if (!this.enabled || !this.runtime.scheduler.canAcquire(this.id)) return;
8424
+ if (this.isFleet1Busy?.()) return;
7865
8425
  const state = this.runtime.bridge.getState();
7866
8426
  if (!state.loaded || state.inSortie) return;
7867
8427
  this.checkRefresh();
@@ -9739,9 +10299,13 @@ var KcaAssistantCoordinator = class {
9739
10299
  isPracticeOpen: () => this.practice.enabled,
9740
10300
  hasReturnedExpeditions: () => this.expedition.getReturnedFleetIds().length > 0
9741
10301
  });
9742
- this.practice = new AutoPracticeModule(runtime, () => {
9743
- this.quests.requestForceCheck();
9744
- });
10302
+ this.practice = new AutoPracticeModule(
10303
+ runtime,
10304
+ () => {
10305
+ this.quests.requestForceCheck();
10306
+ },
10307
+ () => this.kira.isUsingFleet1()
10308
+ );
9745
10309
  this.kira = new AutoKiraModule(
9746
10310
  runtime,
9747
10311
  () => this.practice.needsAction(),
@@ -9754,7 +10318,12 @@ var KcaAssistantCoordinator = class {
9754
10318
  rank,
9755
10319
  sunkEnemyMasterIds
9756
10320
  });
9757
- }
10321
+ },
10322
+ this.settingsStore ? {
10323
+ load: () => this.settingsStore.loadKiraRestoreSnapshot(),
10324
+ save: (snap) => this.settingsStore.saveKiraRestoreSnapshot(snap),
10325
+ clear: () => this.settingsStore.clearKiraRestoreSnapshot()
10326
+ } : void 0
9758
10327
  );
9759
10328
  this.expedition = new AutoExpeditionModule(
9760
10329
  runtime,
@@ -9878,6 +10447,15 @@ var KcaAssistantCoordinator = class {
9878
10447
  getSettings() {
9879
10448
  return this.settings;
9880
10449
  }
10450
+ getKiraRestoreSnapshot() {
10451
+ return this.kira.getPendingRestoreSnapshot();
10452
+ }
10453
+ restoreKiraFleetsNow() {
10454
+ return this.kira.restoreSavedFleetsNow();
10455
+ }
10456
+ discardKiraRestoreSnapshot() {
10457
+ this.kira.discardPendingRestoreSnapshot();
10458
+ }
9881
10459
  replaceSettings(next) {
9882
10460
  this.settings = next;
9883
10461
  this.logger.setMaxEntries(next.general.maxLogEntries);
@@ -11311,10 +11889,10 @@ var PoiStateAdapter = class {
11311
11889
  cachedEquipLimitExslot = {};
11312
11890
  cachedShipCtypes = {};
11313
11891
  onApiResponse(event) {
11314
- const path4 = normalizeApiPath(event.path);
11892
+ const path5 = normalizeApiPath(event.path);
11315
11893
  const body = event.body;
11316
11894
  if (!body || typeof body !== "object") return;
11317
- switch (path4) {
11895
+ switch (path5) {
11318
11896
  case "/kcsapi/api_start2/getData":
11319
11897
  this.ingestStart2(body);
11320
11898
  break;
@@ -12663,30 +13241,192 @@ var import_react11 = __toESM(require("react"));
12663
13241
 
12664
13242
  // src/ui/components/CollapsibleCard.tsx
12665
13243
  var import_react = __toESM(require("react"));
12666
- var STORAGE_PREFIX = "kca-next:fold:";
12667
- var foldAllListeners = /* @__PURE__ */ new Set();
12668
- function setAllMountedCardsOpen(open) {
12669
- for (const listener of foldAllListeners) {
12670
- listener(open);
13244
+
13245
+ // src/ui/fold-store.ts
13246
+ var import_node_fs3 = __toESM(require("fs"));
13247
+ var import_node_path3 = __toESM(require("path"));
13248
+ var LOCAL_STORAGE_PREFIX = "kca-next:fold:v2:";
13249
+ var POI_CONFIG_KEY = "plugin.kca-next.uiFoldStateV2";
13250
+ var FOLD_FILE_NAME = "ui-fold-state.json";
13251
+ var memoryState = /* @__PURE__ */ new Map();
13252
+ var consumedTriggers = /* @__PURE__ */ new Map();
13253
+ var configuredDir = null;
13254
+ var diskHydrated = false;
13255
+ var globalTriggerSeq = 0;
13256
+ function toFlatConfigKey(storageKey) {
13257
+ return storageKey.replace(/\./g, "__");
13258
+ }
13259
+ function resolveFoldFilePath() {
13260
+ if (configuredDir) {
13261
+ return import_node_path3.default.join(configuredDir, FOLD_FILE_NAME);
13262
+ }
13263
+ if (typeof window !== "undefined" && window.APPDATA_PATH) {
13264
+ const appData = String(window.APPDATA_PATH).trim();
13265
+ if (appData) {
13266
+ return import_node_path3.default.join(appData, "kca-next", FOLD_FILE_NAME);
13267
+ }
13268
+ }
13269
+ return null;
13270
+ }
13271
+ function getPoiConfig() {
13272
+ try {
13273
+ if (typeof window === "undefined") return null;
13274
+ const cfg = window.config;
13275
+ if (cfg && typeof cfg.get === "function" && typeof cfg.set === "function") {
13276
+ return cfg;
13277
+ }
13278
+ } catch {
13279
+ }
13280
+ return null;
13281
+ }
13282
+ function hydrateFromDiskOnce() {
13283
+ if (diskHydrated) return;
13284
+ diskHydrated = true;
13285
+ const filePath = resolveFoldFilePath();
13286
+ if (!filePath) return;
13287
+ try {
13288
+ if (!import_node_fs3.default.existsSync(filePath)) return;
13289
+ const raw = import_node_fs3.default.readFileSync(filePath, "utf8");
13290
+ const parsed = JSON.parse(raw);
13291
+ const cards = parsed && typeof parsed === "object" && parsed.cards && typeof parsed.cards === "object" ? parsed.cards : parsed;
13292
+ if (!cards || typeof cards !== "object") return;
13293
+ for (const [k, v] of Object.entries(cards)) {
13294
+ if (typeof v === "boolean" && !memoryState.has(k)) {
13295
+ memoryState.set(k, v);
13296
+ }
13297
+ }
13298
+ } catch {
12671
13299
  }
12672
13300
  }
12673
- function readStoredOpen(storageKey, fallback) {
13301
+ function persistMemoryToDisk() {
13302
+ const filePath = resolveFoldFilePath();
13303
+ if (!filePath) return;
12674
13304
  try {
12675
- if (typeof window === "undefined" || !window.localStorage) return fallback;
12676
- const raw = window.localStorage.getItem(STORAGE_PREFIX + storageKey);
12677
- if (raw === "1") return true;
12678
- if (raw === "0") return false;
13305
+ const cards = {};
13306
+ for (const [k, v] of memoryState.entries()) {
13307
+ cards[k] = v;
13308
+ }
13309
+ const payload = { version: 1, cards };
13310
+ const serialized = JSON.stringify(payload, null, 2);
13311
+ import_node_fs3.default.mkdirSync(import_node_path3.default.dirname(filePath), { recursive: true });
13312
+ const tmpPath = `${filePath}.tmp`;
13313
+ try {
13314
+ import_node_fs3.default.writeFileSync(tmpPath, serialized, "utf8");
13315
+ import_node_fs3.default.renameSync(tmpPath, filePath);
13316
+ } catch {
13317
+ import_node_fs3.default.writeFileSync(filePath, serialized, "utf8");
13318
+ }
13319
+ } catch {
13320
+ }
13321
+ }
13322
+ function configureFoldStoreDir(dir) {
13323
+ const normalized = dir && dir.trim() ? dir.trim() : null;
13324
+ if (configuredDir !== normalized) {
13325
+ configuredDir = normalized;
13326
+ diskHydrated = false;
13327
+ }
13328
+ }
13329
+ function nextFoldTrigger() {
13330
+ globalTriggerSeq += 1;
13331
+ return globalTriggerSeq;
13332
+ }
13333
+ function isFoldTriggerPending(channel, token) {
13334
+ if (!token || token <= 0) return false;
13335
+ return consumedTriggers.get(channel) !== token;
13336
+ }
13337
+ function consumeFoldTrigger(channel, token) {
13338
+ if (!isFoldTriggerPending(channel, token)) return false;
13339
+ consumedTriggers.set(channel, token);
13340
+ return true;
13341
+ }
13342
+ function readFoldOpen(storageKey, fallback) {
13343
+ hydrateFromDiskOnce();
13344
+ const cached = memoryState.get(storageKey);
13345
+ if (typeof cached === "boolean") return cached;
13346
+ const poiCfg = getPoiConfig();
13347
+ if (poiCfg) {
13348
+ try {
13349
+ const storedMap = poiCfg.get?.(POI_CONFIG_KEY);
13350
+ if (storedMap && typeof storedMap === "object") {
13351
+ const val = storedMap[toFlatConfigKey(storageKey)];
13352
+ if (typeof val === "boolean") {
13353
+ memoryState.set(storageKey, val);
13354
+ return val;
13355
+ }
13356
+ }
13357
+ } catch {
13358
+ }
13359
+ }
13360
+ try {
13361
+ if (typeof window !== "undefined" && window.localStorage) {
13362
+ const raw = window.localStorage.getItem(LOCAL_STORAGE_PREFIX + storageKey);
13363
+ if (raw === "1") {
13364
+ memoryState.set(storageKey, true);
13365
+ return true;
13366
+ }
13367
+ if (raw === "0") {
13368
+ memoryState.set(storageKey, false);
13369
+ return false;
13370
+ }
13371
+ }
12679
13372
  } catch {
12680
13373
  }
12681
13374
  return fallback;
12682
13375
  }
12683
- function writeStoredOpen(storageKey, open) {
13376
+ function writeFoldOpen(storageKey, open) {
13377
+ hydrateFromDiskOnce();
13378
+ memoryState.set(storageKey, open);
13379
+ persistMemoryToDisk();
13380
+ const poiCfg = getPoiConfig();
13381
+ if (poiCfg) {
13382
+ try {
13383
+ const existing = poiCfg.get?.(POI_CONFIG_KEY);
13384
+ const nextMap = existing && typeof existing === "object" ? { ...existing } : {};
13385
+ nextMap[toFlatConfigKey(storageKey)] = open;
13386
+ poiCfg.set?.(POI_CONFIG_KEY, nextMap);
13387
+ } catch {
13388
+ }
13389
+ }
12684
13390
  try {
12685
- if (typeof window === "undefined" || !window.localStorage) return;
12686
- window.localStorage.setItem(STORAGE_PREFIX + storageKey, open ? "1" : "0");
13391
+ if (typeof window !== "undefined" && window.localStorage) {
13392
+ window.localStorage.setItem(LOCAL_STORAGE_PREFIX + storageKey, open ? "1" : "0");
13393
+ }
12687
13394
  } catch {
12688
13395
  }
12689
13396
  }
13397
+ function resolveInitialCardOpen(storageKey, defaultOpen, forceOpenTrigger, forceCloseTrigger) {
13398
+ if (isFoldTriggerPending(`open:${storageKey}`, forceOpenTrigger)) {
13399
+ return true;
13400
+ }
13401
+ if (isFoldTriggerPending(`close:${storageKey}`, forceCloseTrigger)) {
13402
+ return false;
13403
+ }
13404
+ return readFoldOpen(storageKey, defaultOpen);
13405
+ }
13406
+ function applyCardForceOpenTrigger(storageKey, forceOpenTrigger, persistForceOpen) {
13407
+ if (!consumeFoldTrigger(`open:${storageKey}`, forceOpenTrigger)) {
13408
+ return false;
13409
+ }
13410
+ if (persistForceOpen) {
13411
+ writeFoldOpen(storageKey, true);
13412
+ }
13413
+ return true;
13414
+ }
13415
+ function applyCardForceCloseTrigger(storageKey, forceCloseTrigger) {
13416
+ if (!consumeFoldTrigger(`close:${storageKey}`, forceCloseTrigger)) {
13417
+ return false;
13418
+ }
13419
+ writeFoldOpen(storageKey, false);
13420
+ return true;
13421
+ }
13422
+
13423
+ // src/ui/components/CollapsibleCard.tsx
13424
+ var foldAllListeners = /* @__PURE__ */ new Set();
13425
+ function setAllMountedCardsOpen(open) {
13426
+ for (const listener of foldAllListeners) {
13427
+ listener(open);
13428
+ }
13429
+ }
12690
13430
  var CollapsibleCard = ({
12691
13431
  storageKey,
12692
13432
  title,
@@ -12694,22 +13434,28 @@ var CollapsibleCard = ({
12694
13434
  headerRight,
12695
13435
  defaultOpen = true,
12696
13436
  forceOpenTrigger,
13437
+ persistForceOpen = true,
13438
+ forceCloseTrigger,
12697
13439
  className,
12698
13440
  children: children2
12699
13441
  }) => {
12700
13442
  const [open, setOpen] = (0, import_react.useState)(
12701
- () => forceOpenTrigger ? true : readStoredOpen(storageKey, defaultOpen)
13443
+ () => resolveInitialCardOpen(storageKey, defaultOpen, forceOpenTrigger, forceCloseTrigger)
12702
13444
  );
12703
13445
  (0, import_react.useEffect)(() => {
12704
- if (forceOpenTrigger) {
13446
+ if (applyCardForceOpenTrigger(storageKey, forceOpenTrigger, persistForceOpen)) {
12705
13447
  setOpen(true);
12706
- writeStoredOpen(storageKey, true);
12707
13448
  }
12708
- }, [forceOpenTrigger, storageKey]);
13449
+ }, [forceOpenTrigger, persistForceOpen, storageKey]);
13450
+ (0, import_react.useEffect)(() => {
13451
+ if (applyCardForceCloseTrigger(storageKey, forceCloseTrigger)) {
13452
+ setOpen(false);
13453
+ }
13454
+ }, [forceCloseTrigger, storageKey]);
12709
13455
  (0, import_react.useEffect)(() => {
12710
13456
  const onSetAll = (nextOpen) => {
12711
13457
  setOpen(nextOpen);
12712
- writeStoredOpen(storageKey, nextOpen);
13458
+ writeFoldOpen(storageKey, nextOpen);
12713
13459
  };
12714
13460
  foldAllListeners.add(onSetAll);
12715
13461
  return () => {
@@ -12719,7 +13465,7 @@ var CollapsibleCard = ({
12719
13465
  const toggle = () => {
12720
13466
  setOpen((prev) => {
12721
13467
  const next = !prev;
12722
- writeStoredOpen(storageKey, next);
13468
+ writeFoldOpen(storageKey, next);
12723
13469
  return next;
12724
13470
  });
12725
13471
  };
@@ -12760,22 +13506,28 @@ var CollapsibleSubBox = ({
12760
13506
  headerRight,
12761
13507
  defaultOpen = false,
12762
13508
  forceOpenTrigger,
13509
+ persistForceOpen = true,
13510
+ forceCloseTrigger,
12763
13511
  danger = false,
12764
13512
  children: children2
12765
13513
  }) => {
12766
13514
  const [open, setOpen] = (0, import_react.useState)(
12767
- () => forceOpenTrigger ? true : readStoredOpen(storageKey, defaultOpen)
13515
+ () => resolveInitialCardOpen(storageKey, defaultOpen, forceOpenTrigger, forceCloseTrigger)
12768
13516
  );
12769
13517
  (0, import_react.useEffect)(() => {
12770
- if (forceOpenTrigger) {
13518
+ if (applyCardForceOpenTrigger(storageKey, forceOpenTrigger, persistForceOpen)) {
12771
13519
  setOpen(true);
12772
- writeStoredOpen(storageKey, true);
12773
13520
  }
12774
- }, [forceOpenTrigger, storageKey]);
13521
+ }, [forceOpenTrigger, persistForceOpen, storageKey]);
13522
+ (0, import_react.useEffect)(() => {
13523
+ if (applyCardForceCloseTrigger(storageKey, forceCloseTrigger)) {
13524
+ setOpen(false);
13525
+ }
13526
+ }, [forceCloseTrigger, storageKey]);
12775
13527
  const toggle = () => {
12776
13528
  setOpen((prev) => {
12777
13529
  const next = !prev;
12778
- writeStoredOpen(storageKey, next);
13530
+ writeFoldOpen(storageKey, next);
12779
13531
  return next;
12780
13532
  });
12781
13533
  };
@@ -13593,6 +14345,12 @@ var ExpeditionKiraTab = ({ coordinator, gameState, settings }) => {
13593
14345
  return `${f}\u961F:${id > 0 ? formatExpeditionCode(id) : "\u5173"}`;
13594
14346
  }).join(" \xB7 ");
13595
14347
  const enabledKiraCount = exp.kiraEnabled.filter(Boolean).length;
14348
+ const pendingRestore = coordinator.getKiraRestoreSnapshot();
14349
+ const useFleet1Mode = exp.kiraUseFleet1 !== false;
14350
+ const restoreFleetLabels = pendingRestore ? [
14351
+ pendingRestore.sourceFleetId > 0 ? `\u7B2C${pendingRestore.sourceFleetId}\u8230\u961F(${pendingRestore.originalSourceShipIds.length}\u8239)` : "",
14352
+ pendingRestore.runnerFleetId > 0 && pendingRestore.runnerFleetId !== pendingRestore.sourceFleetId ? `\u7B2C${pendingRestore.runnerFleetId}\u8230\u961F(${pendingRestore.originalRunnerShipIds.length}\u8239)` : ""
14353
+ ].filter(Boolean).join("\u3001") : "";
13596
14354
  return /* @__PURE__ */ import_react3.default.createElement(import_react3.default.Fragment, null, /* @__PURE__ */ import_react3.default.createElement(
13597
14355
  CollapsibleCard,
13598
14356
  {
@@ -13656,11 +14414,63 @@ var ExpeditionKiraTab = ({ coordinator, gameState, settings }) => {
13656
14414
  storageKey: "exp.kira",
13657
14415
  title: "1-1 \u81EA\u52A8\u5237\u95EA\u914D\u7F6E (\u7B2C 1~4 \u8230\u961F)",
13658
14416
  defaultOpen: true,
13659
- summary: /* @__PURE__ */ import_react3.default.createElement(import_react3.default.Fragment, null, /* @__PURE__ */ import_react3.default.createElement("span", null, "\u5DF2\u542F\u7528 ", enabledKiraCount, "/4 \u8230\u961F"), /* @__PURE__ */ import_react3.default.createElement("span", { className: "kca-muted" }, "\u7B2C 1 \u8230\u961F\u56FA\u5B9A\u4F7F\u7528\u652F\u63F4/\u5168\u5458\u58EB\u6C14\u6A21\u5F0F"))
14417
+ summary: /* @__PURE__ */ import_react3.default.createElement(import_react3.default.Fragment, null, /* @__PURE__ */ import_react3.default.createElement("span", null, "\u5DF2\u542F\u7528 ", enabledKiraCount, "/4 \u8230\u961F"), /* @__PURE__ */ import_react3.default.createElement("span", { className: `kca-badge ${useFleet1Mode ? "kca-badge-ok" : ""}` }, useFleet1Mode ? "1\u961F\u8DE8\u961F\u76F4\u6362" : "\u539F\u8230\u961F\u76F4\u5237"), /* @__PURE__ */ import_react3.default.createElement("span", { className: "kca-muted" }, "\u9ED8\u8BA4 <", KIRA_START_COND, " \u8D77\u5237 \u2192 \u5237\u81F3\u76EE\u6807\u58EB\u6C14")),
14418
+ headerRight: /* @__PURE__ */ import_react3.default.createElement(
14419
+ "label",
14420
+ {
14421
+ className: "kca-switch",
14422
+ title: "\u5F00\u542F\u540E\uFF1A\u7B2C 2~4 \u8230\u961F\u5237\u95EA\u65F6\u7EDF\u4E00\u501F\u7528\u7B2C 1 \u8230\u961F\u51FA\u51FB\uFF0C\u4E0D\u89E3\u6563\u539F\u961F\uFF0C\u4EC5\u628A\u6389\u95EA\u8239\u8DE8\u961F\u6362\u5230\u7B2C 1 \u8230\u961F\uFF0C\u5237\u6EE1\u540E\u6309\u6700\u5C0F\u5DEE\u5206\u81EA\u52A8\u8FD8\u539F\uFF08\u652F\u6301\u8DE8\u961F\u5408\u5E76\u5237\u95EA\u4E0E\u65AD\u7EBF\u6062\u590D\uFF09\uFF1B\u8054\u5408\u8230\u961F\u7F16\u6210\u4E2D\u81EA\u52A8\u907F\u8BA9"
14423
+ },
14424
+ /* @__PURE__ */ import_react3.default.createElement(
14425
+ "input",
14426
+ {
14427
+ type: "checkbox",
14428
+ checked: useFleet1Mode,
14429
+ onChange: (e) => coordinator.updateSettings((s) => {
14430
+ s.expedition.kiraUseFleet1 = e.target.checked;
14431
+ })
14432
+ }
14433
+ ),
14434
+ /* @__PURE__ */ import_react3.default.createElement("strong", null, "\u7EDF\u4E00\u5728\u7B2C 1 \u8230\u961F\u5237\u95EA")
14435
+ )
13660
14436
  },
13661
- /* @__PURE__ */ import_react3.default.createElement("table", { className: "kca-table" }, /* @__PURE__ */ import_react3.default.createElement("thead", null, /* @__PURE__ */ import_react3.default.createElement("tr", null, /* @__PURE__ */ import_react3.default.createElement("th", null, "\u8230\u961F"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u542F\u7528"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u652F\u63F4\u6A21\u5F0F"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u95EA\u8230\u6570"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u76EE\u6807\u58EB\u6C14"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u987A\u5E8F"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u5F53\u524D\u58EB\u6C14\u9884\u89C8"))), /* @__PURE__ */ import_react3.default.createElement("tbody", null, [0, 1, 2, 3].map((i) => {
14437
+ pendingRestore && restoreFleetLabels && /* @__PURE__ */ import_react3.default.createElement(
14438
+ "div",
14439
+ {
14440
+ className: "kca-sub-box",
14441
+ style: {
14442
+ borderColor: "#b45309",
14443
+ background: "#2a1f0f",
14444
+ display: "flex",
14445
+ alignItems: "center",
14446
+ justifyContent: "space-between",
14447
+ gap: 8,
14448
+ flexWrap: "wrap"
14449
+ }
14450
+ },
14451
+ /* @__PURE__ */ import_react3.default.createElement("span", { style: { color: "#fcd34d", fontSize: 12 } }, "\u26A0 \u5B58\u5728\u672A\u8FD8\u539F\u7684\u5237\u95EA\u539F\u7F16\u6210\u5FEB\u7167\uFF1A", restoreFleetLabels, "\uFF08\u65AD\u7EBF/\u6682\u505C\u540E\u53EF\u4E00\u952E\u590D\u539F\uFF09"),
14452
+ /* @__PURE__ */ import_react3.default.createElement("div", { className: "kca-row" }, /* @__PURE__ */ import_react3.default.createElement(
14453
+ "button",
14454
+ {
14455
+ className: "kca-btn kca-btn-sm kca-btn-primary",
14456
+ onClick: () => void coordinator.restoreKiraFleetsNow()
14457
+ },
14458
+ "\u21A9 \u7ACB\u5373\u4E00\u952E\u8FD8\u539F\u539F\u7F16\u6210"
14459
+ ), /* @__PURE__ */ import_react3.default.createElement(
14460
+ "button",
14461
+ {
14462
+ className: "kca-btn kca-btn-sm",
14463
+ title: "\u5982\u679C\u4F60\u5DF2\u5728\u6E38\u620F\u5185\u624B\u52A8\u6539\u56DE\u7F16\u6210\uFF0C\u53EF\u6E05\u9664\u6B64\u63D0\u793A",
14464
+ onClick: () => coordinator.discardKiraRestoreSnapshot()
14465
+ },
14466
+ "\u5FFD\u7565\u8BB0\u5F55"
14467
+ ))
14468
+ ),
14469
+ /* @__PURE__ */ import_react3.default.createElement("table", { className: "kca-table" }, /* @__PURE__ */ import_react3.default.createElement("thead", null, /* @__PURE__ */ import_react3.default.createElement("tr", null, /* @__PURE__ */ import_react3.default.createElement("th", null, "\u8230\u961F"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u542F\u7528"), /* @__PURE__ */ import_react3.default.createElement("th", { title: "\u4E0D\u52FE\u9009\uFF08\u9ED8\u8BA4\uFF09\uFF1A\u58EB\u6C14\u4F4E\u4E8E 50 \u624D\u5F00\u59CB\u5237\uFF0C\u5237\u81F3\u76EE\u6807\u58EB\u6C14\uFF1B\u52FE\u9009\uFF08\u4EC5\u652F\u63F4\u8230\u961F\uFF09\uFF1A\u58EB\u6C14\u4F4E\u4E8E\u76EE\u6807\u58EB\u6C14\u5373\u5F3A\u5236\u8865\u95EA\uFF0C\u8FDC\u5F81\u8230\u961F\u8BF7\u52FF\u52FE\u9009" }, "\u652F\u63F4\u6A21\u5F0F"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u95EA\u8230\u6570"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u76EE\u6807\u58EB\u6C14"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u987A\u5E8F"), /* @__PURE__ */ import_react3.default.createElement("th", null, "\u5F53\u524D\u58EB\u6C14\u9884\u89C8"))), /* @__PURE__ */ import_react3.default.createElement("tbody", null, [0, 1, 2, 3].map((i) => {
13662
14470
  const fleet = gameState.fleets[i + 1];
13663
14471
  const ships = (fleet?.shipIds ?? []).map((id) => gameState.ships[id]).filter(Boolean);
14472
+ const effTargetCond = getEffectiveKiraTargetCond(exp.kiraTargetCond[i]);
14473
+ const isSupport = Boolean(exp.kiraForSupport[i]);
13664
14474
  return /* @__PURE__ */ import_react3.default.createElement("tr", { key: i }, /* @__PURE__ */ import_react3.default.createElement("td", null, "\u7B2C ", i + 1, " \u8230\u961F"), /* @__PURE__ */ import_react3.default.createElement("td", null, /* @__PURE__ */ import_react3.default.createElement(
13665
14475
  "input",
13666
14476
  {
@@ -13672,16 +14482,23 @@ var ExpeditionKiraTab = ({ coordinator, gameState, settings }) => {
13672
14482
  })
13673
14483
  }
13674
14484
  )), /* @__PURE__ */ import_react3.default.createElement("td", null, /* @__PURE__ */ import_react3.default.createElement(
13675
- "input",
14485
+ "label",
13676
14486
  {
13677
- type: "checkbox",
13678
- disabled: i === 0,
13679
- checked: i === 0 ? true : exp.kiraForSupport[i],
13680
- onChange: (e) => coordinator.updateSettings((s) => {
13681
- s.expedition.kiraForSupport[i] = e.target.checked;
13682
- syncRememberedPreset(s, i);
13683
- })
13684
- }
14487
+ className: "kca-switch",
14488
+ title: isSupport ? `\u652F\u63F4\u6A21\u5F0F\uFF1A\u58EB\u6C14 < ${effTargetCond} \u5373\u5F00\u59CB\u5237\u81F3 ${effTargetCond}` : `\u5E38\u89C4\u6A21\u5F0F\uFF1A\u58EB\u6C14 < ${KIRA_START_COND} \u624D\u5F00\u59CB\u5237\uFF0C\u5237\u81F3 ${effTargetCond}`
14489
+ },
14490
+ /* @__PURE__ */ import_react3.default.createElement(
14491
+ "input",
14492
+ {
14493
+ type: "checkbox",
14494
+ checked: isSupport,
14495
+ onChange: (e) => coordinator.updateSettings((s) => {
14496
+ s.expedition.kiraForSupport[i] = e.target.checked;
14497
+ syncRememberedPreset(s, i);
14498
+ })
14499
+ }
14500
+ ),
14501
+ /* @__PURE__ */ import_react3.default.createElement("span", { className: "kca-muted", style: { fontSize: 11 } }, isSupport ? `<${effTargetCond}` : `<${KIRA_START_COND}`)
13685
14502
  )), /* @__PURE__ */ import_react3.default.createElement("td", null, /* @__PURE__ */ import_react3.default.createElement(
13686
14503
  "input",
13687
14504
  {
@@ -13704,7 +14521,7 @@ var ExpeditionKiraTab = ({ coordinator, gameState, settings }) => {
13704
14521
  style: { width: 58 },
13705
14522
  min: 50,
13706
14523
  max: 85,
13707
- value: exp.kiraTargetCond[i],
14524
+ value: effTargetCond,
13708
14525
  onChange: (e) => coordinator.updateSettings((s) => {
13709
14526
  s.expedition.kiraTargetCond[i] = Math.max(50, Math.min(85, Number(e.target.value) || 75));
13710
14527
  syncRememberedPreset(s, i);
@@ -14871,7 +15688,7 @@ var PlanTab = ({ coordinator, settings }) => {
14871
15688
  var import_react7 = __toESM(require("react"));
14872
15689
 
14873
15690
  // src/ui/components/LegacyImportPanel.tsx
14874
- var import_node_fs3 = __toESM(require("fs"));
15691
+ var import_node_fs4 = __toESM(require("fs"));
14875
15692
  var import_react6 = __toESM(require("react"));
14876
15693
  function formatBytes(bytes) {
14877
15694
  if (bytes < 1024) return `${bytes} B`;
@@ -14927,6 +15744,7 @@ async function tryPickDirectoryElectron() {
14927
15744
  var LegacyImportPanel = ({
14928
15745
  coordinator,
14929
15746
  autoScanOnMount = false,
15747
+ autoScanTrigger = 0,
14930
15748
  onImportSuccess
14931
15749
  }) => {
14932
15750
  const [report, setReport] = (0, import_react6.useState)(null);
@@ -15005,11 +15823,16 @@ var LegacyImportPanel = ({
15005
15823
  setShowCustomDirRow((v) => !v);
15006
15824
  }
15007
15825
  };
15826
+ const lastAutoScannedRef = (0, import_react6.useRef)(0);
15008
15827
  (0, import_react6.useEffect)(() => {
15009
- if (autoScanOnMount) {
15828
+ if (autoScanTrigger > 0 && lastAutoScannedRef.current !== autoScanTrigger) {
15829
+ lastAutoScannedRef.current = autoScanTrigger;
15830
+ runAutoDetect();
15831
+ } else if (autoScanOnMount && lastAutoScannedRef.current === 0) {
15832
+ lastAutoScannedRef.current = -1;
15010
15833
  runAutoDetect();
15011
15834
  }
15012
- }, [autoScanOnMount]);
15835
+ }, [autoScanTrigger, autoScanOnMount]);
15013
15836
  const handleManualFiles = async (e) => {
15014
15837
  const files = e.target.files;
15015
15838
  if (!files || files.length === 0) return;
@@ -15084,7 +15907,7 @@ var LegacyImportPanel = ({
15084
15907
  parsed = uploadedSettings.result;
15085
15908
  sourceLabel = uploadedSettings.fileName;
15086
15909
  } else if (activeCandidate) {
15087
- const buf = import_node_fs3.default.readFileSync(activeCandidate.path);
15910
+ const buf = import_node_fs4.default.readFileSync(activeCandidate.path);
15088
15911
  parsed = importLegacyAssistantSettings(buf);
15089
15912
  sourceLabel = activeCandidate.fileName;
15090
15913
  } else {
@@ -15104,7 +15927,7 @@ var LegacyImportPanel = ({
15104
15927
  );
15105
15928
  doneParts.push(`\u5DF2\u5BFC\u5165 ${cnt} \u4E2A\u56FE\u50CF\u6A21\u677F (${uploadedCdata.fileName})`);
15106
15929
  } else if (activeCdata && activeCdata.valid) {
15107
- const buf = import_node_fs3.default.readFileSync(activeCdata.path);
15930
+ const buf = import_node_fs4.default.readFileSync(activeCdata.path);
15108
15931
  const parsedCdata = parseLegacyCdata(buf);
15109
15932
  const cnt = coordinator.importCustomTemplates(parsedCdata.templates, activeCdata.path);
15110
15933
  doneParts.push(`\u5DF2\u5BFC\u5165 ${cnt} \u4E2A\u56FE\u50CF\u6A21\u677F (cdata)`);
@@ -15114,11 +15937,12 @@ var LegacyImportPanel = ({
15114
15937
  setStatusMsg({ kind: "err", text: "\u8BF7\u81F3\u5C11\u52FE\u9009\u4E00\u4E2A\u8981\u5BFC\u5165\u7684\u914D\u7F6E\u6A21\u5757\u6216 cdata \u6A21\u677F\u3002" });
15115
15938
  return;
15116
15939
  }
15940
+ const summaryLine = doneParts.join("\uFF1B");
15117
15941
  setStatusMsg({
15118
15942
  kind: "ok",
15119
- text: `\u2705 ${doneParts.join("\uFF1B")}\u3002\u539F KCA Next \u914D\u7F6E\u5DF2\u81EA\u52A8\u5907\u4EFD\u81F3 backups/settings.v1.1.json\u3002`
15943
+ text: `\u2705 ${summaryLine}\u3002\u539F KCA Next \u914D\u7F6E\u5DF2\u81EA\u52A8\u5907\u4EFD\u81F3 backups/settings.v1.1.json\u3002`
15120
15944
  });
15121
- onImportSuccess?.();
15945
+ onImportSuccess?.(summaryLine);
15122
15946
  } catch (err) {
15123
15947
  setStatusMsg({
15124
15948
  kind: "err",
@@ -15287,6 +16111,16 @@ var SettingsLogsTab = ({
15287
16111
  const [s2Snap, setS2Snap] = (0, import_react7.useState)(
15288
16112
  () => coordinator.getStart2CacheSnapshot()
15289
16113
  );
16114
+ const [autoScanTrigger, setAutoScanTrigger] = (0, import_react7.useState)(
16115
+ () => isFoldTriggerPending("legacy-import:autoscan", legacyImportTrigger) ? legacyImportTrigger : 0
16116
+ );
16117
+ const [importCloseTrigger, setImportCloseTrigger] = (0, import_react7.useState)(0);
16118
+ const [lastImportDoneText, setLastImportDoneText] = (0, import_react7.useState)("");
16119
+ (0, import_react7.useEffect)(() => {
16120
+ if (consumeFoldTrigger("legacy-import:autoscan", legacyImportTrigger)) {
16121
+ setAutoScanTrigger(legacyImportTrigger);
16122
+ }
16123
+ }, [legacyImportTrigger]);
15290
16124
  (0, import_react7.useEffect)(() => {
15291
16125
  let alive = true;
15292
16126
  const poll = async () => {
@@ -15313,7 +16147,10 @@ var SettingsLogsTab = ({
15313
16147
  coordinator.saveNow();
15314
16148
  coordinator.replaceSettings(parsed);
15315
16149
  coordinator.saveNow();
15316
- setJsonMsg("JSON \u914D\u7F6E\u5BFC\u5165\u6210\u529F\uFF08\u539F\u914D\u7F6E\u5DF2\u81EA\u52A8\u5907\u4EFD\uFF09");
16150
+ const doneText = "JSON \u914D\u7F6E\u5BFC\u5165\u6210\u529F\uFF08\u539F\u914D\u7F6E\u5DF2\u81EA\u52A8\u5907\u4EFD\uFF09";
16151
+ setJsonMsg(doneText);
16152
+ setLastImportDoneText(doneText);
16153
+ setImportCloseTrigger(nextFoldTrigger());
15317
16154
  } else {
15318
16155
  setJsonMsg("JSON \u683C\u5F0F\u7248\u672C\u4E0D\u5339\u914D");
15319
16156
  }
@@ -15343,7 +16180,6 @@ var SettingsLogsTab = ({
15343
16180
  }
15344
16181
  };
15345
16182
  const filteredLogs = logs.filter((l) => levelFilter === "all" || l.level === levelFilter).slice(-200).reverse();
15346
- const autoScanLegacy = legacyImportTrigger > 0;
15347
16183
  const speedLabels = {
15348
16184
  safe: "\u7A33\u5065",
15349
16185
  normal: "\u6807\u51C6",
@@ -15354,11 +16190,23 @@ var SettingsLogsTab = ({
15354
16190
  {
15355
16191
  storageKey: "settings.import",
15356
16192
  title: "\u65E7\u7248 (\u975E)\u63D0\u52A9\u624B \u4E00\u952E\u68C0\u6D4B\u4E0E\u65E0\u635F\u5BFC\u5165",
15357
- defaultOpen: autoScanLegacy,
16193
+ defaultOpen: false,
15358
16194
  forceOpenTrigger: legacyImportTrigger,
15359
- summary: /* @__PURE__ */ import_react7.default.createElement("span", null, "v2.xml.gz / \u65E7\u7248 xml / cdata / JSON \u5907\u4EFD")
16195
+ persistForceOpen: false,
16196
+ forceCloseTrigger: importCloseTrigger,
16197
+ summary: lastImportDoneText ? /* @__PURE__ */ import_react7.default.createElement("span", { className: "kca-badge kca-badge-ok", title: lastImportDoneText }, "\u2705 \u5BFC\u5165\u5B8C\u6210\uFF08\u70B9\u51FB\u53EF\u5C55\u5F00\uFF09") : /* @__PURE__ */ import_react7.default.createElement("span", null, "\u9ED8\u8BA4\u6536\u8D77 \xB7 v2.xml.gz / \u65E7\u7248 xml / cdata / JSON \u5907\u4EFD")
15360
16198
  },
15361
- /* @__PURE__ */ import_react7.default.createElement(LegacyImportPanel, { coordinator, autoScanOnMount: autoScanLegacy }),
16199
+ /* @__PURE__ */ import_react7.default.createElement(
16200
+ LegacyImportPanel,
16201
+ {
16202
+ coordinator,
16203
+ autoScanTrigger,
16204
+ onImportSuccess: (summaryText) => {
16205
+ setLastImportDoneText(summaryText || "\u65E7\u7248\u914D\u7F6E\u5DF2\u5BFC\u5165\u5E76\u81EA\u52A8\u5907\u4EFD\u539F\u914D\u7F6E");
16206
+ setImportCloseTrigger(nextFoldTrigger());
16207
+ }
16208
+ }
16209
+ ),
15362
16210
  /* @__PURE__ */ import_react7.default.createElement(
15363
16211
  "div",
15364
16212
  {
@@ -16203,7 +17051,7 @@ var ShipRotationPanel = ({ profile, gameState, updateProfile }) => {
16203
17051
  updateProfile((p) => {
16204
17052
  p.autoChangeShip = checked;
16205
17053
  });
16206
- if (checked) setOpenTrigger((n) => n + 1);
17054
+ if (checked) setOpenTrigger(nextFoldTrigger());
16207
17055
  }
16208
17056
  }
16209
17057
  ), /* @__PURE__ */ import_react9.default.createElement("strong", null, "\u542F\u7528\u81EA\u52A8\u8F6E\u6362")), /* @__PURE__ */ import_react9.default.createElement(
@@ -16966,7 +17814,6 @@ var SortieTab = ({ coordinator, gameState, settings }) => {
16966
17814
  title: "\u5927\u7834\u68C0\u6D4B\u9009\u9879 (\u4EC5\u9650\u5F53\u524D\u65B9\u6848)",
16967
17815
  danger: taihaOverrideActive,
16968
17816
  defaultOpen: taihaOverrideActive,
16969
- forceOpenTrigger: taihaOverrideActive,
16970
17817
  summary: taihaOverrideActive ? /* @__PURE__ */ import_react10.default.createElement("span", { className: "kca-badge kca-badge-err" }, "\u26A0 \u5DF2\u5173\u95ED\u5927\u7834\u4FDD\u62A4") : /* @__PURE__ */ import_react10.default.createElement("span", { className: "kca-badge kca-badge-ok" }, "\u9ED8\u8BA4 7 \u5C42\u4FDD\u62A4\u5F00\u542F")
16971
17818
  },
16972
17819
  /* @__PURE__ */ import_react10.default.createElement("div", { className: "kca-row", style: { gap: 14 } }, /* @__PURE__ */ import_react10.default.createElement("label", { className: "kca-switch" }, /* @__PURE__ */ import_react10.default.createElement(
@@ -17015,7 +17862,7 @@ var SortieTab = ({ coordinator, gameState, settings }) => {
17015
17862
  updateProfile((p) => {
17016
17863
  p.useAdvanceSettings = checked;
17017
17864
  });
17018
- if (checked) setAdvanceOpenTrigger((n) => n + 1);
17865
+ if (checked) setAdvanceOpenTrigger(nextFoldTrigger());
17019
17866
  }
17020
17867
  }
17021
17868
  ), "\u542F\u7528\u9AD8\u7EA7\u89C4\u5219")
@@ -17456,7 +18303,7 @@ var KcaNextApp = ({ coordinator }) => {
17456
18303
  const [gameState, setGameState] = (0, import_react11.useState)(() => coordinator.bridge.getState());
17457
18304
  const [logs, setLogs] = (0, import_react11.useState)(() => [...coordinator.logger.getEntries()]);
17458
18305
  const openLegacyMigration = () => {
17459
- setLegacyImportTrigger((n) => n + 1);
18306
+ setLegacyImportTrigger(nextFoldTrigger());
17460
18307
  setActiveTab("settings");
17461
18308
  };
17462
18309
  (0, import_react11.useEffect)(() => {
@@ -17526,28 +18373,29 @@ var KcaNextApp = ({ coordinator }) => {
17526
18373
  var coordinatorInstance = null;
17527
18374
  function resolveSettingsDir() {
17528
18375
  const appData = typeof window !== "undefined" && window.APPDATA_PATH || process.env.APPDATA || process.cwd();
17529
- return import_node_path3.default.join(appData, "kca-next");
18376
+ return import_node_path4.default.join(appData, "kca-next");
17530
18377
  }
17531
18378
  function createRotatingFileWriter(dir) {
17532
- const logPath = import_node_path3.default.join(dir, "kca-next.log");
18379
+ const logPath = import_node_path4.default.join(dir, "kca-next.log");
17533
18380
  const MAX_BYTES = 5 * 1024 * 1024;
17534
18381
  return (line) => {
17535
- import_node_fs4.default.mkdirSync(dir, { recursive: true });
17536
- if (import_node_fs4.default.existsSync(logPath) && import_node_fs4.default.statSync(logPath).size > MAX_BYTES) {
18382
+ import_node_fs5.default.mkdirSync(dir, { recursive: true });
18383
+ if (import_node_fs5.default.existsSync(logPath) && import_node_fs5.default.statSync(logPath).size > MAX_BYTES) {
17537
18384
  for (let i = 3; i >= 2; i--) {
17538
- const prev = import_node_path3.default.join(dir, `kca-next.${i - 1}.log`);
17539
- const next = import_node_path3.default.join(dir, `kca-next.${i}.log`);
17540
- if (import_node_fs4.default.existsSync(prev)) import_node_fs4.default.renameSync(prev, next);
18385
+ const prev = import_node_path4.default.join(dir, `kca-next.${i - 1}.log`);
18386
+ const next = import_node_path4.default.join(dir, `kca-next.${i}.log`);
18387
+ if (import_node_fs5.default.existsSync(prev)) import_node_fs5.default.renameSync(prev, next);
17541
18388
  }
17542
- import_node_fs4.default.renameSync(logPath, import_node_path3.default.join(dir, "kca-next.1.log"));
18389
+ import_node_fs5.default.renameSync(logPath, import_node_path4.default.join(dir, "kca-next.1.log"));
17543
18390
  }
17544
- import_node_fs4.default.appendFileSync(logPath, `${line}
18391
+ import_node_fs5.default.appendFileSync(logPath, `${line}
17545
18392
  `, "utf8");
17546
18393
  };
17547
18394
  }
17548
18395
  function ensureCoordinator() {
17549
18396
  if (!coordinatorInstance) {
17550
18397
  const dir = resolveSettingsDir();
18398
+ configureFoldStoreDir(dir);
17551
18399
  const bridge = new PoiGameBridge();
17552
18400
  coordinatorInstance = new KcaAssistantCoordinator(bridge, { settingsDir: dir });
17553
18401
  if (coordinatorInstance.getSettings().general.enableFileLog) {