lightfall 0.1.1__py3-none-any.whl

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 (388) hide show
  1. lightfall/__init__.py +8 -0
  2. lightfall/__main__.py +10 -0
  3. lightfall/_version.py +24 -0
  4. lightfall/acquire/__init__.py +74 -0
  5. lightfall/acquire/buffer.py +363 -0
  6. lightfall/acquire/device_wrapper.py +416 -0
  7. lightfall/acquire/engine/__init__.py +155 -0
  8. lightfall/acquire/engine/base.py +587 -0
  9. lightfall/acquire/engine/bluesky.py +358 -0
  10. lightfall/acquire/engine/mock.py +165 -0
  11. lightfall/acquire/engine/plugins/__init__.py +9 -0
  12. lightfall/acquire/engine/plugins/bluesky_plugin.py +56 -0
  13. lightfall/acquire/engine/plugins/mock_plugin.py +55 -0
  14. lightfall/acquire/engine/protocol.py +145 -0
  15. lightfall/acquire/engine/registry.py +152 -0
  16. lightfall/acquire/engine/state.py +32 -0
  17. lightfall/acquire/engine/waiting_hook.py +225 -0
  18. lightfall/acquire/nats_bridge.py +62 -0
  19. lightfall/acquire/plan_ui.py +78 -0
  20. lightfall/acquire/plans/__init__.py +38 -0
  21. lightfall/acquire/plans/adaptive.py +288 -0
  22. lightfall/acquire/plans/example_plans.py +995 -0
  23. lightfall/acquire/plans/lightfall_plans.py +587 -0
  24. lightfall/acquire/plans/registry.py +543 -0
  25. lightfall/acquire/plans/standard_plans.py +186 -0
  26. lightfall/acquire/plans/user_plans.py +470 -0
  27. lightfall/acquire/runengine.py +36 -0
  28. lightfall/acquire/signals.py +452 -0
  29. lightfall/acquire/triggers/__init__.py +16 -0
  30. lightfall/acquire/triggers/base.py +25 -0
  31. lightfall/acquire/triggers/filter.py +37 -0
  32. lightfall/acquire/triggers/manager.py +73 -0
  33. lightfall/acquire/triggers/manual.py +36 -0
  34. lightfall/acquire/triggers/run_end.py +74 -0
  35. lightfall/acquire/triggers/run_start.py +52 -0
  36. lightfall/auth/__init__.py +38 -0
  37. lightfall/auth/policy.py +518 -0
  38. lightfall/auth/providers/__init__.py +30 -0
  39. lightfall/auth/providers/base.py +124 -0
  40. lightfall/auth/providers/keycloak.py +1017 -0
  41. lightfall/auth/providers/local.py +319 -0
  42. lightfall/auth/providers/pam.py +250 -0
  43. lightfall/auth/service_key.py +173 -0
  44. lightfall/auth/service_key_auth.py +79 -0
  45. lightfall/auth/session.py +656 -0
  46. lightfall/claude/__init__.py +52 -0
  47. lightfall/claude/_internal/__init__.py +1 -0
  48. lightfall/claude/_internal/serialization.py +195 -0
  49. lightfall/claude/_internal/threading.py +61 -0
  50. lightfall/claude/_internal/worker.py +757 -0
  51. lightfall/claude/_session_assembly.py +124 -0
  52. lightfall/claude/agent.py +596 -0
  53. lightfall/claude/lightfall_core_tools.py +410 -0
  54. lightfall/claude/markdown.py +103 -0
  55. lightfall/claude/permission_manager.py +588 -0
  56. lightfall/claude/tools/__init__.py +45 -0
  57. lightfall/claude/tools/controller.py +143 -0
  58. lightfall/claude/tools/interaction.py +177 -0
  59. lightfall/claude/tools/introspection.py +127 -0
  60. lightfall/claude/tools/logs.py +155 -0
  61. lightfall/claude/tools/screenshot.py +87 -0
  62. lightfall/claude/widget.py +851 -0
  63. lightfall/claude/widgets/__init__.py +5 -0
  64. lightfall/claude/widgets/permission_request.py +282 -0
  65. lightfall/claude/widgets/question_request.py +227 -0
  66. lightfall/claude/widgets/task_card.py +223 -0
  67. lightfall/config/__init__.py +23 -0
  68. lightfall/config/layers.py +317 -0
  69. lightfall/config/manager.py +244 -0
  70. lightfall/config/schema.py +154 -0
  71. lightfall/core/__init__.py +23 -0
  72. lightfall/core/application.py +727 -0
  73. lightfall/core/services.py +235 -0
  74. lightfall/devices/__init__.py +53 -0
  75. lightfall/devices/backends/__init__.py +17 -0
  76. lightfall/devices/backends/bcs.py +448 -0
  77. lightfall/devices/backends/happi.py +986 -0
  78. lightfall/devices/backends/mock.py +646 -0
  79. lightfall/devices/base.py +338 -0
  80. lightfall/devices/catalog.py +1039 -0
  81. lightfall/devices/connection_manager.py +676 -0
  82. lightfall/devices/model.py +290 -0
  83. lightfall/devices/monitoring.py +442 -0
  84. lightfall/devices/sim/__init__.py +26 -0
  85. lightfall/devices/sim/areadetector.py +436 -0
  86. lightfall/devices/sim/generators.py +223 -0
  87. lightfall/devices/sim/plugins.py +116 -0
  88. lightfall/epics/__init__.py +28 -0
  89. lightfall/epics/ca/__init__.py +10 -0
  90. lightfall/epics/ca/context.py +100 -0
  91. lightfall/epics/ca/pv.py +303 -0
  92. lightfall/epics/widgets/__init__.py +49 -0
  93. lightfall/epics/widgets/areadetector/__init__.py +16 -0
  94. lightfall/epics/widgets/areadetector/areadetector.py +281 -0
  95. lightfall/epics/widgets/areadetector/controls.py +478 -0
  96. lightfall/epics/widgets/areadetector/image_view.py +447 -0
  97. lightfall/epics/widgets/auto.py +319 -0
  98. lightfall/epics/widgets/base.py +404 -0
  99. lightfall/epics/widgets/checkbox.py +239 -0
  100. lightfall/epics/widgets/combobox.py +202 -0
  101. lightfall/epics/widgets/label.py +176 -0
  102. lightfall/epics/widgets/lineedit.py +253 -0
  103. lightfall/epics/widgets/motor.py +694 -0
  104. lightfall/epics/widgets/ophyd_base.py +469 -0
  105. lightfall/epics/widgets/ophyd_combobox.py +86 -0
  106. lightfall/epics/widgets/ophyd_label.py +54 -0
  107. lightfall/epics/widgets/ophyd_lineedit.py +170 -0
  108. lightfall/epics/widgets/ophyd_spinbox.py +79 -0
  109. lightfall/epics/widgets/slider.py +272 -0
  110. lightfall/epics/widgets/status_indicator.py +98 -0
  111. lightfall/epics/widgets/style.py +188 -0
  112. lightfall/exporter/__init__.py +1 -0
  113. lightfall/exporter/cli.py +67 -0
  114. lightfall/exporter/converters/__init__.py +26 -0
  115. lightfall/exporter/converters/base.py +39 -0
  116. lightfall/exporter/converters/noop.py +39 -0
  117. lightfall/exporter/converters/nxsas.py +73 -0
  118. lightfall/exporter/service.py +200 -0
  119. lightfall/exporter/tiled_utils.py +92 -0
  120. lightfall/ipc/__init__.py +6 -0
  121. lightfall/ipc/service.py +701 -0
  122. lightfall/ipc/trust.py +144 -0
  123. lightfall/logbook/__init__.py +46 -0
  124. lightfall/logbook/action_dialog.py +207 -0
  125. lightfall/logbook/action_logger.py +432 -0
  126. lightfall/logbook/block_mapper.py +562 -0
  127. lightfall/logbook/client.py +799 -0
  128. lightfall/logbook/converter.py +273 -0
  129. lightfall/logbook/editors/__init__.py +19 -0
  130. lightfall/logbook/editors/highlighter.py +305 -0
  131. lightfall/logbook/editors/markdown_editor.py +319 -0
  132. lightfall/logbook/editors/richtext_editor.py +1397 -0
  133. lightfall/logbook/entry_widget.py +1065 -0
  134. lightfall/logbook/event_listener.py +221 -0
  135. lightfall/logbook/fragment_widgets.py +925 -0
  136. lightfall/logbook/position_mapper.py +320 -0
  137. lightfall/logbook/protection.py +402 -0
  138. lightfall/logbook/style.py +394 -0
  139. lightfall/logbook/url.py +29 -0
  140. lightfall/logbook/visual_protection.py +330 -0
  141. lightfall/logbook/widget.py +680 -0
  142. lightfall/main.py +1091 -0
  143. lightfall/pipelines/__init__.py +4 -0
  144. lightfall/pipelines/client.py +148 -0
  145. lightfall/plugins/__init__.py +119 -0
  146. lightfall/plugins/agent_plugin.py +106 -0
  147. lightfall/plugins/agents/__init__.py +10 -0
  148. lightfall/plugins/agents/_mcp_helpers.py +52 -0
  149. lightfall/plugins/agents/alignment.py +94 -0
  150. lightfall/plugins/agents/autonomous_experiment/__init__.py +12 -0
  151. lightfall/plugins/agents/autonomous_experiment/nats_tools.py +210 -0
  152. lightfall/plugins/agents/autonomous_experiment/plugin.py +60 -0
  153. lightfall/plugins/agents/autonomous_experiment/prompts.py +164 -0
  154. lightfall/plugins/agents/current_esaf.py +435 -0
  155. lightfall/plugins/agents/device_tools.py +1043 -0
  156. lightfall/plugins/agents/engine_tools.py +720 -0
  157. lightfall/plugins/agents/ipython_tools.py +444 -0
  158. lightfall/plugins/agents/panel_builder.py +637 -0
  159. lightfall/plugins/agents/panel_design/references/cross_panel_patterns.md +95 -0
  160. lightfall/plugins/agents/panel_design/references/panel_design.md +680 -0
  161. lightfall/plugins/agents/panel_design.py +94 -0
  162. lightfall/plugins/agents/plan_design/references/plan_design.md +398 -0
  163. lightfall/plugins/agents/plan_design.py +90 -0
  164. lightfall/plugins/agents/plan_tools.py +878 -0
  165. lightfall/plugins/agents/scan_planning.py +101 -0
  166. lightfall/plugins/builtin_manifest.py +348 -0
  167. lightfall/plugins/controller_plugin.py +162 -0
  168. lightfall/plugins/engine_plugin.py +124 -0
  169. lightfall/plugins/errors.py +104 -0
  170. lightfall/plugins/info.py +112 -0
  171. lightfall/plugins/loader.py +878 -0
  172. lightfall/plugins/manifest.py +150 -0
  173. lightfall/plugins/panel_plugin.py +119 -0
  174. lightfall/plugins/plan_plugin.py +163 -0
  175. lightfall/plugins/registry.py +309 -0
  176. lightfall/plugins/settings_plugin.py +226 -0
  177. lightfall/plugins/statusbar_plugin.py +289 -0
  178. lightfall/plugins/theme_plugin.py +165 -0
  179. lightfall/plugins/types.py +136 -0
  180. lightfall/plugins/user_plugins.py +764 -0
  181. lightfall/project/__init__.py +37 -0
  182. lightfall/project/model.py +375 -0
  183. lightfall/project/service.py +427 -0
  184. lightfall/project/welcome.py +106 -0
  185. lightfall/resources/__init__.py +126 -0
  186. lightfall/resources/images/__init__.py +1 -0
  187. lightfall/resources/images/icon.ico +0 -0
  188. lightfall/resources/images/icon.png +0 -0
  189. lightfall/resources/images/logo.png +0 -0
  190. lightfall/services/__init__.py +33 -0
  191. lightfall/services/_alshub_client.py +73 -0
  192. lightfall/services/access_stamper.py +240 -0
  193. lightfall/services/als_beam_status.py +347 -0
  194. lightfall/services/ca_tunnel.py +325 -0
  195. lightfall/services/threaded_tiled_writer.py +174 -0
  196. lightfall/services/tiled_auth.py +21 -0
  197. lightfall/services/tiled_service.py +971 -0
  198. lightfall/services/tiled_writer_patch.py +301 -0
  199. lightfall/settings/__init__.py +1 -0
  200. lightfall/settings/image_helpers.py +30 -0
  201. lightfall/settings/user_settings_client.py +232 -0
  202. lightfall/ui/__init__.py +28 -0
  203. lightfall/ui/annotations.py +208 -0
  204. lightfall/ui/common/__init__.py +7 -0
  205. lightfall/ui/dialogs/__init__.py +26 -0
  206. lightfall/ui/dialogs/about_dialog.py +131 -0
  207. lightfall/ui/dialogs/add_trigger_dialog.py +152 -0
  208. lightfall/ui/dialogs/base.py +44 -0
  209. lightfall/ui/dialogs/bug_report_dialog.py +353 -0
  210. lightfall/ui/dialogs/create_plan_dialog.py +189 -0
  211. lightfall/ui/dialogs/device_edit_dialog.py +183 -0
  212. lightfall/ui/dialogs/export_dialog.py +565 -0
  213. lightfall/ui/dialogs/go_to_position_dialog.py +192 -0
  214. lightfall/ui/dialogs/login_dialog.py +756 -0
  215. lightfall/ui/dialogs/oauth_browser_dialog.py +305 -0
  216. lightfall/ui/dialogs/run_pipeline_dialog.py +131 -0
  217. lightfall/ui/dialogs/sample_metadata_dialog.py +316 -0
  218. lightfall/ui/docking/__init__.py +22 -0
  219. lightfall/ui/docking/icon_sidebar.py +806 -0
  220. lightfall/ui/docking/manager.py +682 -0
  221. lightfall/ui/docking/state.py +113 -0
  222. lightfall/ui/docking/theme.py +399 -0
  223. lightfall/ui/docking/widget.py +214 -0
  224. lightfall/ui/events.py +75 -0
  225. lightfall/ui/mainwindow.py +1006 -0
  226. lightfall/ui/models/__init__.py +49 -0
  227. lightfall/ui/models/device_selection.py +389 -0
  228. lightfall/ui/models/device_tree.py +1095 -0
  229. lightfall/ui/models/thread_model.py +667 -0
  230. lightfall/ui/models/tiled_model.py +384 -0
  231. lightfall/ui/panels/__init__.py +28 -0
  232. lightfall/ui/panels/base.py +525 -0
  233. lightfall/ui/panels/bluesky_panel.py +619 -0
  234. lightfall/ui/panels/claude/__init__.py +9 -0
  235. lightfall/ui/panels/claude/agent_registry.py +168 -0
  236. lightfall/ui/panels/claude_panel.py +887 -0
  237. lightfall/ui/panels/device_panel.py +370 -0
  238. lightfall/ui/panels/documents_panel.py +166 -0
  239. lightfall/ui/panels/ipython_panel.py +580 -0
  240. lightfall/ui/panels/logbook_entries_panel.py +84 -0
  241. lightfall/ui/panels/logbook_panel.py +627 -0
  242. lightfall/ui/panels/logging_panel.py +587 -0
  243. lightfall/ui/panels/pipeline_jobs_panel.py +160 -0
  244. lightfall/ui/panels/pipeline_triggers_panel.py +170 -0
  245. lightfall/ui/panels/plugins/__init__.py +34 -0
  246. lightfall/ui/panels/plugins/bluesky_plugin.py +27 -0
  247. lightfall/ui/panels/plugins/claude_plugin.py +29 -0
  248. lightfall/ui/panels/plugins/device_plugin.py +27 -0
  249. lightfall/ui/panels/plugins/documents_plugin.py +26 -0
  250. lightfall/ui/panels/plugins/ipython_plugin.py +27 -0
  251. lightfall/ui/panels/plugins/logbook_entries_plugin.py +23 -0
  252. lightfall/ui/panels/plugins/logbook_plugin.py +27 -0
  253. lightfall/ui/panels/plugins/logging_plugin.py +27 -0
  254. lightfall/ui/panels/plugins/pipeline_jobs_plugin.py +23 -0
  255. lightfall/ui/panels/plugins/pipeline_triggers_plugin.py +25 -0
  256. lightfall/ui/panels/plugins/queue_plugin.py +29 -0
  257. lightfall/ui/panels/plugins/synoptic_plugin.py +38 -0
  258. lightfall/ui/panels/plugins/threads_plugin.py +27 -0
  259. lightfall/ui/panels/plugins/tiled_browser_plugin.py +27 -0
  260. lightfall/ui/panels/plugins/visualization_plugin.py +27 -0
  261. lightfall/ui/panels/queue.py +754 -0
  262. lightfall/ui/panels/registry.py +483 -0
  263. lightfall/ui/panels/synoptic/__init__.py +27 -0
  264. lightfall/ui/panels/synoptic/editors.py +481 -0
  265. lightfall/ui/panels/synoptic/items.py +556 -0
  266. lightfall/ui/panels/synoptic/models.py +336 -0
  267. lightfall/ui/panels/synoptic/panel.py +889 -0
  268. lightfall/ui/panels/synoptic/serialization.py +300 -0
  269. lightfall/ui/panels/synoptic/view.py +504 -0
  270. lightfall/ui/panels/threads_panel.py +621 -0
  271. lightfall/ui/panels/tiled_browser_panel.py +854 -0
  272. lightfall/ui/panels/visualization_panel.py +508 -0
  273. lightfall/ui/preferences/__init__.py +24 -0
  274. lightfall/ui/preferences/backend.py +148 -0
  275. lightfall/ui/preferences/builtin.py +220 -0
  276. lightfall/ui/preferences/claude_settings.py +762 -0
  277. lightfall/ui/preferences/device_settings.py +461 -0
  278. lightfall/ui/preferences/dialog.py +234 -0
  279. lightfall/ui/preferences/editor_settings.py +227 -0
  280. lightfall/ui/preferences/ipc_settings.py +226 -0
  281. lightfall/ui/preferences/logbook_settings.py +232 -0
  282. lightfall/ui/preferences/login_settings.py +183 -0
  283. lightfall/ui/preferences/manager.py +562 -0
  284. lightfall/ui/preferences/plugin_settings.py +392 -0
  285. lightfall/ui/preferences/proxy_settings.py +561 -0
  286. lightfall/ui/preferences/skill_settings.py +28 -0
  287. lightfall/ui/preferences/tiled_settings.py +469 -0
  288. lightfall/ui/preferences/tool_settings.py +393 -0
  289. lightfall/ui/preferences/user_portable_backend.py +131 -0
  290. lightfall/ui/preferences/user_profile_settings.py +316 -0
  291. lightfall/ui/preferences/visualization_settings.py +159 -0
  292. lightfall/ui/resources/__init__.py +1 -0
  293. lightfall/ui/resources/logo.png +0 -0
  294. lightfall/ui/statusbar/__init__.py +11 -0
  295. lightfall/ui/statusbar/manager.py +379 -0
  296. lightfall/ui/statusbar/plugins/__init__.py +28 -0
  297. lightfall/ui/statusbar/plugins/als_beam_status.py +218 -0
  298. lightfall/ui/statusbar/plugins/auth_status.py +116 -0
  299. lightfall/ui/statusbar/plugins/connection_status.py +100 -0
  300. lightfall/ui/statusbar/plugins/thread_status.py +556 -0
  301. lightfall/ui/statusbar/plugins/tiled_status.py +179 -0
  302. lightfall/ui/statusbar/plugins/user_status.py +84 -0
  303. lightfall/ui/theater/__init__.py +28 -0
  304. lightfall/ui/theater/manager.py +124 -0
  305. lightfall/ui/theater/overlay.py +279 -0
  306. lightfall/ui/theater/proxy.py +111 -0
  307. lightfall/ui/theme/__init__.py +18 -0
  308. lightfall/ui/theme/builtin.py +1015 -0
  309. lightfall/ui/theme/manager.py +875 -0
  310. lightfall/ui/theme/registry.py +195 -0
  311. lightfall/ui/toast.py +221 -0
  312. lightfall/ui/tutorial.py +1100 -0
  313. lightfall/ui/widgets/__init__.py +110 -0
  314. lightfall/ui/widgets/base_control.py +259 -0
  315. lightfall/ui/widgets/camera/__init__.py +36 -0
  316. lightfall/ui/widgets/camera/base.py +815 -0
  317. lightfall/ui/widgets/camera/dark_frames.py +213 -0
  318. lightfall/ui/widgets/camera/image_view.py +649 -0
  319. lightfall/ui/widgets/camera/panels/__init__.py +14 -0
  320. lightfall/ui/widgets/camera/panels/cooler.py +320 -0
  321. lightfall/ui/widgets/camera/panels/temperature.py +192 -0
  322. lightfall/ui/widgets/camera/plan_based.py +202 -0
  323. lightfall/ui/widgets/compact_motor.py +522 -0
  324. lightfall/ui/widgets/controller_matcher.py +278 -0
  325. lightfall/ui/widgets/controller_registry.py +144 -0
  326. lightfall/ui/widgets/device_control.py +411 -0
  327. lightfall/ui/widgets/device_selector.py +438 -0
  328. lightfall/ui/widgets/device_tree_tab.py +461 -0
  329. lightfall/ui/widgets/document_stream.py +1028 -0
  330. lightfall/ui/widgets/favorites_tab.py +191 -0
  331. lightfall/ui/widgets/motor_control.py +1120 -0
  332. lightfall/ui/widgets/observers/__init__.py +8 -0
  333. lightfall/ui/widgets/observers/camera.py +48 -0
  334. lightfall/ui/widgets/observers/image_view.py +130 -0
  335. lightfall/ui/widgets/plan_config.py +954 -0
  336. lightfall/ui/widgets/plan_edit_dialog.py +294 -0
  337. lightfall/ui/widgets/plan_selector.py +452 -0
  338. lightfall/ui/widgets/profile_avatar.py +128 -0
  339. lightfall/ui/widgets/queue_view.py +647 -0
  340. lightfall/ui/widgets/runengine_control.py +549 -0
  341. lightfall/ui/widgets/signal_control.py +793 -0
  342. lightfall/ui/widgets/skill_trigger_button.py +183 -0
  343. lightfall/ui/widgets/tiled_filter_widget.py +314 -0
  344. lightfall/ui/widgets/tiled_status.py +149 -0
  345. lightfall/ui/widgets/warning_banner.py +185 -0
  346. lightfall/utils/__init__.py +53 -0
  347. lightfall/utils/crash_diagnostics.py +454 -0
  348. lightfall/utils/data_migration.py +22 -0
  349. lightfall/utils/editor_launcher.py +594 -0
  350. lightfall/utils/error_collector.py +245 -0
  351. lightfall/utils/git_tracker.py +197 -0
  352. lightfall/utils/log_buffer.py +233 -0
  353. lightfall/utils/logging.py +229 -0
  354. lightfall/utils/module_resolver.py +70 -0
  355. lightfall/utils/sentry.py +722 -0
  356. lightfall/utils/threads.py +991 -0
  357. lightfall/utils/tiled_helpers.py +96 -0
  358. lightfall/visualization/__init__.py +50 -0
  359. lightfall/visualization/base.py +5 -0
  360. lightfall/visualization/base_visualization.py +74 -0
  361. lightfall/visualization/fitting/__init__.py +24 -0
  362. lightfall/visualization/fitting/base.py +267 -0
  363. lightfall/visualization/fitting/fitters.py +325 -0
  364. lightfall/visualization/fitting/panel.py +265 -0
  365. lightfall/visualization/memory.py +392 -0
  366. lightfall/visualization/motor_mixin.py +524 -0
  367. lightfall/visualization/pg.py +156 -0
  368. lightfall/visualization/registry.py +144 -0
  369. lightfall/visualization/spec.py +79 -0
  370. lightfall/visualization/theme.py +266 -0
  371. lightfall/visualization/widgets/__init__.py +28 -0
  372. lightfall/visualization/widgets/adaptive/__init__.py +1 -0
  373. lightfall/visualization/widgets/adaptive/heatmap.py +655 -0
  374. lightfall/visualization/widgets/adaptive/plot.py +233 -0
  375. lightfall/visualization/widgets/heatmap.py +264 -0
  376. lightfall/visualization/widgets/image_stack.py +316 -0
  377. lightfall/visualization/widgets/image_view_toolbar.py +227 -0
  378. lightfall/visualization/widgets/lazy_image_view.py +590 -0
  379. lightfall/visualization/widgets/plot_1d.py +262 -0
  380. lightfall/visualization/widgets/scatter.py +247 -0
  381. lightfall/visualization/widgets/table.py +221 -0
  382. lightfall/visualization/widgets/time_axis.py +93 -0
  383. lightfall-0.1.1.dist-info/METADATA +223 -0
  384. lightfall-0.1.1.dist-info/RECORD +388 -0
  385. lightfall-0.1.1.dist-info/WHEEL +4 -0
  386. lightfall-0.1.1.dist-info/entry_points.txt +6 -0
  387. lightfall-0.1.1.dist-info/licenses/LEGAL.md +13 -0
  388. lightfall-0.1.1.dist-info/licenses/LICENSE.md +33 -0
@@ -0,0 +1,799 @@
1
+ """
2
+ Local-first logbook client with optional server sync.
3
+
4
+ Provides a singleton ``LogbookClient`` that persists logbook data in a local
5
+ SQLite database (``~/.lightfall/logbook.db``). All writes go to the local
6
+ database first (offline-first). Sync to a remote server happens in a
7
+ background thread when configured.
8
+
9
+ Uses synchronous sqlite3 for simplicity — local disk I/O is fast enough
10
+ and avoids async/Qt event loop integration issues.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import sqlite3
17
+ import threading
18
+ import uuid
19
+ from datetime import UTC, datetime
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from PySide6.QtCore import QTimer
24
+
25
+ from lightfall.auth.service_key_auth import ServiceKeyAuth
26
+ from lightfall.utils.logging import logger
27
+ from lightfall.utils.threads import QThreadFuture, thread_manager
28
+
29
+ try:
30
+ import httpx
31
+ except ImportError: # pragma: no cover
32
+ httpx = None # type: ignore[assignment]
33
+
34
+
35
+ def _uuid() -> str:
36
+ return str(uuid.uuid4())
37
+
38
+
39
+ def _now() -> str:
40
+ return datetime.now(UTC).isoformat()
41
+
42
+
43
+ _SCHEMA = """
44
+ CREATE TABLE IF NOT EXISTS logbook (
45
+ id TEXT PRIMARY KEY,
46
+ user_id TEXT NOT NULL UNIQUE,
47
+ created_at TEXT NOT NULL
48
+ );
49
+
50
+ CREATE TABLE IF NOT EXISTS entry (
51
+ id TEXT PRIMARY KEY,
52
+ logbook_id TEXT NOT NULL REFERENCES logbook(id),
53
+ title TEXT,
54
+ tags TEXT NOT NULL DEFAULT '[]',
55
+ created_at TEXT NOT NULL,
56
+ updated_at TEXT NOT NULL,
57
+ sync_status TEXT NOT NULL DEFAULT 'pending'
58
+ );
59
+
60
+ CREATE TABLE IF NOT EXISTS fragment (
61
+ id TEXT PRIMARY KEY,
62
+ entry_id TEXT NOT NULL REFERENCES entry(id),
63
+ position INTEGER NOT NULL DEFAULT 0,
64
+ kind TEXT NOT NULL DEFAULT 'text',
65
+ subtype TEXT,
66
+ content TEXT NOT NULL DEFAULT '',
67
+ data TEXT,
68
+ created_at TEXT NOT NULL,
69
+ updated_at TEXT NOT NULL,
70
+ sync_status TEXT NOT NULL DEFAULT 'pending'
71
+ );
72
+
73
+ CREATE TABLE IF NOT EXISTS image_sync (
74
+ image_id TEXT PRIMARY KEY,
75
+ local_path TEXT NOT NULL,
76
+ sync_status TEXT NOT NULL DEFAULT 'pending_upload'
77
+ );
78
+
79
+ CREATE INDEX IF NOT EXISTS idx_entry_logbook ON entry(logbook_id);
80
+ CREATE INDEX IF NOT EXISTS idx_fragment_entry ON fragment(entry_id);
81
+ """
82
+
83
+
84
+ def _mime_from_ext(ext: str) -> str:
85
+ """Map file extension to MIME type."""
86
+ return {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif"}.get(
87
+ ext.lower(), "image/png"
88
+ )
89
+
90
+
91
+ _MIME_TO_EXT = {"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif"}
92
+
93
+
94
+ def _run_sync(db_path: str, server_url: str, user_id: str | None = None) -> tuple[int, int]:
95
+ """Run logbook sync (push pending → pull remote). Returns (pushed, pulled).
96
+
97
+ Designed to run inside a QThreadFuture — pure function, no Qt objects.
98
+ """
99
+ if httpx is None:
100
+ return (0, 0)
101
+
102
+ pushed = pulled = 0
103
+ db = sqlite3.connect(db_path)
104
+ db.row_factory = sqlite3.Row
105
+
106
+ # Use proxy settings if configured
107
+ client_kwargs: dict[str, Any] = {"base_url": server_url, "timeout": 10}
108
+ # Per-service API key auth — reads from SessionManager cache per request
109
+ client_kwargs["auth"] = ServiceKeyAuth("logbook")
110
+ if user_id:
111
+ # Dev-mode passthrough: when the logbook server is configured without
112
+ # Keycloak, its CombinedAuthMiddleware falls through unauthenticated
113
+ # requests and the API layer reads X-User-Id to identify the user.
114
+ # In prod the apikey carries identity and this header is ignored.
115
+ client_kwargs["headers"] = {"X-User-Id": user_id}
116
+ try:
117
+ from lightfall.ui.preferences.proxy_settings import ProxySettingsProvider
118
+ proxy_url = ProxySettingsProvider.should_use_proxy_for_url(server_url)
119
+ if proxy_url:
120
+ client_kwargs["proxy"] = proxy_url
121
+ logger.debug("Logbook sync using proxy: {}", proxy_url)
122
+ except Exception:
123
+ pass
124
+
125
+ try:
126
+ with httpx.Client(**client_kwargs) as client:
127
+ # ── Phase 1: Push images (before metadata so server has file before fragment references it)
128
+ try:
129
+ cursor = db.execute(
130
+ "SELECT image_id, local_path FROM image_sync WHERE sync_status = 'pending_upload'"
131
+ )
132
+ for image_id, local_path in cursor.fetchall():
133
+ path = Path(local_path)
134
+ if not path.exists():
135
+ db.execute(
136
+ "UPDATE image_sync SET sync_status = 'synced' WHERE image_id = ?",
137
+ (image_id,),
138
+ )
139
+ continue
140
+ try:
141
+ with open(path, "rb") as f:
142
+ resp = client.post(
143
+ "/logbook/images",
144
+ files={"file": (path.name, f, _mime_from_ext(path.suffix))},
145
+ )
146
+ if resp.status_code == 201:
147
+ db.execute(
148
+ "UPDATE image_sync SET sync_status = 'synced' WHERE image_id = ?",
149
+ (image_id,),
150
+ )
151
+ pushed += 1
152
+ except Exception as exc:
153
+ logger.debug("Image upload failed for {}: {}", image_id, exc)
154
+ db.commit()
155
+ except Exception as exc:
156
+ logger.debug("Image push phase failed: {}", exc)
157
+ # Push pending entries (PUT to update, POST to create if 404)
158
+ for row in db.execute("SELECT * FROM entry WHERE sync_status = 'pending'"):
159
+ r = dict(row)
160
+ r["tags"] = json.loads(r["tags"]) if isinstance(r["tags"], str) else r["tags"]
161
+ try:
162
+ resp = client.put(f"/logbook/entries/{r['id']}", json=r)
163
+ if resp.status_code == 404:
164
+ resp = client.post("/logbook/entries", json={
165
+ "id": r["id"],
166
+ "title": r.get("title"),
167
+ "tags": r.get("tags", []),
168
+ })
169
+ if not resp.is_success:
170
+ logger.warning("Entry sync failed ({}): {}", resp.status_code, resp.text[:200])
171
+ if resp.is_success:
172
+ db.execute("UPDATE entry SET sync_status = 'synced' WHERE id = ?", (r["id"],))
173
+ pushed += 1
174
+ except Exception:
175
+ pass
176
+
177
+ # Push pending fragments (PUT to update, POST to create if 404)
178
+ for row in db.execute("SELECT * FROM fragment WHERE sync_status = 'pending'"):
179
+ r = dict(row)
180
+ logger.debug("Syncing fragment id={} (type={}, len={})", r["id"], type(r["id"]).__name__, len(str(r["id"])))
181
+ if r.get("data") and isinstance(r["data"], str):
182
+ r["data"] = json.loads(r["data"])
183
+ try:
184
+ resp = client.put(f"/logbook/fragments/{r['id']}", json=r)
185
+ if resp.status_code == 404:
186
+ resp = client.post(f"/logbook/entries/{r['entry_id']}/fragments", json={
187
+ "id": r["id"],
188
+ "kind": r.get("kind", "text"),
189
+ "subtype": r.get("subtype"),
190
+ "content": r.get("content", ""),
191
+ "data": r.get("data"),
192
+ "position": r.get("position", 0),
193
+ })
194
+ if not resp.is_success:
195
+ logger.warning("Fragment sync failed ({}): {}", resp.status_code, resp.text[:200])
196
+ if resp.is_success:
197
+ db.execute("UPDATE fragment SET sync_status = 'synced' WHERE id = ?", (r["id"],))
198
+ pushed += 1
199
+ except Exception:
200
+ pass
201
+
202
+ db.commit()
203
+
204
+ # ── Pull: fetch server entries and upsert locally ─────
205
+ try:
206
+ resp = client.get("/logbook/entries")
207
+ if resp.is_success:
208
+ remote_entries = resp.json()
209
+ for re in remote_entries:
210
+ eid = str(re["id"])
211
+ local = db.execute("SELECT id, updated_at FROM entry WHERE id = ?", (eid,)).fetchone()
212
+ logbook_id = str(re["logbook_id"])
213
+
214
+ # Ensure logbook row exists locally
215
+ if not db.execute("SELECT id FROM logbook WHERE id = ?", (logbook_id,)).fetchone():
216
+ db.execute(
217
+ "INSERT OR IGNORE INTO logbook (id, user_id, created_at) VALUES (?, ?, ?)",
218
+ (logbook_id, user_id or "unknown", re.get("created_at", _now())),
219
+ )
220
+
221
+ if local is None:
222
+ db.execute(
223
+ "INSERT INTO entry (id, logbook_id, title, tags, created_at, updated_at, sync_status) "
224
+ "VALUES (?, ?, ?, ?, ?, ?, 'synced')",
225
+ (eid, logbook_id, re.get("title"),
226
+ json.dumps(re.get("tags", [])),
227
+ re.get("created_at", _now()), re.get("updated_at", _now())),
228
+ )
229
+ pulled += 1
230
+ elif local["updated_at"] < re.get("updated_at", ""):
231
+ cur = db.execute("SELECT sync_status FROM entry WHERE id = ?", (eid,)).fetchone()
232
+ if cur and cur["sync_status"] != "pending":
233
+ db.execute(
234
+ "UPDATE entry SET title = ?, tags = ?, updated_at = ?, sync_status = 'synced' WHERE id = ?",
235
+ (re.get("title"), json.dumps(re.get("tags", [])), re.get("updated_at"), eid),
236
+ )
237
+ pulled += 1
238
+
239
+ # Pull fragments for this entry
240
+ for rf in re.get("fragments", []):
241
+ fid = str(rf["id"])
242
+ local_frag = db.execute("SELECT id, updated_at, sync_status FROM fragment WHERE id = ?", (fid,)).fetchone()
243
+ if local_frag is None:
244
+ db.execute(
245
+ "INSERT INTO fragment (id, entry_id, position, kind, subtype, content, data, created_at, updated_at, sync_status) "
246
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced')",
247
+ (fid, eid, rf.get("position", 0), rf.get("kind", "text"),
248
+ rf.get("subtype"), rf.get("content", ""),
249
+ json.dumps(rf.get("data")) if rf.get("data") else None,
250
+ rf.get("created_at", _now()), rf.get("updated_at", _now())),
251
+ )
252
+ pulled += 1
253
+ elif local_frag["sync_status"] != "pending" and local_frag["updated_at"] < rf.get("updated_at", ""):
254
+ db.execute(
255
+ "UPDATE fragment SET position = ?, content = ?, data = ?, updated_at = ?, sync_status = 'synced' WHERE id = ?",
256
+ (rf.get("position", 0), rf.get("content", ""),
257
+ json.dumps(rf.get("data")) if rf.get("data") else None,
258
+ rf.get("updated_at"), fid),
259
+ )
260
+ pulled += 1
261
+
262
+ db.commit()
263
+ except Exception as exc:
264
+ logger.warning("Pull sync failed: {}", exc)
265
+
266
+ # ── Phase 4: Pull images (download missing image files after metadata pull)
267
+ try:
268
+ cursor = db.execute(
269
+ "SELECT id, data FROM fragment WHERE kind = 'image'"
270
+ )
271
+ image_dir = Path.home() / ".lightfall" / "logbook" / "images"
272
+ image_dir.mkdir(parents=True, exist_ok=True)
273
+
274
+ for _frag_id, data_json in cursor.fetchall():
275
+ frag_data = json.loads(data_json) if data_json else {}
276
+ img_id = frag_data.get("image_id")
277
+ if not img_id:
278
+ continue
279
+
280
+ # Check if already synced
281
+ existing = db.execute(
282
+ "SELECT sync_status FROM image_sync WHERE image_id = ?", (img_id,)
283
+ ).fetchone()
284
+ if existing and existing["sync_status"] == "synced":
285
+ continue
286
+
287
+ # Check if file exists on disk
288
+ mime_type = frag_data.get("mime_type", "image/png")
289
+ ext = _MIME_TO_EXT.get(mime_type, ".png")
290
+ local_path = image_dir / f"{img_id}{ext}"
291
+
292
+ if local_path.exists():
293
+ db.execute(
294
+ "INSERT OR REPLACE INTO image_sync (image_id, local_path, sync_status) VALUES (?, ?, 'synced')",
295
+ (img_id, str(local_path)),
296
+ )
297
+ continue
298
+
299
+ # Download from server
300
+ try:
301
+ resp = client.get(f"/logbook/images/{img_id}")
302
+ if resp.status_code == 200:
303
+ local_path.write_bytes(resp.content)
304
+ db.execute(
305
+ "INSERT OR REPLACE INTO image_sync (image_id, local_path, sync_status) VALUES (?, ?, 'synced')",
306
+ (img_id, str(local_path)),
307
+ )
308
+ pulled += 1
309
+ except Exception as exc:
310
+ logger.debug("Image download failed for {}: {}", img_id, exc)
311
+ db.execute(
312
+ "INSERT OR IGNORE INTO image_sync (image_id, local_path, sync_status) VALUES (?, ?, 'pending_download')",
313
+ (img_id, str(local_path)),
314
+ )
315
+ db.commit()
316
+ except Exception as exc:
317
+ logger.debug("Image pull phase failed: {}", exc)
318
+ finally:
319
+ db.close()
320
+
321
+ return (pushed, pulled)
322
+
323
+
324
+ class LogbookClient:
325
+ """Offline-first logbook persistence with optional remote sync.
326
+
327
+ All operations are synchronous (local SQLite). Remote sync runs
328
+ in a background QThread.
329
+
330
+ Usage::
331
+
332
+ client = LogbookClient.get_instance()
333
+ client.init()
334
+ logbook_id = client.get_or_create_logbook("rp")
335
+ entry_id = client.create_entry(logbook_id, title="Shift 1")
336
+ """
337
+
338
+ _instance: LogbookClient | None = None
339
+ _lock = threading.Lock()
340
+
341
+ def __init__(self) -> None:
342
+ self._db: sqlite3.Connection | None = None
343
+ self._db_path = Path.home() / ".lightfall" / "logbook.db"
344
+ self._server_url: str | None = None
345
+ self._offline_only = False
346
+ self._initialized = False
347
+ self._sync_timer: QTimer | None = None
348
+ self._on_pull_callback: callable | None = None
349
+ self._on_sync_error_callback: callable | None = None
350
+ self._on_sync_restored_callback: callable | None = None
351
+ self._on_entry_created_callback: callable | None = None
352
+ self._sync_failed = False
353
+
354
+ @classmethod
355
+ def get_instance(cls) -> LogbookClient:
356
+ if cls._instance is None:
357
+ with cls._lock:
358
+ if cls._instance is None:
359
+ cls._instance = cls()
360
+ return cls._instance
361
+
362
+ @classmethod
363
+ def reset(cls) -> None:
364
+ with cls._lock:
365
+ cls._instance = None
366
+
367
+ def init(self) -> None:
368
+ """Open/create the local database and apply schema."""
369
+ if self._initialized:
370
+ return
371
+
372
+ self._load_preferences()
373
+ self._db_path.parent.mkdir(parents=True, exist_ok=True)
374
+
375
+ self._db = sqlite3.connect(str(self._db_path))
376
+ self._db.row_factory = sqlite3.Row
377
+ self._db.executescript(_SCHEMA)
378
+ self._db.commit()
379
+ self._initialized = True
380
+ logger.info("LogbookClient initialised (db={})", self._db_path)
381
+ self.schedule_sync()
382
+
383
+ def purge_synced(self) -> None:
384
+ """Remove all locally-synced data, keeping only pending (unsynced) rows.
385
+
386
+ Called on close/logout so the local DB stays lean — it's a
387
+ temporary buffer, not a growing archive.
388
+ """
389
+ db = self._ensure_db()
390
+ # Delete synced fragments first (FK order)
391
+ db.execute("DELETE FROM fragment WHERE sync_status = 'synced'")
392
+ # Delete synced entries that have no remaining fragments
393
+ db.execute(
394
+ "DELETE FROM entry WHERE sync_status = 'synced' "
395
+ "AND id NOT IN (SELECT DISTINCT entry_id FROM fragment)"
396
+ )
397
+ # Delete logbooks with no remaining entries
398
+ db.execute(
399
+ "DELETE FROM logbook WHERE id NOT IN (SELECT DISTINCT logbook_id FROM entry)"
400
+ )
401
+ db.commit()
402
+ db.execute("VACUUM")
403
+ logger.info("Purged synced content from local logbook DB")
404
+
405
+ def close(self) -> None:
406
+ if self._db:
407
+ try:
408
+ self.purge_synced()
409
+ except Exception as exc:
410
+ logger.warning("Failed to purge synced data on close: {}", exc)
411
+ self._db.close()
412
+ self._db = None
413
+ self._initialized = False
414
+
415
+ def _load_preferences(self) -> None:
416
+ from lightfall.logbook.url import get_logbook_base_url
417
+ try:
418
+ from lightfall.ui.preferences.manager import PreferencesManager
419
+ prefs = PreferencesManager.get_instance()
420
+ self._server_url = get_logbook_base_url()
421
+ self._offline_only = prefs.get("logbook_offline_only", False)
422
+ except Exception:
423
+ logger.debug("Could not load logbook preferences, using defaults")
424
+
425
+ def _ensure_db(self) -> sqlite3.Connection:
426
+ if self._db is None:
427
+ raise RuntimeError("LogbookClient not initialised — call init() first")
428
+ return self._db
429
+
430
+ # ── Logbook ───────────────────────────────────────────────────
431
+
432
+ def get_or_create_logbook(self, user_id: str) -> str:
433
+ db = self._ensure_db()
434
+ row = db.execute("SELECT id FROM logbook WHERE user_id = ?", (user_id,)).fetchone()
435
+ if row:
436
+ return row["id"]
437
+ logbook_id = _uuid()
438
+ db.execute(
439
+ "INSERT INTO logbook (id, user_id, created_at) VALUES (?, ?, ?)",
440
+ (logbook_id, user_id, _now()),
441
+ )
442
+ db.commit()
443
+ logger.info("Created logbook {} for user {}", logbook_id, user_id)
444
+ return logbook_id
445
+
446
+ # ── Entry CRUD ────────────────────────────────────────────────
447
+
448
+ def create_entry(
449
+ self,
450
+ logbook_id: str,
451
+ *,
452
+ title: str | None = None,
453
+ tags: list[str] | None = None,
454
+ entry_id: str | None = None,
455
+ ) -> str:
456
+ db = self._ensure_db()
457
+ eid = entry_id or _uuid()
458
+ now = _now()
459
+ db.execute(
460
+ "INSERT INTO entry (id, logbook_id, title, tags, created_at, updated_at, sync_status) "
461
+ "VALUES (?, ?, ?, ?, ?, ?, 'pending')",
462
+ (eid, logbook_id, title, json.dumps(tags or []), now, now),
463
+ )
464
+ db.commit()
465
+ if self._on_entry_created_callback:
466
+ cb = self._on_entry_created_callback
467
+ QTimer.singleShot(0, lambda: cb(eid, logbook_id))
468
+ self.schedule_sync()
469
+ return eid
470
+
471
+ def list_entries(self, logbook_id: str) -> list[dict[str, Any]]:
472
+ db = self._ensure_db()
473
+ rows = db.execute(
474
+ "SELECT * FROM entry WHERE logbook_id = ? ORDER BY created_at DESC",
475
+ (logbook_id,),
476
+ ).fetchall()
477
+ return [dict(r) for r in rows]
478
+
479
+ def get_entry(self, entry_id: str) -> dict[str, Any] | None:
480
+ db = self._ensure_db()
481
+ row = db.execute("SELECT * FROM entry WHERE id = ?", (entry_id,)).fetchone()
482
+ return dict(row) if row else None
483
+
484
+ def update_entry(
485
+ self, entry_id: str, *, title: str | None = None, tags: list[str] | None = None
486
+ ) -> None:
487
+ db = self._ensure_db()
488
+ parts: list[str] = ["updated_at = ?", "sync_status = 'pending'"]
489
+ params: list[Any] = [_now()]
490
+ if title is not None:
491
+ parts.append("title = ?")
492
+ params.append(title)
493
+ if tags is not None:
494
+ parts.append("tags = ?")
495
+ params.append(json.dumps(tags))
496
+ params.append(entry_id)
497
+ db.execute(f"UPDATE entry SET {', '.join(parts)} WHERE id = ?", params)
498
+ db.commit()
499
+ self.schedule_sync()
500
+
501
+ def delete_entry(self, entry_id: str) -> None:
502
+ db = self._ensure_db()
503
+ db.execute("DELETE FROM fragment WHERE entry_id = ?", (entry_id,))
504
+ db.execute("DELETE FROM entry WHERE id = ?", (entry_id,))
505
+ db.commit()
506
+ self.schedule_sync()
507
+
508
+ # ── Fragment CRUD ─────────────────────────────────────────────
509
+
510
+ def add_fragment(
511
+ self,
512
+ entry_id: str,
513
+ *,
514
+ kind: str = "text",
515
+ subtype: str | None = None,
516
+ content: str = "",
517
+ data: dict[str, Any] | None = None,
518
+ position: int | None = None,
519
+ fragment_id: str | None = None,
520
+ ) -> str:
521
+ db = self._ensure_db()
522
+ fid = fragment_id or _uuid()
523
+ now = _now()
524
+ if position is None:
525
+ row = db.execute(
526
+ "SELECT COALESCE(MAX(position), -1) + 1 AS pos FROM fragment WHERE entry_id = ?",
527
+ (entry_id,),
528
+ ).fetchone()
529
+ position = row["pos"] if row else 0
530
+ db.execute(
531
+ "INSERT INTO fragment (id, entry_id, position, kind, subtype, content, data, "
532
+ "created_at, updated_at, sync_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')",
533
+ (fid, entry_id, position, kind, subtype, content,
534
+ json.dumps(data) if data else None, now, now),
535
+ )
536
+ db.commit()
537
+ self.schedule_sync()
538
+ return fid
539
+
540
+ def update_fragment(
541
+ self,
542
+ fragment_id: str,
543
+ *,
544
+ content: str | None = None,
545
+ data: dict[str, Any] | None = None,
546
+ position: int | None = None,
547
+ ) -> None:
548
+ db = self._ensure_db()
549
+ parts: list[str] = ["updated_at = ?", "sync_status = 'pending'"]
550
+ params: list[Any] = [_now()]
551
+ if content is not None:
552
+ parts.append("content = ?")
553
+ params.append(content)
554
+ if data is not None:
555
+ parts.append("data = ?")
556
+ params.append(json.dumps(data))
557
+ if position is not None:
558
+ parts.append("position = ?")
559
+ params.append(position)
560
+ params.append(fragment_id)
561
+ db.execute(f"UPDATE fragment SET {', '.join(parts)} WHERE id = ?", params)
562
+ db.commit()
563
+ self.schedule_sync()
564
+
565
+ def reorder_fragments(self, entry_id: str, fragment_ids: list[str]) -> None:
566
+ """Update fragment positions to match the given order."""
567
+ db = self._ensure_db()
568
+ for pos, fid in enumerate(fragment_ids):
569
+ db.execute(
570
+ "UPDATE fragment SET position = ?, sync_status = 'pending' WHERE id = ? AND entry_id = ?",
571
+ (pos, fid, entry_id),
572
+ )
573
+ db.commit()
574
+ self.schedule_sync()
575
+
576
+ def delete_fragment(self, fragment_id: str) -> None:
577
+ db = self._ensure_db()
578
+ db.execute("DELETE FROM fragment WHERE id = ?", (fragment_id,))
579
+ db.commit()
580
+ self.schedule_sync()
581
+
582
+ def list_fragments(self, entry_id: str) -> list[dict[str, Any]]:
583
+ db = self._ensure_db()
584
+ rows = db.execute(
585
+ "SELECT * FROM fragment WHERE entry_id = ? ORDER BY position",
586
+ (entry_id,),
587
+ ).fetchall()
588
+ return [dict(r) for r in rows]
589
+
590
+ # ── Images ───────────────────────────────────────────────────
591
+
592
+ _MIME_TO_EXT = {
593
+ "image/png": ".png",
594
+ "image/jpeg": ".jpg",
595
+ "image/gif": ".gif",
596
+ }
597
+ _EXT_TO_MIME = {v: k for k, v in _MIME_TO_EXT.items()}
598
+
599
+ @property
600
+ def _image_dir(self) -> Path:
601
+ """Local image storage directory."""
602
+ d = Path.home() / ".lightfall" / "logbook" / "images"
603
+ d.mkdir(parents=True, exist_ok=True)
604
+ return d
605
+
606
+ def _save_image_locally(self, image_id: str, data: bytes, mime_type: str) -> Path:
607
+ """Save image bytes to local storage, return the file path."""
608
+ ext = self._MIME_TO_EXT.get(mime_type, ".png")
609
+ path = self._image_dir / f"{image_id}{ext}"
610
+ path.write_bytes(data)
611
+ return path
612
+
613
+ def _get_local_image_path(self, image_id: str) -> Path | None:
614
+ """Find a locally stored image by ID, or None if not present."""
615
+ for ext in self._MIME_TO_EXT.values():
616
+ path = self._image_dir / f"{image_id}{ext}"
617
+ if path.exists():
618
+ return path
619
+ return None
620
+
621
+ def add_image(
622
+ self,
623
+ image: Any,
624
+ caption: str = "",
625
+ subtype: str = "clipboard",
626
+ entry_id: str | None = None,
627
+ ) -> str:
628
+ """Add an image fragment to the logbook.
629
+
630
+ Args:
631
+ image: Image as raw bytes, file path (str/Path), QImage, or QPixmap.
632
+ caption: Optional caption text.
633
+ subtype: Fragment subtype for styling.
634
+ entry_id: Target entry ID. None = current entry (caller must provide).
635
+
636
+ Returns:
637
+ The new fragment ID.
638
+ """
639
+ from PySide6.QtCore import QBuffer, QIODevice
640
+ from PySide6.QtGui import QImage, QPixmap
641
+
642
+ # Normalize input to bytes + mime_type
643
+ if isinstance(image, QPixmap):
644
+ image = image.toImage()
645
+ if isinstance(image, QImage):
646
+ buf = QBuffer()
647
+ buf.open(QIODevice.OpenModeFlag.WriteOnly)
648
+ image.save(buf, "PNG")
649
+ data = bytes(buf.data())
650
+ mime_type = "image/png"
651
+ elif isinstance(image, (str, Path)):
652
+ path = Path(image)
653
+ data = path.read_bytes()
654
+ mime_type = self._EXT_TO_MIME.get(path.suffix.lower(), "image/png")
655
+ elif isinstance(image, bytes):
656
+ data = image
657
+ if data[:2] == b"\xff\xd8":
658
+ mime_type = "image/jpeg"
659
+ elif data[:4] == b"GIF8":
660
+ mime_type = "image/gif"
661
+ else:
662
+ mime_type = "image/png"
663
+ else:
664
+ raise TypeError(f"Unsupported image type: {type(image)}")
665
+
666
+ image_id = _uuid()
667
+
668
+ # Save to local disk
669
+ local_path = self._save_image_locally(image_id, data, mime_type)
670
+
671
+ # Get image dimensions
672
+ qimg = QImage()
673
+ qimg.loadFromData(data)
674
+ width = qimg.width() if not qimg.isNull() else 0
675
+ height = qimg.height() if not qimg.isNull() else 0
676
+
677
+ ext = self._MIME_TO_EXT.get(mime_type, ".png")
678
+ filename = f"{image_id}{ext}"
679
+
680
+ if entry_id is None:
681
+ raise ValueError("entry_id is required (no current entry tracking yet)")
682
+
683
+ # Create image fragment in local DB
684
+ fragment_id = self.add_fragment(
685
+ entry_id,
686
+ kind="image",
687
+ subtype=subtype,
688
+ content=caption,
689
+ data={
690
+ "image_id": image_id,
691
+ "filename": filename,
692
+ "mime_type": mime_type,
693
+ "width": width,
694
+ "height": height,
695
+ "size_bytes": len(data),
696
+ },
697
+ )
698
+
699
+ # Track for sync
700
+ db = self._ensure_db()
701
+ db.execute(
702
+ "INSERT OR REPLACE INTO image_sync (image_id, local_path, sync_status) VALUES (?, ?, ?)",
703
+ (image_id, str(local_path), "pending_upload"),
704
+ )
705
+ db.commit()
706
+
707
+ self.schedule_sync()
708
+ return fragment_id
709
+
710
+ # ── Sync ──────────────────────────────────────────────────────
711
+
712
+ def set_on_pull_callback(self, callback: callable) -> None:
713
+ """Register a callback to be invoked when data is pulled from the server."""
714
+ self._on_pull_callback = callback
715
+
716
+ def set_on_entry_created_callback(self, callback: callable) -> None:
717
+ """Register a callback invoked when an entry is created locally.
718
+
719
+ The callback receives ``(entry_id, logbook_id)``.
720
+ """
721
+ self._on_entry_created_callback = callback
722
+
723
+ def schedule_sync(self) -> None:
724
+ """Debounce sync — waits 2s after last mutation before starting."""
725
+ if self._offline_only or not self._server_url:
726
+ return
727
+ if self._sync_timer is None:
728
+ self._sync_timer = QTimer()
729
+ self._sync_timer.setSingleShot(True)
730
+ self._sync_timer.timeout.connect(self._do_sync)
731
+ # Restart the 2s debounce timer on each call
732
+ self._sync_timer.start(2000)
733
+
734
+ @staticmethod
735
+ def _is_guest_user() -> bool:
736
+ """Check if the current user is a guest (no sync for guests)."""
737
+ try:
738
+ from lightfall.auth.policy import Role
739
+ from lightfall.auth.session import SessionManager
740
+ user = SessionManager.get_instance().current_user
741
+ return user.highest_role == Role.GUEST
742
+ except Exception:
743
+ return False
744
+
745
+ def _do_sync(self) -> None:
746
+ """Actually start the background sync via QThreadFuture."""
747
+ # Don't sync for guest users — their data is local-only
748
+ if self._is_guest_user():
749
+ logger.debug("Skipping logbook sync for guest user")
750
+ return
751
+
752
+ # If a sync is already running, re-schedule to pick up new changes after
753
+ existing = thread_manager.get_by_key("logbook-sync")
754
+ if existing and existing.running:
755
+ self._sync_timer.start(2000)
756
+ return
757
+
758
+ # Get user ID from session manager if available. The user is identified
759
+ # by the apikey record on the server side under ServiceKeyAuth; the
760
+ # local user_id is still needed downstream to upsert local logbook rows.
761
+ user_id: str | None = None
762
+ try:
763
+ from lightfall.auth.session import SessionManager
764
+ sm = SessionManager.get_instance()
765
+ user = sm.current_user
766
+ if user and user.username:
767
+ user_id = user.username
768
+ except Exception:
769
+ pass
770
+
771
+ QThreadFuture(
772
+ _run_sync,
773
+ str(self._db_path),
774
+ self._server_url,
775
+ user_id,
776
+ callback_slot=self._on_sync_done,
777
+ except_slot=self._on_sync_error,
778
+ key="logbook-sync",
779
+ name="logbook-sync",
780
+ ).start()
781
+
782
+ def _on_sync_done(self, result: tuple[int, int]) -> None:
783
+ pushed, pulled = result
784
+ if pushed or pulled:
785
+ logger.info("Sync complete: {} pushed, {} pulled", pushed, pulled)
786
+ if pulled > 0 and self._on_pull_callback:
787
+ self._on_pull_callback()
788
+ # Connection restored after previous failure
789
+ if self._sync_failed:
790
+ self._sync_failed = False
791
+ if self._on_sync_restored_callback:
792
+ self._on_sync_restored_callback()
793
+
794
+ def _on_sync_error(self, exc: Exception) -> None:
795
+ logger.warning("Sync failed: {}", exc)
796
+ if not self._sync_failed:
797
+ self._sync_failed = True
798
+ if self._on_sync_error_callback:
799
+ self._on_sync_error_callback()