@goodpeanuts/dsh-sui 0.1.0 → 0.1.2-fix.1

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.
package/README.md CHANGED
@@ -18,7 +18,9 @@ dsh plugin --profile web add @goodpeanuts/dsh-sui
18
18
 
19
19
  ### 首次登录与同步
20
20
 
21
- 首次使用时,先停止使用同一数据目录的宿主,在终端执行:
21
+ 首次打开本地账本时,可直接填写随手记账号和密码并登录。单账本会自动同步最近两个月;多个账本可选择其中一个同步,更早的数据可在“数据与同步”选择全量同步。凭据保存在系统钥匙串。
22
+
23
+ 也可先停止使用同一数据目录的宿主,在终端执行:
22
24
 
23
25
  ```sh
24
26
  npx --yes --package=@goodpeanuts/dsh-sui feidee auth set '你的随手记账号'
@@ -27,7 +29,7 @@ npx --yes --package=@goodpeanuts/dsh-sui feidee books --pretty
27
29
  npx --yes --package=@goodpeanuts/dsh-sui feidee sync recent --book '上一步返回的账本ID'
28
30
  ```
29
31
 
30
- 按隐藏提示输入密码;凭据保存在系统钥匙串。同步完成后启动宿主。插件和命令默认共用 `$DSH_HOME/sui-ledger`(默认 `~/.dsh/sui-ledger`);若修改了插件数据目录,运行命令时请将环境变量 `SUI_LEDGER_DATA_DIR` 设为相同目录。空数据集的页面目前尚无首次登录向导。
32
+ 按隐藏提示输入密码;同步完成后启动宿主。插件和命令默认共用 `$DSH_HOME/sui-ledger`(默认 `~/.dsh/sui-ledger`);若修改了插件数据目录,运行命令时请将环境变量 `SUI_LEDGER_DATA_DIR` 设为相同目录。
31
33
 
32
34
  打开宿主后,从左侧 `sui-ledger` 进入账本。安装态默认禁止远端交易写入,本地草稿编辑和读取同步可用;实际策略通过 `/api/sui-ledger/finance/write-policy` 核对。模型服务在 DSH 设置中配置。
33
35
 
@@ -43,6 +45,8 @@ npx --yes --package=@goodpeanuts/dsh-sui feidee sync recent --book '上一步返
43
45
 
44
46
  ### 会话草稿与待入账
45
47
 
48
+ 会话输入框上方的“账本授权”用于选择当前会话可访问的账本,即使还没有草稿也会显示。点击后选择账本并“确认授权”;可勾选设为默认,供尚未授权的会话自动使用。再次打开可切换当前会话账本或清除默认账本;清除默认不影响已经授权的会话。切换前须先处理当前草稿,防止旧草稿失去授权。没有可选账本时,先打开账本页面登录并同步。
49
+
46
50
  模型通过受限 finance 工具读取账本、维护当前会话的一份流水草稿。用户和 Agent 共同编辑同一份字段;缺项由必填字段和校验结果派生,未知信息通过宿主提问,不写入草稿问题状态。
47
51
 
48
52
  非空草稿在输入框上方显示单个图标,点击打开工作台,关闭后保留编辑。完整条目可加入“待入账”,原批次冻结为只读存档;部分加入时剩余条目继续使用原入口,整批加入后入口收起,后续记账另开批次。其他会话的 open 草稿不共享,已加入同一账本的待入账记录可读。
@@ -61,7 +61,7 @@ var FinanceDatabase = class {
61
61
  assertTimestamp(input.now, "now");
62
62
  return this.db.transaction(() => {
63
63
  const current = this.getActiveGrant(input.subjectId);
64
- if (input.expectedRevision !== void 0 && current?.revision !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
64
+ if (input.expectedRevision !== void 0 && (current?.revision ?? 0) !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
65
65
  if (current?.bookId === input.bookId) return current;
66
66
  const revision = (current?.revision ?? 0) + 1;
67
67
  if (current) this.db.prepare("UPDATE book_read_grants SET replaced_at=? WHERE id=? AND replaced_at IS NULL").run(input.now, current.id);
@@ -1128,6 +1128,7 @@ window.__ModuleLoader__.load({
1128
1128
  section: "sync",
1129
1129
  query: { view: "backup" }
1130
1130
  };
1131
+ if (match.routeId === FinanceRouteIds.setup) return { section: "sync" };
1131
1132
  if (match.routeId === FinanceRouteIds.preferences) return { section: "preferences" };
1132
1133
  const bookId = match.params.bookId;
1133
1134
  if (!bookId || match.routeId === FinanceRouteIds.index) return {
@@ -1229,7 +1230,8 @@ window.__ModuleLoader__.load({
1229
1230
  };
1230
1231
  }
1231
1232
  function ledgerRouteTarget(route) {
1232
- if (route.section === "sync" && (route.query?.view === "backup" || !route.bookId)) return { routeId: FinanceRouteIds.maintenance };
1233
+ if (route.section === "sync" && route.query?.view === "backup") return { routeId: FinanceRouteIds.maintenance };
1234
+ if (route.section === "sync" && !route.bookId) return { routeId: FinanceRouteIds.setup };
1233
1235
  if (route.section === "preferences") return { routeId: FinanceRouteIds.preferences };
1234
1236
  if (!route.bookId) return { routeId: FinanceRouteIds.index };
1235
1237
  const params = { bookId: route.bookId };
@@ -1408,6 +1410,7 @@ window.__ModuleLoader__.load({
1408
1410
  index: "finance.ledger.index",
1409
1411
  preferences: "finance.ledger.preferences",
1410
1412
  maintenance: "finance.ledger.maintenance",
1413
+ setup: "finance.ledger.setup",
1411
1414
  overview: "finance.ledger.overview",
1412
1415
  transactions: "finance.ledger.transactions",
1413
1416
  transactionDetail: "finance.ledger.transaction-detail",
@@ -11181,6 +11184,243 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11181
11184
  };
11182
11185
  }));
11183
11186
  //#endregion
11187
+ //#region ../../packages/finance-ui/src/book-grant.css
11188
+ var init_book_grant$1 = __esmMin((() => {}));
11189
+ //#endregion
11190
+ //#region ../../packages/finance-ui/src/book-grant.tsx
11191
+ /** Available before the first draft exists: authorization must not depend on authorized work. */
11192
+ function BookGrantControl({ subjectId, client, onOpenLedger }) {
11193
+ const [opened, setOpened] = (0, react.useState)(false);
11194
+ const [bound, setBound] = (0, react.useState)(false);
11195
+ (0, react.useEffect)(() => {
11196
+ let active = true;
11197
+ const refresh = () => {
11198
+ client.getSubjectGrant(subjectId).then((grant) => {
11199
+ if (active) setBound(Boolean(grant));
11200
+ }).catch(() => {});
11201
+ };
11202
+ refresh();
11203
+ window.addEventListener("sui-ledger:finance-updated", refresh);
11204
+ return () => {
11205
+ active = false;
11206
+ window.removeEventListener("sui-ledger:finance-updated", refresh);
11207
+ };
11208
+ }, [client, subjectId]);
11209
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11210
+ className: "sui-ledger-draft-ui book-grant-control",
11211
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
11212
+ type: "button",
11213
+ className: "book-grant-trigger",
11214
+ "aria-haspopup": "dialog",
11215
+ "aria-expanded": opened,
11216
+ title: bound ? "查看或切换会话账本" : "选择当前会话可访问的账本",
11217
+ onClick: () => setOpened(true),
11218
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { name: "book" }), "账本授权"]
11219
+ }), opened && (0, react_dom.createPortal)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
11220
+ className: "sui-ledger-draft-ui",
11221
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BookGrantDialog, {
11222
+ subjectId,
11223
+ client,
11224
+ onClose: () => setOpened(false),
11225
+ onOpenLedger
11226
+ })
11227
+ }), document.body)]
11228
+ });
11229
+ }
11230
+ function BookGrantDialog({ subjectId, client, onClose, onOpenLedger }) {
11231
+ const dialog = (0, react.useRef)(null);
11232
+ const alive = (0, react.useRef)(true);
11233
+ const running = (0, react.useRef)(false);
11234
+ const [data, setData] = (0, react.useState)(null);
11235
+ const [selected, setSelected] = (0, react.useState)("");
11236
+ const [makeDefault, setMakeDefault] = (0, react.useState)(false);
11237
+ const [busy, setBusy] = (0, react.useState)(false);
11238
+ const [error, setError] = (0, react.useState)("");
11239
+ const load = (0, react.useCallback)(async () => {
11240
+ if (running.current) return;
11241
+ running.current = true;
11242
+ setBusy(true);
11243
+ setError("");
11244
+ setData(null);
11245
+ setMakeDefault(false);
11246
+ try {
11247
+ if (!client.requestBookGrantSelection) throw new Error("请更新插件后重试。");
11248
+ const next = await client.requestBookGrantSelection(subjectId);
11249
+ if (!alive.current) return;
11250
+ setData(next);
11251
+ const preferred = next.grant?.bookId ?? next.defaultBookId;
11252
+ setSelected(next.books.find((book) => book.id === preferred)?.id ?? next.books[0]?.id ?? "");
11253
+ } catch {
11254
+ if (alive.current) setError("无法读取账本授权,请重试。");
11255
+ } finally {
11256
+ running.current = false;
11257
+ if (alive.current) setBusy(false);
11258
+ }
11259
+ }, [client, subjectId]);
11260
+ (0, react.useEffect)(() => {
11261
+ alive.current = true;
11262
+ const element = dialog.current;
11263
+ element.showModal();
11264
+ load();
11265
+ return () => {
11266
+ alive.current = false;
11267
+ element.close();
11268
+ };
11269
+ }, [load]);
11270
+ const finish = async (decision) => {
11271
+ if (running.current) return;
11272
+ if (!data || !client.respondBookGrantSelection) {
11273
+ onClose();
11274
+ return;
11275
+ }
11276
+ running.current = true;
11277
+ setBusy(true);
11278
+ setError("");
11279
+ try {
11280
+ await client.respondBookGrantSelection(subjectId, data.request.id, {
11281
+ decision,
11282
+ ...decision === "confirm" ? {
11283
+ bookId: selected,
11284
+ makeDefault
11285
+ } : {}
11286
+ });
11287
+ window.dispatchEvent(new Event("sui-ledger:finance-updated"));
11288
+ if (alive.current) onClose();
11289
+ } catch (cause) {
11290
+ if (!alive.current) return;
11291
+ if (decision === "cancel") onClose();
11292
+ else if (cause instanceof Error && cause.message === "finance_draft_book_change_blocked") setError("当前会话仍有流水草稿,请先将其加入待入账或移除全部条目,再切换账本。");
11293
+ else setError("授权未完成,账本可能已在其他页面更改。请重新读取后确认。");
11294
+ } finally {
11295
+ running.current = false;
11296
+ if (alive.current) setBusy(false);
11297
+ }
11298
+ };
11299
+ const clearDefault = async () => {
11300
+ if (running.current || !client.setDefaultBook) return;
11301
+ running.current = true;
11302
+ setBusy(true);
11303
+ setError("");
11304
+ try {
11305
+ await client.setDefaultBook(null);
11306
+ if (alive.current) {
11307
+ setData((current) => current && {
11308
+ ...current,
11309
+ defaultBookId: null
11310
+ });
11311
+ setMakeDefault(false);
11312
+ }
11313
+ } catch {
11314
+ if (alive.current) setError("清除默认账本失败,请重试。");
11315
+ } finally {
11316
+ running.current = false;
11317
+ if (alive.current) setBusy(false);
11318
+ }
11319
+ };
11320
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("dialog", {
11321
+ ref: dialog,
11322
+ className: "book-grant-dialog",
11323
+ "aria-labelledby": "book-grant-title",
11324
+ onCancel: (event) => {
11325
+ event.preventDefault();
11326
+ finish("cancel");
11327
+ },
11328
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
11329
+ onSubmit: (event) => {
11330
+ event.preventDefault();
11331
+ if (selected && !busy) finish("confirm");
11332
+ },
11333
+ children: [
11334
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("header", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
11335
+ id: "book-grant-title",
11336
+ children: "选择会话账本"
11337
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11338
+ type: "button",
11339
+ tone: "ghost",
11340
+ disabled: busy,
11341
+ "aria-label": "关闭账本授权",
11342
+ onClick: () => void finish("cancel"),
11343
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { name: "close" })
11344
+ })] }),
11345
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "授权后,当前会话可读取所选账本并维护草稿;实际入账仍需单独人工确认。" }),
11346
+ data && data.books.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
11347
+ className: "workset-field",
11348
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "授权账本" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
11349
+ value: selected,
11350
+ disabled: busy,
11351
+ onChange: (event) => setSelected(event.currentTarget.value),
11352
+ children: data.books.map((book) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
11353
+ value: book.id,
11354
+ children: book.name || book.id
11355
+ }, book.id))
11356
+ })]
11357
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
11358
+ className: "book-grant-default",
11359
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
11360
+ type: "checkbox",
11361
+ checked: makeDefault,
11362
+ disabled: busy,
11363
+ onChange: (event) => setMakeDefault(event.currentTarget.checked)
11364
+ }), "设为默认账本,供尚未授权的会话自动使用"]
11365
+ })] }),
11366
+ data && data.books.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11367
+ role: "status",
11368
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "尚无可用账本,请先在账本页面登录并同步。" }), onOpenLedger && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11369
+ type: "button",
11370
+ disabled: busy,
11371
+ onClick: () => {
11372
+ finish("cancel").then(onOpenLedger);
11373
+ },
11374
+ children: "打开账本"
11375
+ })]
11376
+ }),
11377
+ data?.defaultBookId && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11378
+ className: "book-grant-current-default",
11379
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { children: ["默认账本:", data.books.find((book) => book.id === data.defaultBookId)?.name ?? data.defaultBookId] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11380
+ type: "button",
11381
+ tone: "ghost",
11382
+ disabled: busy,
11383
+ onClick: () => void clearDefault(),
11384
+ children: "清除默认账本"
11385
+ })]
11386
+ }),
11387
+ error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
11388
+ role: "alert",
11389
+ children: error
11390
+ }),
11391
+ busy && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
11392
+ role: "status",
11393
+ children: "正在处理…"
11394
+ }),
11395
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("footer", { children: [
11396
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11397
+ type: "button",
11398
+ disabled: busy,
11399
+ onClick: () => void finish("cancel"),
11400
+ children: "取消"
11401
+ }),
11402
+ error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11403
+ type: "button",
11404
+ disabled: busy,
11405
+ onClick: () => void load(),
11406
+ children: "重新读取"
11407
+ }),
11408
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
11409
+ type: "submit",
11410
+ tone: "primary",
11411
+ disabled: busy || !data?.books.length || !selected,
11412
+ children: "确认授权"
11413
+ })
11414
+ ] })
11415
+ ]
11416
+ })
11417
+ });
11418
+ }
11419
+ var init_book_grant = __esmMin((() => {
11420
+ init_src$2();
11421
+ init_book_grant$1();
11422
+ }));
11423
+ //#endregion
11184
11424
  //#region ../../packages/finance-ui/src/ledger-route-page.tsx
11185
11425
  var ledger_route_page_exports = /* @__PURE__ */ __exportAll({ createFinanceLedgerRoutePage: () => createFinanceLedgerRoutePage });
11186
11426
  function createFinanceLedgerRoutePage(financeClient, fetchImpl) {
@@ -11226,6 +11466,15 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11226
11466
  };
11227
11467
  const readStatus = (path) => request(path, { signal: AbortSignal.timeout(1e4) });
11228
11468
  return {
11469
+ async requestBookGrantSelection(subjectId) {
11470
+ return request(`/finance/subjects/${encodeURIComponent(subjectId)}/grant/selection`, jsonRequest("POST", {}));
11471
+ },
11472
+ async respondBookGrantSelection(subjectId, requestId, response) {
11473
+ return request(`/finance/subjects/${encodeURIComponent(subjectId)}/grant/selection/${encodeURIComponent(requestId)}`, jsonRequest("POST", response));
11474
+ },
11475
+ async setDefaultBook(bookId) {
11476
+ return (await request("/finance/default-book", jsonRequest("PUT", { bookId }))).bookId;
11477
+ },
11229
11478
  async getPreparation(worksetId) {
11230
11479
  return (await readStatus(`/finance/worksets/${encodeURIComponent(worksetId)}/preparation`)).operation;
11231
11480
  },
@@ -11238,6 +11487,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11238
11487
  async loginSession(credential) {
11239
11488
  return (await request("/finance/session/login", jsonRequest("POST", credential ?? {}))).session;
11240
11489
  },
11490
+ async listRemoteBooks() {
11491
+ return (await request("/finance/session/books", jsonRequest("POST", {}))).books;
11492
+ },
11241
11493
  async verifyCommit(commitId) {
11242
11494
  return (await request(`/finance/commits/${encodeURIComponent(commitId)}/verify`, jsonRequest("POST", {}))).commit;
11243
11495
  },
@@ -11348,6 +11600,12 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
11348
11600
  description: "备份与恢复。",
11349
11601
  loadPage: loadLedgerPage
11350
11602
  },
11603
+ {
11604
+ id: FinanceRouteIds.setup,
11605
+ path: "/ledger/setup",
11606
+ description: "首次登录与同步。",
11607
+ loadPage: loadLedgerPage
11608
+ },
11351
11609
  {
11352
11610
  id: FinanceRouteIds.index,
11353
11611
  path: "/ledger",
@@ -14385,6 +14643,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
14385
14643
  init_transaction_time();
14386
14644
  init_memo_policy();
14387
14645
  init_draft_card();
14646
+ init_book_grant();
14388
14647
  init_ledger_route();
14389
14648
  }));
14390
14649
  //#endregion
@@ -20080,7 +20339,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20080
20339
  ].map(([view, label]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
20081
20340
  type: "button",
20082
20341
  "aria-current": view === "backup" ? "page" : void 0,
20083
- disabled: view !== "backup" && !bookId || !!busy,
20342
+ disabled: view !== "backup" && view !== "status" && !bookId || !!busy,
20084
20343
  onClick: () => onNavigate({
20085
20344
  ...bookId ? { bookId } : {},
20086
20345
  section: "sync",
@@ -22093,6 +22352,218 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22093
22352
  };
22094
22353
  }));
22095
22354
  //#endregion
22355
+ //#region ../../packages/finance-ui/src/first-run-setup.css
22356
+ var init_first_run_setup$1 = __esmMin((() => {}));
22357
+ //#endregion
22358
+ //#region ../../packages/finance-ui/src/first-run-setup.tsx
22359
+ /** The local ledger does not exist yet, so login and sync must not require a book route. */
22360
+ function FirstRunSetup({ client, coordinator, onNavigate, showTabs }) {
22361
+ const session = useFinanceSession(client);
22362
+ const [username, setUsername] = (0, react.useState)("");
22363
+ const [password, setPassword] = (0, react.useState)("");
22364
+ const [books, setBooks] = (0, react.useState)();
22365
+ const [selected, setSelected] = (0, react.useState)("");
22366
+ const [working, setWorking] = (0, react.useState)(false);
22367
+ const [error, setError] = (0, react.useState)("");
22368
+ const alive = (0, react.useRef)(true);
22369
+ (0, react.useEffect)(() => {
22370
+ alive.current = true;
22371
+ return () => {
22372
+ alive.current = false;
22373
+ };
22374
+ }, []);
22375
+ const busy = working || session.sending || Boolean(coordinator.syncingMode);
22376
+ const discover = async () => {
22377
+ if (!client.listRemoteBooks) throw new Error("当前插件无法读取远端账本,请更新插件后重试。");
22378
+ const found = await client.listRemoteBooks();
22379
+ if (!alive.current) return;
22380
+ setBooks(found);
22381
+ setSelected(found[0]?.id ?? "");
22382
+ if (found.length === 1) await coordinator.startSync(found[0].id, "recent");
22383
+ };
22384
+ const login = async (credential) => {
22385
+ if (busy) return;
22386
+ setWorking(true);
22387
+ setError("");
22388
+ setBooks(void 0);
22389
+ try {
22390
+ const state = await session.login(credential);
22391
+ if (!alive.current) return;
22392
+ if (!state || state.status !== "authenticated" || state.loginFailure || state.saveFailed) {
22393
+ const failure = state?.loginFailure ?? state?.status;
22394
+ setError(state?.saveFailed ? "登录成功,但凭据未能保存到系统凭据库,请检查后重试。" : failure === "invalid_credentials" ? "随手记账号或密码不正确,请重试。" : failure === "missing_credentials" ? "尚未保存登录凭据,请填写账号和密码。" : failure === "credential_unavailable" ? "无法访问系统凭据库,请检查系统权限。" : failure === "network_unavailable" ? "无法连接随手记,请检查网络后重试。" : "登录未完成,请检查账号、密码和网络后重试。");
22395
+ return;
22396
+ }
22397
+ await discover();
22398
+ } catch {
22399
+ if (alive.current) setError("无法读取远端账本,请检查网络和登录状态后重试。");
22400
+ } finally {
22401
+ if (alive.current) setWorking(false);
22402
+ }
22403
+ };
22404
+ const submit = (event) => {
22405
+ event.preventDefault();
22406
+ if (!username.trim() || !password || busy) return;
22407
+ const credential = {
22408
+ username: username.trim(),
22409
+ password
22410
+ };
22411
+ setPassword("");
22412
+ login(credential);
22413
+ };
22414
+ const syncSelected = async () => {
22415
+ if (!selected || busy) return;
22416
+ setError("");
22417
+ await coordinator.startSync(selected, "recent");
22418
+ };
22419
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
22420
+ className: "ledger-page first-run-setup",
22421
+ children: [
22422
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("header", {
22423
+ className: "page-head",
22424
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h1", { children: showTabs ? "数据与同步" : "连接随手记账本" })
22425
+ }),
22426
+ showTabs && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("nav", {
22427
+ className: "ledger-sync-tabs",
22428
+ "aria-label": "数据与同步分区",
22429
+ children: [
22430
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
22431
+ type: "button",
22432
+ "aria-current": "page",
22433
+ children: "同步状态"
22434
+ }),
22435
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
22436
+ type: "button",
22437
+ disabled: true,
22438
+ children: "流水变更"
22439
+ }),
22440
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
22441
+ type: "button",
22442
+ disabled: true,
22443
+ children: "汇率与计算"
22444
+ }),
22445
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
22446
+ type: "button",
22447
+ onClick: () => onNavigate({
22448
+ section: "sync",
22449
+ query: { view: "backup" }
22450
+ }),
22451
+ children: "备份与恢复"
22452
+ })
22453
+ ]
22454
+ }),
22455
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
22456
+ className: "ledger-card first-run-card",
22457
+ "aria-label": "首次连接随手记",
22458
+ children: [
22459
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", { children: "登录随手记并同步账本" }),
22460
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "登录后将同步所选账本最近两个月的数据;如需更早的流水,可在同步页面选择全量同步。" }),
22461
+ session.state?.canSaveCredentials !== false && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
22462
+ onSubmit: submit,
22463
+ className: "first-run-form",
22464
+ children: [
22465
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
22466
+ className: "workset-field",
22467
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "随手记账号" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
22468
+ autoComplete: "username",
22469
+ value: username,
22470
+ disabled: busy,
22471
+ onChange: (event) => setUsername(event.currentTarget.value)
22472
+ })]
22473
+ }),
22474
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
22475
+ className: "workset-field",
22476
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "随手记密码" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
22477
+ type: "password",
22478
+ autoComplete: "current-password",
22479
+ value: password,
22480
+ disabled: busy,
22481
+ onChange: (event) => setPassword(event.currentTarget.value)
22482
+ })]
22483
+ }),
22484
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
22485
+ type: "submit",
22486
+ tone: "primary",
22487
+ disabled: busy || !username.trim() || !password || !session.canLogin,
22488
+ children: "登录并同步"
22489
+ })
22490
+ ]
22491
+ }),
22492
+ session.state?.canSaveCredentials === false && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "当前使用启动环境中的凭据,请使用已有凭据登录。" }),
22493
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
22494
+ className: "first-run-actions",
22495
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
22496
+ type: "button",
22497
+ disabled: busy || !session.canLogin,
22498
+ onClick: () => void login(),
22499
+ children: "使用已有凭据登录"
22500
+ }), !showTabs && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
22501
+ type: "button",
22502
+ tone: "ghost",
22503
+ disabled: busy,
22504
+ onClick: () => onNavigate({
22505
+ section: "sync",
22506
+ query: { view: "backup" }
22507
+ }),
22508
+ children: "从备份恢复"
22509
+ })]
22510
+ }),
22511
+ books && books.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
22512
+ role: "status",
22513
+ children: "该账号下没有可同步的账本。"
22514
+ }),
22515
+ books && books.length > 1 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
22516
+ className: "first-run-choice",
22517
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
22518
+ className: "workset-field",
22519
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "选择要同步的账本" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("select", {
22520
+ value: selected,
22521
+ disabled: busy,
22522
+ onChange: (event) => setSelected(event.currentTarget.value),
22523
+ children: books.map((book) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("option", {
22524
+ value: book.id,
22525
+ children: book.name
22526
+ }, book.id))
22527
+ })]
22528
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
22529
+ type: "button",
22530
+ tone: "primary",
22531
+ disabled: busy || !selected,
22532
+ onClick: () => void syncSelected(),
22533
+ children: "同步所选账本"
22534
+ })]
22535
+ }),
22536
+ books && books.length === 1 && coordinator.pendingSync?.phase === "terminal" && coordinator.pendingSync.terminal?.status === "failed" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Button, {
22537
+ type: "button",
22538
+ disabled: busy,
22539
+ onClick: () => void syncSelected(),
22540
+ children: "重新同步"
22541
+ }),
22542
+ (error || coordinator.syncError?.message || session.requestError) && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
22543
+ role: "alert",
22544
+ className: "first-run-error",
22545
+ children: error || coordinator.syncError?.message || session.requestError
22546
+ }),
22547
+ working && !coordinator.syncingMode && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
22548
+ role: "status",
22549
+ children: "正在登录并读取账本…"
22550
+ }),
22551
+ coordinator.pendingSync && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LedgerSyncProgress, {
22552
+ operation: coordinator.pendingSync,
22553
+ stale: coordinator.progressStale
22554
+ })
22555
+ ]
22556
+ })
22557
+ ]
22558
+ });
22559
+ }
22560
+ var init_first_run_setup = __esmMin((() => {
22561
+ init_src$2();
22562
+ init_ledger_sync_progress();
22563
+ init_session_recovery();
22564
+ init_first_run_setup$1();
22565
+ }));
22566
+ //#endregion
22096
22567
  //#region ../../packages/finance-ui/src/local-ledger.tsx
22097
22568
  function LocalLedger(props) {
22098
22569
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LedgerTransportProvider, {
@@ -22203,7 +22674,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22203
22674
  "aria-label": "本地账本页面",
22204
22675
  children: [sections.map((item) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
22205
22676
  type: "button",
22206
- disabled: preferencesSaving,
22677
+ disabled: preferencesSaving || !loading && !book && section !== "preferences" && ![
22678
+ "overview",
22679
+ "sync",
22680
+ "preferences"
22681
+ ].includes(item.id),
22207
22682
  className: section === item.id ? "active" : "",
22208
22683
  "aria-current": section === item.id ? "page" : void 0,
22209
22684
  onClick: () => selectSection(item.id),
@@ -22245,11 +22720,15 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22245
22720
  children: [pendingSection && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UnsavedPreferencesNotice, {
22246
22721
  onKeep: () => setPendingSection(void 0),
22247
22722
  onDiscard: () => selectSection(pendingSection, true)
22248
- }), section === "sync" && (props.route.query?.view === "backup" || !!error || !book) ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BackupRecoveryPage, {
22723
+ }), section === "sync" && (props.route.query?.view === "backup" || !!error) ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BackupRecoveryPage, {
22249
22724
  ...bookId || books[0]?.id ? { bookId: bookId || books[0]?.id } : {},
22250
22725
  onNavigate: props.onNavigate,
22251
22726
  onRestored: () => {
22252
22727
  discardPreferencesDraft(void 0, fetchImpl);
22728
+ if (props.route.query?.view !== "backup") props.onNavigate({
22729
+ section: "sync",
22730
+ query: { view: "backup" }
22731
+ });
22253
22732
  reconcileLedgerIndex();
22254
22733
  }
22255
22734
  }) : section === "preferences" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PersonalPreferencesPage, {
@@ -22267,10 +22746,15 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22267
22746
  icon: "warning",
22268
22747
  title: "账本页面不存在",
22269
22748
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "当前地址中的报表或资料类型无效。地址已保留,你可以从上方导航选择其他分区。" })
22270
- }) : !book ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LedgerState, {
22749
+ }) : !book && (bookId || books.length) ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(LedgerState, {
22271
22750
  icon: "receipt",
22272
- title: props.route.bookId || books.length ? "找不到这个账本" : "暂无账本",
22273
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: props.route.bookId || books.length ? "当前地址指定的账本不存在或不可访问。" : "完成首次同步后,账本会显示在这里。" })
22751
+ title: "找不到这个账本",
22752
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "当前地址指定的账本不存在或不可访问。" })
22753
+ }) : !book ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FirstRunSetup, {
22754
+ client: props.financeClient,
22755
+ coordinator: syncCoordinator,
22756
+ onNavigate: props.onNavigate,
22757
+ showTabs: section === "sync"
22274
22758
  }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(AutomaticValuationRefresh, {
22275
22759
  bookId: book.id,
22276
22760
  refreshKey: latestSync?.completedAt
@@ -22374,6 +22858,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22374
22858
  init_local_ledger_visuals();
22375
22859
  init_backup_recovery();
22376
22860
  init_service_records_page();
22861
+ init_first_run_setup();
22377
22862
  LEDGER_BOOK_KEY = "sui-ledger.local-ledger.book";
22378
22863
  LEDGER_SECTION_KEY = "sui-ledger.local-ledger.section";
22379
22864
  sections = [
@@ -22460,6 +22945,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22460
22945
  description: "备份与恢复。",
22461
22946
  loadPage: stubLoadPage
22462
22947
  },
22948
+ {
22949
+ id: FinanceRouteIds.setup,
22950
+ path: "/ledger/setup",
22951
+ ownerModuleId: OWNER_MODULE_ID,
22952
+ description: "首次登录与同步。",
22953
+ loadPage: stubLoadPage
22954
+ },
22463
22955
  {
22464
22956
  id: FinanceRouteIds.preferences,
22465
22957
  path: "/ledger/preferences",
@@ -22959,7 +23451,11 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
22959
23451
  init_src$2();
22960
23452
  /** DSH's session-scoped input dock stays mounted even while the icon is absent. */
22961
23453
  function DraftComposerDock(props) {
22962
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionDraftDock, { ...props }, props.sessionId);
23454
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(BookGrantControl, {
23455
+ subjectId: `dsh-session-${props.sessionId}`,
23456
+ client: props.financeClient,
23457
+ onOpenLedger: props.onOpenLedger
23458
+ }, `grant-${props.sessionId}`), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionDraftDock, { ...props }, props.sessionId)] });
22963
23459
  }
22964
23460
  function SessionDraftDock(props) {
22965
23461
  const timeline = props.useChat((snapshot) => snapshot.timeline);
@@ -23476,7 +23972,10 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
23476
23972
  id: "sui-ledger-draft",
23477
23973
  order: 15,
23478
23974
  locale: NS,
23479
- inject: () => ({ financeClient })
23975
+ inject: () => ({
23976
+ financeClient,
23977
+ onOpenLedger: () => ctx.layout.selectPanel(PANEL_ID)
23978
+ })
23480
23979
  }, DraftComposerDock));
23481
23980
  for (const { key, component } of TOOLVIEWS) ctx.slots.inject("tool.call.toolview", () => ctx.slots.register({
23482
23981
  name: "tool.call.toolview",
@@ -25,7 +25,7 @@ function registerFinanceStateContext(prompt, read) {
25
25
  }
26
26
  }
27
27
  function buildFinanceStateContext(snapshot) {
28
- if (snapshot.status === "unbound") return "【当前账务状态】\n当前会话尚无账本授权;未读取任何默认账本统计。用 finance_books_list 查看默认账本和授权,沿用现有账本授权流程。";
28
+ if (snapshot.status === "unbound") return "【当前账务状态】\n当前会话尚无账本授权;未读取任何默认账本统计。用 finance_books_list 查看默认账本和授权;没有默认账本时,请用户点击会话输入框上方的“账本授权”选择并确认。若没有可选账本,先打开账本页面登录并同步。";
29
29
  return [
30
30
  "【当前账务状态】",
31
31
  "以下是本次模型上下文组装时的轻量状态,覆盖之前的状态快照,不是已读取或已核对的凭据。fingerprint 仅为状态指纹,不能作为读取工具的分页版本;续读须使用各工具实际返回的 dataVersion。",
@@ -135,7 +135,7 @@ async function apply(ctx, config) {
135
135
  path: "/api/sui-ledger",
136
136
  handler: async (req, res) => {
137
137
  const url = new URL(req.url ?? "/", "http://localhost"), path = url.pathname.slice(15);
138
- if (path === "/maintenance" || path.startsWith("/maintenance/") || path === "/finance/services" || path.startsWith("/finance/services/")) {
138
+ if (path === "/maintenance" || path.startsWith("/maintenance/") || path === "/finance/services" || path.startsWith("/finance/services/") || path === "/finance/session" || path.startsWith("/finance/session/") || path === "/finance/default-book" || /^\/finance\/subjects\/[^/]+\/grant(?:\/|$)/.test(path)) {
139
139
  const rejection = web.connection.requestRejection(req);
140
140
  if (rejection !== void 0) {
141
141
  res.statusCode = rejection;
@@ -90,7 +90,7 @@ function createFinanceTools(service, ledger, options = {}) {
90
90
  throw new FinancePublicError(JSON.stringify({
91
91
  code,
92
92
  activeGrant: books.activeGrant,
93
- message: code === "finance_grant_book_mismatch" ? "Use the active grant's bookId if the requested ID was mistyped. Selecting another book requires trusted user action." : "No active book grant. Request finance.book_grant.selection and wait for the trusted response."
93
+ message: code === "finance_grant_book_mismatch" ? "Use the active grant's bookId if the requested ID was mistyped. Selecting another book requires trusted user action." : "No active book grant. Ask the user to click 账本授权 (Book access) above the conversation input and confirm a book; if the list is empty, open the Ledger panel to log in and sync first."
94
94
  }));
95
95
  }
96
96
  if (code) throw new FinancePublicError(JSON.stringify({
@@ -61,7 +61,7 @@ var FinanceDatabase = class {
61
61
  assertTimestamp(input.now, "now");
62
62
  return this.db.transaction(() => {
63
63
  const current = this.getActiveGrant(input.subjectId);
64
- if (input.expectedRevision !== void 0 && current?.revision !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
64
+ if (input.expectedRevision !== void 0 && (current?.revision ?? 0) !== input.expectedRevision) throw new Error("finance_grant_revision_conflict");
65
65
  if (current?.bookId === input.bookId) return current;
66
66
  const revision = (current?.revision ?? 0) + 1;
67
67
  if (current) this.db.prepare("UPDATE book_read_grants SET replaced_at=? WHERE id=? AND replaced_at IS NULL").run(input.now, current.id);
@@ -18,6 +18,10 @@ function createFinanceInteractionTypes(service) {
18
18
  suggestedBookId: {
19
19
  type: "string",
20
20
  minLength: 1
21
+ },
22
+ expectedRevision: {
23
+ type: "integer",
24
+ minimum: 0
21
25
  }
22
26
  },
23
27
  additionalProperties: false
@@ -39,7 +43,7 @@ function createFinanceInteractionTypes(service) {
39
43
  },
40
44
  additionalProperties: false
41
45
  },
42
- handleResponse(ctx, _payload, response) {
46
+ handleResponse(ctx, payload, response) {
43
47
  if (ctx.request.context.scope.type !== "subject") return {
44
48
  ok: false,
45
49
  error: "Book selection requires a Conversation"
@@ -53,10 +57,11 @@ function createFinanceInteractionTypes(service) {
53
57
  ok: false,
54
58
  error: "A book must be selected"
55
59
  };
56
- const grant = service.bindSubjectGrant({
57
- subjectId: ctx.request.context.scope.subjectId,
60
+ const subjectId = ctx.request.context.scope.subjectId;
61
+ const grant = service.selectSubjectBook({
62
+ subjectId,
58
63
  bookId: response.bookId,
59
- ...response.expectedRevision !== void 0 ? { expectedRevision: response.expectedRevision } : {}
64
+ ...(payload.expectedRevision ?? response.expectedRevision) !== void 0 ? { expectedRevision: payload.expectedRevision ?? response.expectedRevision } : {}
60
65
  });
61
66
  if (response.makeDefault) service.setDefaultBook(grant.bookId);
62
67
  return {
@@ -147,6 +147,10 @@ function createFinanceTrustedControlRoute(finance, interaction, preferences) {
147
147
  if (Object.keys(body).length) badRequest("Session check accepts an empty object");
148
148
  return json(200, { session: await finance.checkSession() });
149
149
  }
150
+ if (request.method === "POST" && request.pathname === "/v1/finance/session/books" && finance.listRemoteBooks) {
151
+ if (Object.keys(await request.body()).length) badRequest("Book discovery accepts an empty object");
152
+ return json(200, { books: await financeCall(() => finance.listRemoteBooks()) });
153
+ }
150
154
  if (request.method === "POST" && request.pathname === "/v1/finance/session/login") {
151
155
  const body = await request.body();
152
156
  if (Object.keys(body).some((key) => key !== "username" && key !== "password")) badRequest("Invalid login request");
@@ -171,15 +175,67 @@ function createFinanceTrustedControlRoute(finance, interaction, preferences) {
171
175
  return recoveryResponse(() => recovery[2] === "resume" ? finance.resumeCommit(recovery[1], hash, recoveryHash) : finance.endCommit(recovery[1], hash), "checking", recovery[2] === "resume" ? 202 : 200);
172
176
  }
173
177
  if (request.pathname === "/v1/finance/default-book" && request.method === "PUT") {
174
- const bookId = requiredIdentifier((await request.body()).bookId, "bookId");
178
+ const body = await request.body();
179
+ if (Object.keys(body).some((key) => key !== "bookId")) badRequest("Invalid default book request");
180
+ const bookId = body.bookId === null ? null : requiredIdentifier(body.bookId, "bookId");
175
181
  return json(200, { bookId: (await financeCall(() => finance.setDefaultBook(bookId))).bookId });
176
182
  }
183
+ const selection = request.pathname.match(/^\/v1\/finance\/subjects\/([A-Za-z0-9._-]+)\/grant\/selection(?:\/([A-Za-z0-9._-]+))?$/);
184
+ if (request.method === "POST" && selection) {
185
+ const subjectId = selection[1], requestId = selection[2];
186
+ const body = await request.body();
187
+ if (!requestId) {
188
+ if (Object.keys(body).length) badRequest("Book selection accepts an empty object");
189
+ const { books, defaultBookId } = finance.describeBooks({ subjectId });
190
+ const grant = finance.getGrant(subjectId) ?? null;
191
+ const revision = grant?.revision ?? 0;
192
+ const suggestedBookId = grant?.bookId ?? defaultBookId;
193
+ return json(200, {
194
+ request: publicInteraction(interaction.attention().flatMap((item) => item.kind === "interaction" ? [item.value] : []).find((item) => item.type === FinanceInteractionTypes.bookGrantSelection && item.context.scope.type === "subject" && item.context.scope.subjectId === subjectId && record(item.payload)?.expectedRevision === revision) ?? interaction.request({
195
+ type: FinanceInteractionTypes.bookGrantSelection,
196
+ context: {
197
+ scope: {
198
+ type: "subject",
199
+ subjectId
200
+ },
201
+ origin: { module: "finance" }
202
+ },
203
+ title: "选择会话账本",
204
+ summary: "确认当前会话可读取和编辑草稿的账本。",
205
+ payload: {
206
+ reason: "用户选择会话账本",
207
+ expectedRevision: revision,
208
+ ...suggestedBookId ? { suggestedBookId } : {}
209
+ }
210
+ })),
211
+ books,
212
+ grant,
213
+ defaultBookId
214
+ });
215
+ }
216
+ if (Object.keys(body).some((key) => ![
217
+ "decision",
218
+ "bookId",
219
+ "makeDefault"
220
+ ].includes(key))) badRequest("Invalid book selection response");
221
+ if (body.decision !== "confirm" && body.decision !== "cancel") badRequest("decision must be confirm or cancel");
222
+ if (body.decision === "confirm") requiredIdentifier(body.bookId, "bookId");
223
+ if (body.makeDefault !== void 0 && typeof body.makeDefault !== "boolean") badRequest("makeDefault must be a boolean");
224
+ if (!interaction.attention().flatMap((item) => item.kind === "interaction" ? [item.value] : []).find((item) => item.id === requestId && item.type === FinanceInteractionTypes.bookGrantSelection && item.context.scope.type === "subject" && item.context.scope.subjectId === subjectId)) throw new FinanceRouteError(409, "Book selection is no longer current; reopen Book access");
225
+ const result = await financeCall(() => interaction.respond(requestId, body));
226
+ return json(result.accepted ? 200 : 409, {
227
+ accepted: result.accepted,
228
+ ...result.error ? { error: result.error } : {},
229
+ grant: finance.getGrant(subjectId) ?? null,
230
+ defaultBookId: finance.getDefaultBook()
231
+ });
232
+ }
177
233
  const grant = request.pathname.match(/^\/v1\/finance\/subjects\/([A-Za-z0-9._-]+)\/grant$/);
178
234
  if (request.method === "PUT" && grant) {
179
235
  const body = await request.body();
180
236
  const bookId = requiredIdentifier(body.bookId, "bookId");
181
237
  const expectedRevision = body.expectedRevision === void 0 ? void 0 : requiredInteger(body.expectedRevision, "expectedRevision");
182
- return json(200, { grant: await financeCall(() => finance.bindSubjectGrant({
238
+ return json(200, { grant: await financeCall(() => finance.selectSubjectBook({
183
239
  subjectId: grant[1],
184
240
  bookId,
185
241
  ...expectedRevision !== void 0 ? { expectedRevision } : {}
@@ -382,6 +438,8 @@ async function financeCall(operation) {
382
438
  if (message === "checkpoint_not_found") throw new FinanceRouteError(404, "finance_checkpoint_not_found");
383
439
  if (message.includes("finance_workset_version_conflict") || message.includes("finance_workset_review_version_conflict") || message.includes("finance_entry_version_conflict") || message.includes("finance_draft_open_row_exists") || message.includes("finance_draft_book_mismatch") || message.includes("finance_draft_row_frozen") || message.includes("finance_grant_revision_conflict") || message.includes("finance_ledger_revision_conflict")) throw new FinanceRouteError(409, "Finance resource version changed; reload before continuing");
384
440
  if (message.includes("finance_workset_confirmation_pending")) throw new FinanceRouteError(409, "finance_workset_confirmation_pending");
441
+ if (message === "finance_draft_book_change_blocked") throw new FinanceRouteError(409, message);
442
+ if (message === "finance_book_not_found") throw new FinanceRouteError(404, message);
385
443
  if ([
386
444
  "finance_commit_operations_changed",
387
445
  "finance_commit_not_resumable",
@@ -16,6 +16,7 @@ function createFinanceLedgerPort(finance) {
16
16
  sessionStatus: () => finance.sessionStatus(),
17
17
  checkSession: () => finance.checkSession(),
18
18
  loginSession: (credential) => finance.loginSession(credential),
19
+ liveBooks: () => finance.liveBooks(),
19
20
  verifyTransaction: (bookId, input, attempt) => finance.verifyTransaction(bookId, input, attempt),
20
21
  hasMutationReceipt: (bookId, input) => finance.hasMutationReceipt(bookId, input),
21
22
  assertDeletedCreationReplaceable: (bookId, input, remoteId, replacementId) => finance.assertDeletedCreationReplaceable(bookId, input, remoteId, replacementId),
@@ -20,7 +20,7 @@ import { createHash, randomUUID } from "node:crypto";
20
20
  //#region ../../packages/finance-module/src/service.ts
21
21
  const DEFAULT_BOOK_SETTING_KEY = "default_book_id";
22
22
  const FINANCE_REMOTE_WRITES_DISABLED_ERROR = "finance_remote_writes_disabled";
23
- const FINANCE_GRANT_MISSING_HINT = "finance_grant_missing: no active BookReadGrant for this subject. Call finance_books_list to inspect the books and the active grant, then create the finance.book_grant.selection interaction so the user can bind a book; do not retry other book tools.";
23
+ const FINANCE_GRANT_MISSING_HINT = "finance_grant_missing: no active BookReadGrant for this subject. Ask the user to click 账本授权 (Book access) above the conversation input and confirm a book. If no books are listed, open the Ledger panel to log in and sync first. Do not retry other book tools before authorization.";
24
24
  function knownBook(ledger, bookId) {
25
25
  const books = ledger.cachedBooks();
26
26
  return Array.isArray(books) && books.some((book) => book?.id === bookId);
@@ -89,6 +89,18 @@ var FinanceApplicationService = class {
89
89
  getGrant(subjectId) {
90
90
  return this.options.store.getActiveGrant(subjectId);
91
91
  }
92
+ /** User selection must not strand a note bound to the previous grant. */
93
+ selectSubjectBook(input) {
94
+ if (!knownBook(this.options.ledger, input.bookId)) throw new Error("finance_book_not_found");
95
+ return this.options.store.transaction(() => {
96
+ const current = this.getGrant(input.subjectId);
97
+ const draft = this.options.store.getOpenDraftRow(input.subjectId);
98
+ if (draft?.entries.length && (current?.bookId !== input.bookId || draft.grantId !== current.id)) throw new Error("finance_draft_book_change_blocked");
99
+ const grant = this.bindSubjectGrant(input);
100
+ if (draft && !draft.entries.length && draft.grantId !== grant.id) this.options.store.deleteDraftRow(draft.id);
101
+ return grant;
102
+ });
103
+ }
92
104
  /** Prompt assembly is a pure read: it must not auto-bind the default book. */
93
105
  getModelFinanceContext(subjectId) {
94
106
  const grant = this.options.store.getActiveGrant(subjectId);
@@ -130,7 +142,7 @@ var FinanceApplicationService = class {
130
142
  return typeof value === "string" && value.trim() ? value : null;
131
143
  }
132
144
  setDefaultBook(bookId) {
133
- if (!knownBook(this.options.ledger, bookId)) throw new Error("finance_book_not_found");
145
+ if (bookId !== null && !knownBook(this.options.ledger, bookId)) throw new Error("finance_book_not_found");
134
146
  this.options.store.setSetting(DEFAULT_BOOK_SETTING_KEY, bookId, this.now());
135
147
  return { bookId };
136
148
  }
@@ -914,6 +926,10 @@ var FinanceApplicationService = class {
914
926
  if (!this.options.ledger.loginSession) throw new Error("finance_session_unavailable");
915
927
  return this.options.ledger.loginSession(credential);
916
928
  }
929
+ listRemoteBooks() {
930
+ if (!this.options.ledger.liveBooks) throw new Error("finance_session_unavailable");
931
+ return this.options.ledger.liveBooks();
932
+ }
917
933
  async respondCommit(commitId, decision, overrideCheckpointIds = [], background = false) {
918
934
  const commit = this.getCommit(commitId);
919
935
  if (commit.status !== "awaiting_confirmation") return commit;
@@ -1812,7 +1828,7 @@ var FinanceApplicationService = class {
1812
1828
  requireGrant(subjectId, bookId, grantId) {
1813
1829
  const grant = this.ensureDefaultBookGrant(subjectId);
1814
1830
  if (!grant) throw new Error(FINANCE_GRANT_MISSING_HINT);
1815
- if (grant.bookId !== bookId || grantId && grant.id !== grantId) throw new Error(`finance_grant_book_mismatch: the active BookReadGrant covers book ${grant.bookId}, not ${bookId}. Rebind the book via the finance.book_grant.selection interaction instead of retrying other book tools.`);
1831
+ if (grant.bookId !== bookId || grantId && grant.id !== grantId) throw new Error(`finance_grant_book_mismatch: the active BookReadGrant covers book ${grant.bookId}, not ${bookId}. Ask the user to click 账本授权 (Book access) above the conversation input to select another book instead of retrying other book tools.`);
1816
1832
  return grant;
1817
1833
  }
1818
1834
  draftMutationOnce(context, operation, input, mutate) {
@@ -1,3 +1,116 @@
1
+ .book-grant-control {
2
+ box-sizing: border-box;
3
+ width: calc(100% - 2 * var(--finance-composer-side-clearance, 16px));
4
+ max-width: var(--finance-composer-card-max-width, 712px);
5
+ margin-inline: auto;
6
+ padding: 0 0 6px;
7
+ }
8
+
9
+ .book-grant-trigger {
10
+ border: 1px solid var(--line);
11
+ background: var(--surface);
12
+ color: var(--ink);
13
+ cursor: pointer;
14
+ font: inherit;
15
+ border-radius: 8px;
16
+ align-items: center;
17
+ gap: 6px;
18
+ padding: 5px 10px;
19
+ font-size: 12px;
20
+ display: inline-flex;
21
+ }
22
+
23
+ .book-grant-trigger svg {
24
+ width: 16px;
25
+ height: 16px;
26
+ }
27
+
28
+ .book-grant-trigger:hover {
29
+ background: var(--surface-soft);
30
+ }
31
+
32
+ .book-grant-trigger:focus-visible {
33
+ outline: 2px solid var(--blue);
34
+ outline-offset: 2px;
35
+ }
36
+
37
+ .book-grant-dialog {
38
+ box-sizing: border-box;
39
+ border: 1px solid var(--line);
40
+ width: min(480px, 100vw - 32px);
41
+ max-height: calc(100dvh - 32px);
42
+ color: var(--ink);
43
+ background: var(--surface);
44
+ border-radius: 14px;
45
+ padding: 24px;
46
+ overflow: auto;
47
+ }
48
+
49
+ .book-grant-dialog::backdrop {
50
+ background: #00000059;
51
+ }
52
+
53
+ .book-grant-dialog form {
54
+ gap: 16px;
55
+ display: grid;
56
+ }
57
+
58
+ .book-grant-dialog header, .book-grant-dialog footer, .book-grant-current-default {
59
+ justify-content: space-between;
60
+ align-items: center;
61
+ gap: 12px;
62
+ display: flex;
63
+ }
64
+
65
+ .book-grant-dialog h2 {
66
+ margin: 0;
67
+ font-size: 18px;
68
+ }
69
+
70
+ .book-grant-dialog p {
71
+ margin: 0;
72
+ font-size: 13px;
73
+ line-height: 1.6;
74
+ }
75
+
76
+ .book-grant-dialog select {
77
+ box-sizing: border-box;
78
+ border: 1px solid var(--line);
79
+ background: var(--surface);
80
+ width: 100%;
81
+ min-width: 0;
82
+ min-height: 36px;
83
+ color: var(--ink);
84
+ font: inherit;
85
+ border-radius: 8px;
86
+ padding: 6px 10px;
87
+ }
88
+
89
+ .book-grant-default {
90
+ align-items: flex-start;
91
+ gap: 8px;
92
+ font-size: 13px;
93
+ line-height: 1.5;
94
+ display: flex;
95
+ }
96
+
97
+ .book-grant-default input {
98
+ flex: none;
99
+ }
100
+
101
+ .book-grant-current-default {
102
+ flex-wrap: wrap;
103
+ font-size: 13px;
104
+ }
105
+
106
+ .book-grant-dialog [role="alert"] {
107
+ color: var(--danger);
108
+ }
109
+
110
+ .book-grant-dialog footer {
111
+ flex-wrap: wrap;
112
+ justify-content: flex-end;
113
+ }
1
114
  .backup-recovery-page .page-head h1 {
2
115
  margin: 0 0 26px;
3
116
  font-size: 24px;
@@ -147,6 +260,38 @@
147
260
  padding: 22px;
148
261
  }
149
262
  }
263
+ .first-run-card {
264
+ max-width: 640px;
265
+ padding: 24px;
266
+ }
267
+
268
+ .first-run-card h2 {
269
+ margin: 0 0 8px;
270
+ }
271
+
272
+ .first-run-card > p {
273
+ line-height: 1.6;
274
+ }
275
+
276
+ .first-run-form, .first-run-choice {
277
+ gap: 12px;
278
+ margin: 20px 0 12px;
279
+ display: grid;
280
+ }
281
+
282
+ .first-run-form .button, .first-run-choice .button {
283
+ justify-self: start;
284
+ }
285
+
286
+ .first-run-actions {
287
+ flex-wrap: wrap;
288
+ gap: 8px;
289
+ display: flex;
290
+ }
291
+
292
+ .first-run-error {
293
+ color: var(--danger, #b42318);
294
+ }
150
295
  :root {
151
296
  color-scheme: light;
152
297
  color: #252823;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodpeanuts/dsh-sui",
3
- "version": "0.1.0",
3
+ "version": "0.1.2-fix.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Ledger (随手记/feidee) plugin for DeepSeek Harness — finance tools and ledger UI",