-
Notifications
You must be signed in to change notification settings - Fork 298
Expand file tree
/
Copy pathstorage_location_router.py
More file actions
1892 lines (1677 loc) · 72 KB
/
Copy pathstorage_location_router.py
File metadata and controls
1892 lines (1677 loc) · 72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2025-2026 Project N.E.K.O. Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Storage-location bootstrap API for the main web app.
Stage 3 keeps the same homepage bootstrap entry, adds the shutdown/restart
checkpoint flow, and exposes maintenance-state diagnostics for the web UI.
URL convention: routes declared WITHOUT trailing slash (no ``@router.get('/')``).
See ``main_routers/characters_router.py`` docstring or
``.agent/rules/neko-guide.md`` (§"API URL 末尾不带斜杠") for the rationale;
enforced by ``scripts/check_api_trailing_slash.py``.
"""
from __future__ import annotations
import asyncio
import logging
import os
import shutil
import sys
import inspect
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from fastapi import APIRouter, Request, Response
from pydantic import BaseModel, Field, field_validator
from config import APP_NAME
from main_routers.shared_state import (
get_config_manager,
get_request_app_shutdown,
get_release_storage_startup_barrier,
)
from utils.cloudsave_runtime import (
ROOT_MODE_MAINTENANCE_READONLY,
ROOT_MODE_NORMAL,
cloudsave_disabled_reason,
is_cloudsave_disabled_due_to_local_state_unavailable,
set_root_mode,
)
from utils.storage_location_bootstrap import (
STORAGE_STARTUP_BLOCKING_REASONS,
STORAGE_STATUS_POLL_INTERVAL_MS,
build_storage_location_bootstrap_payload,
)
from utils.storage_migration import (
MIGRATED_RUNTIME_ENTRY_NAMES,
STORAGE_MIGRATION_STATUS_COMPLETED,
STORAGE_MIGRATION_STATUS_FAILED,
create_pending_storage_migration,
delete_storage_migration,
is_retained_root_cleanup_available,
load_storage_migration,
save_storage_migration,
)
from utils.storage_policy import (
StorageSelectionValidationError,
compute_anchor_root,
get_storage_policy_path,
is_runtime_root_available,
load_storage_policy,
normalize_runtime_root,
paths_equal,
save_storage_policy,
validate_selected_root,
)
from utils.config_manager import get_config_manager as get_runtime_config_manager
router = APIRouter(prefix="/api/storage/location", tags=["storage_location"])
logger = logging.getLogger(__name__)
_storage_mutation_lock = asyncio.Lock()
# _STORAGE_MUTATION_STAYS_ON_LOOP
#
# 本文件里所有写存储状态的调用**刻意**留在事件循环上(各处 noqa: ASYNC_BLOCK 指向
# 这里)。落盘本身是同步的、带无上界的 fsync,按理该挪进 to_thread —— 但这里有两条
# 独立的理由压过它,任缺其一都会造成比循环卡顿严重得多的后果。
#
# 一、这些写是**取消原子**的序列,而它们之间今天一个 await 都没有。
# 典型形状:delete_storage_migration → save_storage_policy → set_root_mode。
# 任何一处插进 await,请求超时或应用关闭产生的 CancelledError 就能落在中间:
# 恢复检查点已删、策略已写,而 root mode 还是旧值。CancelledError 是
# BaseException,外层 `except Exception` 接不住,也就没人回滚 —— 用户会得到
# 一个「恢复闸自相矛盾」的盘上状态。
#
# 二、root_state 有一个**不在锁里**的写者。
# build_storage_location_bootstrap_payload → _reconcile_legacy_cleanup_pending_
# root_state(utils/storage/location_bootstrap.py:191)会 save_root_state,它挂在
# GET /bootstrap、/status、/diagnostics、/retained-source 和 POST /exit 上,这些
# 都不在 _storage_mutation_lock 覆盖下。今天让「GET 侧 reconcile」和「变更路由的
# 写」互斥的不是锁,是**它们都跑在同一条事件循环线程上**。把任何一个 root_state
# 写者挪进 worker,前端存储页每 500ms 的 /status 轮询就能把它整份盖掉。
#
# 真正的收口是给 root_state 一把真锁,并让 GET 路由别在读路径上写盘。在那之前,
# 这个文件宁可让罕见的存储变更请求同步落盘。
class StorageLocationSelectionRequest(BaseModel):
selected_root: str = Field(..., min_length=1, max_length=4096)
selection_source: str = Field(default="user_selected", min_length=1, max_length=64)
confirm_existing_target_content: bool = False
@field_validator("selected_root", "selection_source")
@classmethod
def _strip_whitespace(cls, value: str) -> str:
stripped = str(value or "").strip()
if not stripped:
raise ValueError("value cannot be empty")
return stripped
class StorageLocationCleanupRequest(BaseModel):
retained_root: str = Field(default="", min_length=0, max_length=4096)
class StorageLocationDirectoryPickerRequest(BaseModel):
start_path: str = Field(default="", min_length=0, max_length=4096)
class _DirectoryPickerCancelled(Exception):
pass
class _DirectoryPickerUnavailable(RuntimeError):
def __init__(self, error_code: str, message: str):
super().__init__(message)
self.error_code = str(error_code or "directory_picker_unavailable").strip() or "directory_picker_unavailable"
self.message = str(message or "当前环境暂不支持系统目录选择,请手动输入路径。").strip() or "当前环境暂不支持系统目录选择,请手动输入路径。"
class _OpenStorageRootUnavailable(RuntimeError):
def __init__(self, error_code: str, message: str):
super().__init__(message)
self.error_code = str(error_code or "open_storage_root_unavailable").strip() or "open_storage_root_unavailable"
self.message = str(message or "当前环境暂不支持直接打开目录。").strip() or "当前环境暂不支持直接打开目录。"
def _set_no_cache_headers(response: Response) -> None:
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
def _reject_storage_mutation_when_cloudsave_disabled(response: Response) -> dict[str, Any] | None:
if not is_cloudsave_disabled_due_to_local_state_unavailable():
return None
response.status_code = 409
return {
"ok": False,
"error_code": "cloudsave_local_state_unavailable",
"error": "本机状态目录不可用,当前会话已禁用云存档。请先修复本机 state 路径后重启应用,再进行存储位置变更。",
"cloudsave_disabled": True,
"cloudsave_disabled_reason": cloudsave_disabled_reason(),
}
def _normalize_optional_path(value: Any) -> str:
raw_value = str(value or "").strip()
if not raw_value:
return ""
return str(normalize_runtime_root(raw_value))
def _path_is_within(candidate: Path | str | None, root: Path | str | None) -> bool:
if not candidate or not root:
return False
candidate_path = normalize_runtime_root(candidate)
root_path = normalize_runtime_root(root)
try:
candidate_path.relative_to(root_path)
return True
except ValueError:
return False
def _dedupe_paths(paths: list[Path | str]) -> list[str]:
normalized_paths: list[str] = []
seen: set[str] = set()
for candidate in paths:
normalized = _normalize_optional_path(candidate)
if not normalized or normalized in seen:
continue
seen.add(normalized)
normalized_paths.append(normalized)
return normalized_paths
def _get_storage_config_manager():
try:
return get_config_manager()
except RuntimeError:
# During limited startup, the storage bootstrap endpoints must stay usable
# even if main_server shared_state has not been fully published yet.
return get_runtime_config_manager(APP_NAME, migrate=False)
def _snapshot_storage_mutation_state(config_manager, *, anchor_root: Path) -> dict[str, Any]:
return {
"root_state": config_manager.load_root_state(),
"policy": load_storage_policy(config_manager, anchor_root=anchor_root),
"migration": load_storage_migration(config_manager, anchor_root=anchor_root),
}
def _restore_storage_mutation_state(
config_manager,
snapshot: dict[str, Any],
*,
anchor_root: Path,
) -> None:
previous_migration = snapshot.get("migration")
if isinstance(previous_migration, dict):
save_storage_migration(config_manager, previous_migration, anchor_root=anchor_root)
else:
delete_storage_migration(config_manager, anchor_root=anchor_root)
policy_path = get_storage_policy_path(config_manager, anchor_root=anchor_root)
previous_policy = snapshot.get("policy")
if isinstance(previous_policy, dict):
from utils.file_utils import atomic_write_json
atomic_write_json(policy_path, previous_policy, ensure_ascii=False, indent=2)
else:
try:
os.unlink(policy_path)
except FileNotFoundError:
pass
previous_root_state = snapshot.get("root_state")
if isinstance(previous_root_state, dict):
config_manager.save_root_state(previous_root_state)
async def _release_storage_startup_barrier_or_rollback(
config_manager,
*,
snapshot: dict[str, Any],
anchor_root: Path,
reason: str,
) -> None:
try:
await _release_storage_startup_barrier_if_needed(reason=reason)
except Exception:
try:
# 这一处**刻意**留在事件循环上。_restore_storage_mutation_state 的最后
# 一步是 config_manager.save_root_state(),而 root_state 还有另一个写者:
# build_storage_location_bootstrap_payload → _reconcile_legacy_cleanup_
# pending_root_state(utils/storage/location_bootstrap.py:191)也会
# save_root_state,它挂在 GET /bootstrap、/status、/diagnostics、
# /retained-source 和 POST /exit 上 —— 这几条**都不在
# _storage_mutation_lock 覆盖下**(锁只包 cleanup / select / restart 三条)。
#
# 今天让这两个「读 root_state — 改 — 写回」互斥的,不是锁,而是「它们都跑在
# 同一条事件循环线程上」。把回滚搬进 worker 就恰好打破这个不变量:前端存储页
# 每 500ms 轮询 /status,回滚写 root_state 的同时那边正拿着读到的旧 dict 往
# 回写,回滚会被整份盖掉 —— 迁移检查点和策略回滚了、root_state 没有,下次启动
# recovery_required 直接算成 False,恢复闸被跳过。
#
# 正确的收口是给 root_state 一把真锁、并让 GET 路由别在读路径上写盘,那是
# 独立的一份工作。在那之前,宁可让这条罕见的回滚路径同步落盘。
_restore_storage_mutation_state(config_manager, snapshot, anchor_root=anchor_root) # noqa: ASYNC_BLOCK — 末步 save_root_state 与无锁 GET 路由的 root_state 读改写互斥,只靠「同在循环线程」保证
except Exception:
logger.exception(
"failed to rollback storage mutation state after startup barrier release failed",
)
raise
def _safe_path_size(path: Path) -> int:
try:
if path.is_symlink():
return 0
if path.is_file():
return int(path.stat().st_size)
if not path.is_dir():
return 0
except OSError:
return 0
total = 0
stack = [path]
while stack:
current = stack.pop()
try:
children = list(current.iterdir())
except OSError:
continue
for child in children:
try:
if child.is_symlink():
continue
if child.is_dir():
stack.append(child)
continue
if child.is_file():
total += int(child.stat().st_size)
except OSError:
continue
return total
def _estimate_runtime_payload_bytes(source_root: Path) -> int:
total = 0
for name in MIGRATED_RUNTIME_ENTRY_NAMES:
total += _safe_path_size(source_root / name)
return total
def _target_root_has_user_content(target_root: Path, config_manager) -> bool:
try:
from utils.cloudsave_runtime import runtime_root_has_user_content
return bool(runtime_root_has_user_content(target_root, config_manager=config_manager))
except Exception:
if not target_root.exists() or not target_root.is_dir():
return False
try:
return any(target_root.iterdir())
except OSError:
return False
def _find_existing_ancestor(path: Path) -> Path:
candidate = path.expanduser()
while True:
if candidate.exists():
return candidate
parent = candidate.parent
if parent == candidate:
return candidate
candidate = parent
def _path_chain_has_symlink(path: Path) -> bool:
candidate = path.expanduser()
while True:
if candidate.exists():
try:
return candidate.is_symlink()
except OSError:
return False
parent = candidate.parent
if parent == candidate:
return False
candidate = parent
def _path_segments(path: Path) -> list[str]:
return [
segment.strip().lower()
for segment in str(path).replace("\\", "/").split("/")
if segment.strip()
]
def _is_cloud_sync_path_segment(segment: str) -> bool:
normalized_segment = str(segment or "").strip().lower()
def matches_client_folder(prefix: str) -> bool:
if normalized_segment == prefix:
return True
if not normalized_segment.startswith(prefix):
return False
suffix = normalized_segment[len(prefix) :].lstrip()
return bool(suffix) and suffix[0] in {"(", "-", "["}
if any(
matches_client_folder(prefix)
for prefix in ("icloud drive", "google drive", "googledrive", "dropbox")
):
return True
return (
normalized_segment == "onedrive"
or normalized_segment.startswith("onedrive - ")
or normalized_segment.startswith("onedrive (")
)
def _collect_warning_codes(current_root: Path, target_root: Path) -> list[str]:
warning_codes: list[str] = []
raw_target = str(target_root)
normalized_target = raw_target.replace("\\", "/").lower()
if any(_is_cloud_sync_path_segment(segment) for segment in _path_segments(target_root)):
warning_codes.append("sync_folder")
if raw_target.startswith("\\\\") or normalized_target.startswith("//"):
warning_codes.append("network_share")
if _path_chain_has_symlink(target_root):
warning_codes.append("symlink_path")
if sys.platform == "win32":
current_drive = str(current_root.drive or "").lower()
target_drive = str(target_root.drive or "").lower()
if current_drive and target_drive and current_drive != target_drive:
warning_codes.append("external_volume")
elif normalized_target.startswith("/volumes/") or normalized_target.startswith("/media/") or normalized_target.startswith("/mnt/"):
warning_codes.append("external_volume")
return sorted(set(warning_codes))
def _build_restart_preflight(
current_root: Path,
target_root: Path,
*,
config_manager=None,
estimated_required_bytes: int | None = None,
allow_existing_target_content: bool = False,
) -> dict[str, Any]:
target_root = normalize_runtime_root(target_root)
if estimated_required_bytes is None:
estimated_required_bytes = _estimate_runtime_payload_bytes(current_root)
existing_anchor = _find_existing_ancestor(target_root)
target_free_bytes = 0
try:
target_free_bytes = int(shutil.disk_usage(str(existing_anchor)).free)
except OSError:
target_free_bytes = 0
if target_root.exists():
permission_probe = target_root
else:
permission_probe = existing_anchor
permission_ok = os.access(str(permission_probe), os.W_OK)
target_has_existing_content = bool(
config_manager is not None
and _target_root_has_user_content(target_root, config_manager)
)
requires_existing_target_confirmation = bool(
target_has_existing_content
and not allow_existing_target_content
)
blocking_error_code = ""
blocking_error_message = ""
if not permission_ok:
blocking_error_code = "target_not_writable"
blocking_error_message = "目标路径当前不可写,无法开始关闭后的迁移流程。"
elif (
estimated_required_bytes > 0
and target_free_bytes > 0
and target_free_bytes < estimated_required_bytes
):
blocking_error_code = "insufficient_space"
blocking_error_message = "目标卷剩余空间不足,无法安全执行关闭后的迁移。"
return {
"target_root": str(target_root),
"estimated_required_bytes": estimated_required_bytes,
"target_free_bytes": target_free_bytes,
"permission_ok": permission_ok,
"warning_codes": _collect_warning_codes(current_root, target_root),
"target_has_existing_content": target_has_existing_content,
"requires_existing_target_confirmation": requires_existing_target_confirmation,
"existing_target_confirmation_message": (
"目标路径已经包含现有数据。确认后迁移会覆盖目标中的同名运行时数据目录,"
"目标目录中的其他文件会保留。请确认已选择正确目录。"
if requires_existing_target_confirmation
else ""
),
"blocking_error_code": blocking_error_code,
"blocking_error_message": blocking_error_message,
}
def _load_committed_selected_root(config_manager, *, anchor_root: Path, fallback_root: Path) -> Path:
policy = load_storage_policy(config_manager, anchor_root=anchor_root)
if not isinstance(policy, dict):
return fallback_root
selected_root_value = str(policy.get("selected_root") or "").strip()
if not selected_root_value:
return fallback_root
try:
return normalize_runtime_root(selected_root_value)
except Exception:
return fallback_root
def _is_selected_root_missing_recovery(config_manager, *, current_root: Path, anchor_root: Path) -> bool:
if not bool(getattr(config_manager, "recovery_committed_root_unavailable", False)):
return False
committed_selected_root = _load_committed_selected_root(
config_manager,
anchor_root=anchor_root,
fallback_root=current_root,
)
return not paths_equal(committed_selected_root, current_root)
def _build_maintenance_message(bootstrap_payload: dict[str, Any]) -> str:
blocking_reason = str(bootstrap_payload.get("blocking_reason") or "").strip()
last_error_summary = str(bootstrap_payload.get("last_error_summary") or "").strip()
if blocking_reason == "migration_pending":
return "正在优化存储布局,当前实例关闭后会继续迁移并自动恢复。"
if blocking_reason == "recovery_required":
return last_error_summary or "检测到需要恢复的存储状态,请先重新确认本次使用的存储位置。"
if blocking_reason == "selection_required":
return "需要先确认本次运行使用的存储位置,主页主功能会继续保持阻断。"
return ""
def _normalize_directory_picker_start_path(raw_value: str) -> str:
candidate_text = str(raw_value or "").strip()
if not candidate_text:
return ""
try:
candidate = normalize_runtime_root(candidate_text)
except Exception:
candidate = Path(candidate_text).expanduser()
if not candidate.is_absolute():
return ""
if candidate.exists() and candidate.is_dir():
return str(candidate)
current = candidate.parent
while current != current.parent:
if current.exists() and current.is_dir():
return str(current)
current = current.parent
if current.exists() and current.is_dir():
return str(current)
return ""
def _resolve_executable_name(*candidates: str) -> str:
for candidate in candidates:
if not candidate:
continue
if os.path.isabs(candidate) and os.path.exists(candidate):
return candidate
resolved = shutil.which(candidate)
if resolved:
return resolved
return candidates[0]
def _pick_directory_via_osascript(*, start_path: str) -> str:
command = [_resolve_executable_name("/usr/bin/osascript", "osascript")]
if start_path:
safe_start_path = start_path.replace("\\", "\\\\").replace('"', '\\"')
command.extend(
[
"-e",
'tell application "Finder" to activate',
"-e",
f'set defaultLocation to POSIX file "{safe_start_path}"',
"-e",
'set selectedFolder to choose folder with prompt "请选择存储位置目录" default location defaultLocation',
]
)
else:
command.extend(
[
"-e",
'tell application "Finder" to activate',
"-e",
'set selectedFolder to choose folder with prompt "请选择存储位置目录"',
]
)
command.extend(["-e", "POSIX path of selectedFolder"])
try:
completed = subprocess.run(
command,
capture_output=True,
text=True,
check=False,
timeout=120,
)
except FileNotFoundError as exc:
raise _DirectoryPickerUnavailable(
"directory_picker_unavailable",
"当前环境暂不支持系统目录选择,请手动输入路径。",
) from exc
except Exception as exc:
raise _DirectoryPickerUnavailable(
"directory_picker_unavailable",
f"打开系统目录选择器失败: {exc}",
) from exc
if completed.returncode != 0:
stderr = str(completed.stderr or "").strip()
if "User canceled" in stderr or "(-128)" in stderr:
raise _DirectoryPickerCancelled()
raise _DirectoryPickerUnavailable(
"directory_picker_failed",
f"打开系统目录选择器失败: {stderr or completed.returncode}",
)
selected_root = str(completed.stdout or "").strip()
if not selected_root:
raise _DirectoryPickerCancelled()
return selected_root
def _pick_directory_via_powershell(*, start_path: str) -> str:
powershell_executable = _resolve_executable_name(
os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
"powershell.exe",
"powershell",
"pwsh.exe",
"pwsh",
)
if not os.path.isabs(powershell_executable) and not shutil.which(powershell_executable):
raise _DirectoryPickerUnavailable(
"directory_picker_unavailable",
"当前系统未找到 PowerShell,无法打开目录选择器。",
)
escaped_start_path = start_path.replace("'", "''")
script = """
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$owner = New-Object System.Windows.Forms.Form
$owner.Text = 'N.E.K.O'
$owner.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$owner.Size = New-Object System.Drawing.Size(1, 1)
$owner.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedToolWindow
$owner.ShowInTaskbar = $false
$owner.Opacity = 0
$owner.TopMost = $true
$dialog = New-Object System.Windows.Forms.FolderBrowserDialog
$dialog.Description = '请选择存储位置目录'
$dialog.ShowNewFolderButton = $true
if ('{start_path}') {{
$dialog.SelectedPath = '{start_path}'
}}
$owner.Show()
$owner.Activate()
$owner.BringToFront()
[System.Windows.Forms.Application]::DoEvents()
$result = $dialog.ShowDialog($owner)
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {{
Write-Output $dialog.SelectedPath
exit 0
}}
exit 2
""".strip().format(start_path=escaped_start_path)
try:
completed = subprocess.run(
[powershell_executable, "-NoProfile", "-STA", "-Command", script],
capture_output=True,
text=True,
check=False,
timeout=120,
)
except FileNotFoundError as exc:
raise _DirectoryPickerUnavailable(
"directory_picker_unavailable",
"当前系统未找到 PowerShell,无法打开目录选择器。",
) from exc
except Exception as exc:
raise _DirectoryPickerUnavailable(
"directory_picker_failed",
f"打开系统目录选择器失败: {exc}",
) from exc
if completed.returncode == 2:
raise _DirectoryPickerCancelled()
if completed.returncode != 0:
stderr = str(completed.stderr or "").strip()
raise _DirectoryPickerUnavailable(
"directory_picker_failed",
f"打开系统目录选择器失败: {stderr or completed.returncode}",
)
selected_root = str(completed.stdout or "").strip()
if not selected_root:
raise _DirectoryPickerCancelled()
return selected_root
def _pick_directory_via_linux_dialog(*, start_path: str) -> str:
commands: list[list[str]] = []
zenity_executable = _resolve_executable_name("/usr/bin/zenity", "/bin/zenity", "zenity")
if os.path.isabs(zenity_executable) and os.path.exists(zenity_executable) or shutil.which(zenity_executable):
command = [zenity_executable, "--file-selection", "--directory", "--title=请选择存储位置目录"]
if start_path:
command.append(f"--filename={start_path.rstrip('/')}/")
commands.append(command)
kdialog_executable = _resolve_executable_name("/usr/bin/kdialog", "/bin/kdialog", "kdialog")
if os.path.isabs(kdialog_executable) and os.path.exists(kdialog_executable) or shutil.which(kdialog_executable):
command = [kdialog_executable, "--getexistingdirectory"]
if start_path:
command.append(start_path)
commands.append(command)
yad_executable = _resolve_executable_name("/usr/bin/yad", "/bin/yad", "yad")
if os.path.isabs(yad_executable) and os.path.exists(yad_executable) or shutil.which(yad_executable):
command = [yad_executable, "--file-selection", "--directory", "--title=请选择存储位置目录"]
if start_path:
command.append(f"--filename={start_path.rstrip('/')}/")
commands.append(command)
if not commands:
raise _DirectoryPickerUnavailable(
"directory_picker_unavailable",
"当前系统未安装可用的图形目录选择器。",
)
last_error = None
for command in commands:
try:
completed = subprocess.run(
command,
capture_output=True,
text=True,
check=False,
timeout=120,
)
except Exception as exc:
last_error = exc
continue
if completed.returncode == 0:
selected_root = str(completed.stdout or "").strip()
if selected_root:
return selected_root
raise _DirectoryPickerCancelled()
if completed.returncode in (1, 252):
raise _DirectoryPickerCancelled()
last_error = str(completed.stderr or "").strip() or completed.returncode
raise _DirectoryPickerUnavailable(
"directory_picker_failed",
f"打开系统目录选择器失败: {last_error}",
)
def _pick_storage_location_directory(*, start_path: str) -> str:
# 项目策略:不带 Tk/Tcl。每个平台只信任其原生桥(osascript / PowerShell /
# zenity-kdialog-yad),原生桥失败就直接 _DirectoryPickerUnavailable,让前端
# 提示用户手填路径——而不是落到 tkinter 兜底(Nuitka 不带 tk-inter 时
# tk.Tk() 抛 SystemExit 拖死后端)。检查由 scripts/check_no_tkinter.py 守门。
normalized_start_path = _normalize_directory_picker_start_path(start_path)
if sys.platform == "darwin":
return _pick_directory_via_osascript(start_path=normalized_start_path)
if sys.platform == "win32":
return _pick_directory_via_powershell(start_path=normalized_start_path)
return _pick_directory_via_linux_dialog(start_path=normalized_start_path)
def _open_path_in_file_manager(path: Path | str) -> None:
target_path = normalize_runtime_root(path)
if not target_path.exists() or not target_path.is_dir():
raise _OpenStorageRootUnavailable(
"storage_root_unavailable",
"当前数据目录不存在或不可访问。",
)
try:
if sys.platform == "win32":
os.startfile(str(target_path)) # type: ignore[attr-defined]
return
if sys.platform == "darwin":
subprocess.Popen(["open", str(target_path)])
return
opener = shutil.which("xdg-open") or shutil.which("gio")
if not opener:
raise _OpenStorageRootUnavailable(
"open_storage_root_unavailable",
"当前系统未找到可用的文件管理器打开命令。",
)
if os.path.basename(opener) == "gio":
subprocess.Popen([opener, "open", str(target_path)])
else:
subprocess.Popen([opener, str(target_path)])
except _OpenStorageRootUnavailable:
raise
except Exception as exc:
raise _OpenStorageRootUnavailable(
"open_storage_root_failed",
f"打开当前数据目录失败: {exc}",
) from exc
def _build_status_payload(config_manager) -> dict[str, Any]:
bootstrap_payload = build_storage_location_bootstrap_payload(config_manager)
blocking_reason = str(bootstrap_payload.get("blocking_reason") or "").strip()
migration_payload = bootstrap_payload.get("migration") if isinstance(bootstrap_payload.get("migration"), dict) else {}
completion_notice = _build_completed_migration_notice(config_manager, bootstrap_payload=bootstrap_payload)
lifecycle_state = "ready"
if blocking_reason == "migration_pending":
lifecycle_state = "maintenance"
elif blocking_reason == "recovery_required":
lifecycle_state = "recovery_required"
elif blocking_reason == "selection_required":
lifecycle_state = "selection_required"
return {
"ok": True,
"ready": lifecycle_state == "ready",
"status": lifecycle_state,
"lifecycle_state": lifecycle_state,
"migration_stage": str(migration_payload.get("status") or "").strip(),
"maintenance_message": _build_maintenance_message(bootstrap_payload),
"poll_interval_ms": int(bootstrap_payload.get("poll_interval_ms") or STORAGE_STATUS_POLL_INTERVAL_MS),
"effective_root": str(normalize_runtime_root(config_manager.app_docs_dir)),
"last_error_summary": str(bootstrap_payload.get("last_error_summary") or "").strip(),
"blocking_reason": blocking_reason,
"completion_notice": completion_notice,
"storage": {
"selection_required": bool(bootstrap_payload.get("selection_required")),
"migration_pending": bool(bootstrap_payload.get("migration_pending")),
"recovery_required": bool(bootstrap_payload.get("recovery_required")),
"legacy_cleanup_pending": bool(bootstrap_payload.get("legacy_cleanup_pending")),
"stage": bootstrap_payload.get("stage") or "",
},
"migration": migration_payload,
}
def _build_runtime_entry_diagnostic(
*,
name: str,
write_root: Path | str,
read_roots: list[Path | str],
effective_root: Path | str,
retained_source_root: Path | str | None,
notes: list[str] | None = None,
) -> dict[str, Any]:
normalized_write_root = _normalize_optional_path(write_root)
normalized_read_roots = _dedupe_paths(read_roots)
reads_outside_effective_root = [
path for path in normalized_read_roots if not _path_is_within(path, effective_root)
]
reads_from_retained_source_root = [
path for path in normalized_read_roots if _path_is_within(path, retained_source_root)
]
return {
"name": name,
"write_root": normalized_write_root,
"read_roots": normalized_read_roots,
"write_within_effective_root": _path_is_within(normalized_write_root, effective_root),
"reads_outside_effective_root": reads_outside_effective_root,
"reads_from_retained_source_root": reads_from_retained_source_root,
"all_reads_within_effective_root": not reads_outside_effective_root,
"notes": list(notes or []),
}
def _build_storage_location_diagnostics_payload(config_manager) -> dict[str, Any]:
bootstrap_payload = build_storage_location_bootstrap_payload(config_manager)
migration_payload = (
bootstrap_payload.get("migration")
if isinstance(bootstrap_payload.get("migration"), dict)
else {}
)
effective_root = normalize_runtime_root(config_manager.app_docs_dir)
anchor_root = normalize_runtime_root(config_manager.anchor_root)
committed_selected_root = normalize_runtime_root(
getattr(config_manager, "committed_selected_root", config_manager.app_docs_dir)
)
retained_source_root = _normalize_optional_path(
migration_payload.get("retained_source_root")
or migration_payload.get("backup_root")
or ""
)
live2d_lookup = getattr(config_manager, "get_live2d_lookup_roots", None)
if callable(live2d_lookup):
live2d_read_roots = list(live2d_lookup())
else:
live2d_read_roots = [getattr(config_manager, "live2d_dir", effective_root / "live2d")]
runtime_entries = {
"config": _build_runtime_entry_diagnostic(
name="config",
write_root=config_manager.config_dir,
read_roots=[config_manager.config_dir],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
"memory": _build_runtime_entry_diagnostic(
name="memory",
write_root=config_manager.memory_dir,
read_roots=[config_manager.memory_dir],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
"plugins": _build_runtime_entry_diagnostic(
name="plugins",
write_root=config_manager.plugins_dir,
read_roots=[config_manager.plugins_dir],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
"live2d": _build_runtime_entry_diagnostic(
name="live2d",
write_root=config_manager.live2d_dir,
read_roots=live2d_read_roots,
effective_root=effective_root,
retained_source_root=retained_source_root,
notes=(
["windows_cfa_fallback_read_enabled"]
if bool(getattr(config_manager, "is_windows_cfa_fallback_active", False))
else []
),
),
"vrm": _build_runtime_entry_diagnostic(
name="vrm",
write_root=config_manager.vrm_dir,
read_roots=[config_manager.vrm_dir],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
"mmd": _build_runtime_entry_diagnostic(
name="mmd",
write_root=config_manager.mmd_dir,
read_roots=[config_manager.mmd_dir],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
"workshop": _build_runtime_entry_diagnostic(
name="workshop",
write_root=config_manager.workshop_dir,
read_roots=[config_manager.workshop_dir],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
"character_cards": _build_runtime_entry_diagnostic(
name="character_cards",
write_root=config_manager.chara_dir,
read_roots=[config_manager.chara_dir],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
"jukebox": _build_runtime_entry_diagnostic(
name="jukebox",
write_root=Path(config_manager.app_docs_dir) / "jukebox",
read_roots=[Path(config_manager.app_docs_dir) / "jukebox"],
effective_root=effective_root,
retained_source_root=retained_source_root,
),
}
entries_with_reads_outside_effective_root = [
name
for name, payload in runtime_entries.items()
if payload["reads_outside_effective_root"]
]
entries_reading_retained_source_root = [
name
for name, payload in runtime_entries.items()
if payload["reads_from_retained_source_root"]
]
return {
"ok": True,
"layout": {
"effective_root": str(effective_root),
"committed_selected_root": str(committed_selected_root),
"reported_current_root": _normalize_optional_path(
getattr(config_manager, "reported_current_root", config_manager.app_docs_dir)
),
"anchor_root": str(anchor_root),
"retained_source_root": retained_source_root,
"cloudsave_root": str(config_manager.cloudsave_dir),
"state_root": str(config_manager.local_state_dir),
"recovery_committed_root_unavailable": bool(
getattr(config_manager, "recovery_committed_root_unavailable", False)
),
"windows_cfa_fallback_active": bool(
getattr(config_manager, "is_windows_cfa_fallback_active", False)
),
},
"runtime_entries": runtime_entries,
"anchored_entries": {
"cloudsave": {
"root": _normalize_optional_path(config_manager.cloudsave_dir),
"anchored_to": "anchor_root",
},
"state": {
"root": _normalize_optional_path(config_manager.local_state_dir),
"anchored_to": "anchor_root",