dsh-plugin-core-demo 0.36.2 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/client.js +636 -15
  2. package/package.json +1 -1
package/dist/client.js CHANGED
@@ -70015,6 +70015,70 @@ h(SideSheet, {
70015
70015
  }
70016
70016
  ]
70017
70017
  },
70018
+ "bt-authoritative": {
70019
+ "id": "bt-authoritative",
70020
+ "heading": {
70021
+ "zh": "\u670D\u52A1\u7AEF\u6743\u5A01\u4EFB\u52A1\uFF1A\u6062\u590D\u3001\u5224\u6B7B\u4E0E\u547D\u4EE4",
70022
+ "en": "Authoritative server tasks: recovery, watchdog and commands"
70023
+ },
70024
+ "prose": [
70025
+ {
70026
+ "zh": "\u65E7\u7684\u72B6\u6001\u6E90\u6A21\u5F0F\u53EA\u662F\u300C\u6309\u5DF2\u77E5 key \u95EE\u670D\u52A1\u7AEF\u300D\uFF1A\u9875\u9762\u5168\u5173\u540E\u62FF\u4E0D\u5230 key\uFF0C\u5237\u65B0\u4F1A\u628A\u65F6\u949F\u4ECE\u96F6\u7B97\u8D77\uFF0C\u6309\u94AE handler \u4E5F\u968F\u9875\u9762\u9500\u6BC1\u3002\u8981\u5B8C\u6574\u6062\u590D\uFF0C\u6539\u7528 `taskNotifications.setTaskBackend(project, backend)` + `notifyTask.server(title, options)`\u3002\u540E\u7AEF\u5FC5\u987B\u63D0\u4F9B `list / follow / listNotices / ackNotices / invoke / ack` \u516D\u4E2A\u80FD\u529B\uFF0C\u7F3A\u4E00\u5373\u6CE8\u518C\u5931\u8D25\u2014\u2014\u4E0D\u505A\u9759\u9ED8\u964D\u7EA7\u3002",
70027
+ "en": "The status-source mode only asks the server about keys it already knows: after every page closes there are no keys, a reload restarts the clock, and action handlers die with the page. For full recovery use `taskNotifications.setTaskBackend(project, backend)` plus `notifyTask.server(title, options)`. A backend must provide `list / follow / listNotices / ackNotices / invoke / ack`; registering otherwise throws \u2014 there is no silent fallback."
70028
+ },
70029
+ {
70030
+ "zh": "\u4E24\u6761\u901A\u9053\u5404\u53F8\u5176\u804C\uFF1A\u901A\u9053 A\uFF08`list / follow`\uFF09\u53EA\u6C34\u5408\u5728\u8DD1\u4EFB\u52A1\uFF0C\u7EC8\u6001\u5893\u7891\u53EA\u66F4\u65B0\u672C\u5730\u7EC8\u6001\u95E8\uFF0C\u7EDD\u4E0D\u53D1 `settled`\u3001\u7EDD\u4E0D ack\uFF1B\u901A\u9053 B\uFF08`listNotices / ackNotices`\uFF09\u4E13\u95E8\u6295\u9012\u672A\u786E\u8BA4\u7684\u7EC8\u6001\u901A\u77E5\uFF0C\u4E8B\u4EF6\u53D1\u51FA\u540E\u624D\u6309\u8FDE\u7EED\u6210\u529F\u524D\u7F00 ack\u3002\u56E0\u6B64\u9875\u9762\u91CD\u5F00\u540E\u57FA\u7EBF\u56DE\u653E\u4E0D\u4F1A\u9020\u6210\u91CD\u590D\u901A\u77E5\uFF0C\u672A\u786E\u8BA4\u7684\u901A\u77E5\u4ECD\u4F1A\u901A\u8FC7\u901A\u9053 B \u9001\u8FBE\u3002",
70031
+ "en": "Two channels with separate jobs: channel A (`list / follow`) only hydrates running tasks; a terminal tombstone only updates the local terminal gate and never emits `settled` nor acks. Channel B (`listNotices / ackNotices`) delivers unacknowledged terminal notices; the cursor advances only after the event is emitted. A page reopen therefore never duplicates a notice from baseline replay, and unacknowledged notices still arrive through channel B."
70032
+ },
70033
+ {
70034
+ "zh": "\u771F\u6E90\u5728\u670D\u52A1\u7AEF\uFF1A\u539F\u5B50 `create` \u51B3\u5B9A `created`\uFF0C`startedAt / deadlineAt / version` \u7531\u670D\u52A1\u7AEF\u751F\u6210\uFF0C\u8D85\u65F6\u4E0E\u79DF\u7EA6\u7531\u670D\u52A1\u7AEF watchdog \u5224\u5B9A\uFF0C\u7EC8\u6001\u6309 TTL \u6E05\u7406\u3002\u6838\u5FC3\u53EA\u6309\u5355\u8C03 version \u5408\u5E76\u57FA\u7EBF\u3001\u5206\u9875\u4E0E\u589E\u91CF\uFF1B\u6309\u94AE\u662F `{id, token, expiresAt}` \u63CF\u8FF0\uFF0C`runAction` \u6309 actionId \u8D70\u670D\u52A1\u7AEF\u547D\u4EE4\uFF0C\u4E0D\u4F9D\u8D56\u9875\u9762\u95ED\u5305\u3002\u70B9\u51FB\u6309\u94AE\u4F1A\u5411 `taskNotificationEvents` \u53D1 `action` \u4E8B\u4EF6\uFF08\u542B\u4EFB\u52A1\u5FEB\u7167\u3001actionId\u3001ok\u3001reason\u3001result\uFF09\uFF0C\u6D88\u8D39\u65B9\u636E\u6B64\u628A\u754C\u9762\u5E26\u56DE\u6765\u3002\u6743\u5A01\u53E5\u67C4\u53EA\u6709 `id / isSettled / settled`\uFF0C\u6CA1\u6709 update/touch/background/done/fail/track\u2014\u2014\u7EC8\u6001\u7531\u670D\u52A1\u7AEF\u5224\u5B9A\uFF0C\u7F16\u8BD1\u671F\u5373\u963B\u6B62\u8BEF\u7528\u3002",
70035
+ "en": "The server owns the truth: atomic `create` decides `created`; `startedAt / deadlineAt / version` come from the server; a server watchdog decides timeouts and lease expiry; terminal records are cleared by TTL. Actions are `{id, token, expiresAt}` descriptors and `runAction` dispatches by actionId to the server, never through page closures. Every click emits an `action` event to `taskNotificationEvents` (with task snapshot, actionId, ok, reason, result) so consumers can restore their UI. An authoritative handle exposes only `id / isSettled / settled`; update/touch/background/done/fail/track do not exist \u2014 the server decides terminal state, and the type system prevents misuse."
70036
+ }
70037
+ ],
70038
+ "api": [
70039
+ {
70040
+ "id": "bt-authoritative-api",
70041
+ "rows": [
70042
+ {
70043
+ "name": "taskNotifications.setTaskBackend(project, backend)",
70044
+ "type": "(project: string, backend: TaskBackend) => void",
70045
+ "def": "\u2014",
70046
+ "desc": {
70047
+ "zh": "\u5207\u6362\u5230\u670D\u52A1\u7AEF\u6743\u5A01\u6A21\u5F0F\uFF1B\u5FC5\u987B\u63D0\u4F9B list/follow/listNotices/ackNotices/invoke/ack\uFF0C\u5426\u5219\u629B\u9519",
70048
+ "en": "Switches to authoritative mode; list/follow/listNotices/ackNotices/invoke/ack are mandatory or registration throws"
70049
+ }
70050
+ },
70051
+ {
70052
+ "name": "notifyTask.server(title, options?)",
70053
+ "type": "(title: string, options?: NotifyTaskOptions) => Promise<AuthoritativeClaim>",
70054
+ "def": "\u2014",
70055
+ "desc": {
70056
+ "zh": "\u670D\u52A1\u7AEF\u539F\u5B50 create \u767B\u8BB0\uFF1B\u53E5\u67C4\u53EA\u6709 id/isSettled/settled\uFF0C\u6CA1\u6709\u53EF\u88AB\u9875\u9762\u5199\u7684\u65B9\u6CD5",
70057
+ "en": "Registers through server-side atomic create; the handle exposes only id/isSettled/settled with no page-writable methods"
70058
+ }
70059
+ },
70060
+ {
70061
+ "name": "createHttpTaskBackend(options)",
70062
+ "type": "(options: HttpTaskBackendOptions) => TaskBackend",
70063
+ "def": "\u2014",
70064
+ "desc": {
70065
+ "zh": "HTTP transport\uFF1B\u4ECE dsh-plugin-core/adv/tasks/http-backend \u5BFC\u5165\uFF0C\u957F\u8FDE\u63A5\u65AD\u5F00\u7531\u5F15\u64CE\u9000\u907F\u91CD\u8FDE",
70066
+ "en": "HTTP transport from dsh-plugin-core/adv/tasks/http-backend; the engine reconnects a dropped stream with backoff"
70067
+ }
70068
+ },
70069
+ {
70070
+ "name": "serveTaskCenter(ctx, options)",
70071
+ "type": "(ctx: HostContextLike, options: TaskCenterRouteOptions) => () => void",
70072
+ "def": "\u2014",
70073
+ "desc": {
70074
+ "zh": "\u5BBF\u4E3B\u4FA7\u8DEF\u7531\u88C5\u914D\uFF08dsh-plugin-core/host/task-center\uFF09\uFF1Bauthorize \u5FC5\u586B\uFF0C\u5BBF\u4E3B\u4E0D\u63D0\u4F9B\u5168\u5C40\u9274\u6743",
70075
+ "en": "Host-side route wiring (dsh-plugin-core/host/task-center); authorize is mandatory because the host provides no global auth"
70076
+ }
70077
+ }
70078
+ ]
70079
+ }
70080
+ ]
70081
+ },
70018
70082
  "bt-use-tasks": {
70019
70083
  "id": "bt-use-tasks",
70020
70084
  "heading": {
@@ -74744,14 +74808,365 @@ function PaginationPage() {
74744
74808
  // packages/demo/src/sections/task-notifications.tsx
74745
74809
  var import_react108 = require("react");
74746
74810
 
74811
+ // dist/adv/tasks/authoritative.js
74812
+ var idempotencySeq = 0;
74813
+ function newIdempotencyKey(clientId) {
74814
+ idempotencySeq += 1;
74815
+ const random = Math.random().toString(36).slice(2);
74816
+ return `${clientId}:${Date.now().toString(36)}:${idempotencySeq.toString(36)}:${random}`;
74817
+ }
74818
+ function mergeInto(state, rows) {
74819
+ const accepted = [];
74820
+ for (const row3 of rows) {
74821
+ if (!Number.isFinite(row3.version))
74822
+ continue;
74823
+ const seenVersion = state.watermark.get(row3.key) ?? -1;
74824
+ if (row3.version < seenVersion)
74825
+ continue;
74826
+ const terminal = state.terminal.get(row3.key);
74827
+ if (terminal !== void 0 && row3.version <= terminal)
74828
+ continue;
74829
+ const current3 = state.seen.get(row3.key);
74830
+ if (current3 !== void 0 && current3.version > row3.version)
74831
+ continue;
74832
+ if (current3 !== void 0 && current3.version === row3.version && current3.state === row3.state)
74833
+ continue;
74834
+ state.seen.set(row3.key, row3);
74835
+ state.watermark.set(row3.key, row3.version);
74836
+ if (row3.tombstone === true || row3.state !== "running")
74837
+ state.terminal.set(row3.key, row3.version);
74838
+ accepted.push(row3);
74839
+ }
74840
+ return accepted;
74841
+ }
74842
+ function createAuthoritativeEngine(options) {
74843
+ const { onChange, onNotice, clientId } = options;
74844
+ const rebaseMinMs = options.rebaseMinMs ?? 5e3;
74845
+ const actionTimeoutMs = options.actionTimeoutMs ?? 5e3;
74846
+ const backends = /* @__PURE__ */ new Map();
74847
+ const projects = /* @__PURE__ */ new Map();
74848
+ const followers = /* @__PURE__ */ new Map();
74849
+ let started = false;
74850
+ let disposed = false;
74851
+ let lastRebase = 0;
74852
+ let reconnectFailures = 0;
74853
+ let reconnectTimer = null;
74854
+ const noticeCursors = /* @__PURE__ */ new Map();
74855
+ let noticePumping = false;
74856
+ let noticePending = false;
74857
+ function clientCursor() {
74858
+ return noticeCursors.get(clientId);
74859
+ }
74860
+ const invokes = /* @__PURE__ */ new Map();
74861
+ const INVOKE_CACHE_MS = 6e4;
74862
+ function invokeCacheKey(project, key, actionId, version) {
74863
+ return `${project}:${key}:${actionId}:${version}`;
74864
+ }
74865
+ function projectState(project) {
74866
+ let state = projects.get(project);
74867
+ if (state === void 0) {
74868
+ state = { snapshotVersion: -1, epoch: 0, seen: /* @__PURE__ */ new Map(), watermark: /* @__PURE__ */ new Map(), terminal: /* @__PURE__ */ new Map() };
74869
+ projects.set(project, state);
74870
+ }
74871
+ return state;
74872
+ }
74873
+ function emitChange() {
74874
+ const all = [];
74875
+ for (const state of projects.values()) {
74876
+ for (const row3 of state.seen.values()) {
74877
+ if (row3.tombstone === true || row3.state !== "running")
74878
+ continue;
74879
+ all.push(row3);
74880
+ }
74881
+ }
74882
+ onChange(Object.freeze(all));
74883
+ }
74884
+ function applyRows(project, rows) {
74885
+ if (mergeInto(projectState(project), rows).length === 0)
74886
+ return;
74887
+ emitChange();
74888
+ }
74889
+ async function pumpNotices() {
74890
+ if (disposed || !started || backends.size === 0)
74891
+ return;
74892
+ if (noticePumping) {
74893
+ noticePending = true;
74894
+ return;
74895
+ }
74896
+ noticePumping = true;
74897
+ try {
74898
+ do {
74899
+ noticePending = false;
74900
+ const projectsNow = [...backends.keys()];
74901
+ const backend = backends.get(projectsNow[0] ?? "");
74902
+ if (backend === void 0)
74903
+ return;
74904
+ let cursor2 = clientCursor();
74905
+ const seenCursors = /* @__PURE__ */ new Set();
74906
+ for (; ; ) {
74907
+ if (disposed)
74908
+ return;
74909
+ if (cursor2 !== void 0) {
74910
+ if (seenCursors.has(cursor2))
74911
+ return;
74912
+ seenCursors.add(cursor2);
74913
+ }
74914
+ const page = await backend.listNotices(projectsNow, cursor2);
74915
+ if (disposed || page.notices.length === 0)
74916
+ break;
74917
+ let delivered = 0;
74918
+ for (const notice of page.notices) {
74919
+ onNotice(notice);
74920
+ cursor2 = notice.cursor;
74921
+ delivered += 1;
74922
+ }
74923
+ if (delivered > 0 && cursor2 !== void 0) {
74924
+ await backend.ackNotices(projectsNow, cursor2);
74925
+ noticeCursors.set(clientId, cursor2);
74926
+ }
74927
+ if (page.nextCursor === void 0 || page.nextCursor === cursor2)
74928
+ break;
74929
+ cursor2 = page.nextCursor;
74930
+ }
74931
+ } while (noticePending && !disposed);
74932
+ } catch {
74933
+ } finally {
74934
+ noticePumping = false;
74935
+ }
74936
+ }
74937
+ function advanceCursor2(project, event) {
74938
+ const state = projectState(project);
74939
+ if (event.kind === "cursor")
74940
+ state.cursor = event.cursor;
74941
+ }
74942
+ async function rebase(project) {
74943
+ const backend = backends.get(project);
74944
+ if (backend === void 0 || disposed)
74945
+ return;
74946
+ const state = projectState(project);
74947
+ const generation = state.epoch;
74948
+ try {
74949
+ let cursor2 = state.cursor;
74950
+ while (!disposed && generation === state.epoch) {
74951
+ const page = await backend.list(project, cursor2);
74952
+ if (disposed || generation !== state.epoch)
74953
+ return;
74954
+ if (page.rows.length > 0)
74955
+ applyRows(project, page.rows);
74956
+ if (page.snapshotVersion < state.snapshotVersion)
74957
+ break;
74958
+ state.snapshotVersion = page.snapshotVersion;
74959
+ if (page.nextCursor === void 0 || page.nextCursor === cursor2)
74960
+ break;
74961
+ cursor2 = page.nextCursor;
74962
+ }
74963
+ if (disposed || generation !== state.epoch)
74964
+ return;
74965
+ state.cursor = cursor2;
74966
+ reconnectFailures = 0;
74967
+ startFollow();
74968
+ } catch {
74969
+ }
74970
+ }
74971
+ function startFollow() {
74972
+ if (disposed || backends.size === 0)
74973
+ return;
74974
+ const byBackend = /* @__PURE__ */ new Map();
74975
+ for (const [project, backend] of backends) {
74976
+ const bucket = byBackend.get(backend);
74977
+ if (bucket === void 0)
74978
+ byBackend.set(backend, [project]);
74979
+ else
74980
+ bucket.push(project);
74981
+ }
74982
+ for (const [backend, owned] of byBackend) {
74983
+ if (followers.has(backend))
74984
+ continue;
74985
+ const cursors = {};
74986
+ for (const project of owned) {
74987
+ const state = projects.get(project);
74988
+ if (state?.cursor !== void 0)
74989
+ cursors[project] = state.cursor;
74990
+ }
74991
+ followers.set(backend, backend.follow(owned, cursors, (project, event) => {
74992
+ if (disposed || !owned.includes(project))
74993
+ return;
74994
+ if (event.kind === "upsert")
74995
+ applyRows(project, event.rows);
74996
+ else if (event.kind === "notice-available")
74997
+ void pumpNotices();
74998
+ advanceCursor2(project, event);
74999
+ }, () => {
75000
+ for (const project of owned) {
75001
+ const state = projects.get(project);
75002
+ if (state !== void 0)
75003
+ state.epoch += 1;
75004
+ }
75005
+ followers.get(backend)?.();
75006
+ followers.delete(backend);
75007
+ if (disposed || reconnectTimer !== null)
75008
+ return;
75009
+ reconnectFailures += 1;
75010
+ const delay = Math.min(15e3, 250 * 2 ** Math.min(reconnectFailures, 6)) + Math.random() * 250;
75011
+ reconnectTimer = setTimeout(() => {
75012
+ reconnectTimer = null;
75013
+ void rebaseAll();
75014
+ }, delay);
75015
+ }));
75016
+ }
75017
+ }
75018
+ async function rebaseAll() {
75019
+ if (disposed)
75020
+ return;
75021
+ await Promise.all([...backends.keys()].map((project) => rebase(project)));
75022
+ void pumpNotices();
75023
+ }
75024
+ return {
75025
+ attach(project, backend) {
75026
+ if (disposed)
75027
+ throw new Error("authoritative engine is disposed");
75028
+ if (typeof backend.list !== "function" || typeof backend.follow !== "function" || typeof backend.listNotices !== "function" || typeof backend.ackNotices !== "function" || typeof backend.invoke !== "function" || typeof backend.ack !== "function") {
75029
+ throw new Error(`task backend for ${project} must provide list/follow/listNotices/ackNotices/invoke/ack`);
75030
+ }
75031
+ backends.set(project, backend);
75032
+ projectState(project);
75033
+ if (started) {
75034
+ const wasStarted = started;
75035
+ this.stop();
75036
+ started = wasStarted;
75037
+ void rebaseAll();
75038
+ }
75039
+ },
75040
+ start() {
75041
+ if (started || disposed)
75042
+ return;
75043
+ started = true;
75044
+ void rebaseAll();
75045
+ },
75046
+ visible() {
75047
+ const now = Date.now();
75048
+ if (now - lastRebase < rebaseMinMs)
75049
+ return;
75050
+ lastRebase = now;
75051
+ void rebaseAll();
75052
+ },
75053
+ refresh(project) {
75054
+ if (project === void 0)
75055
+ void rebaseAll();
75056
+ else
75057
+ void rebase(project);
75058
+ },
75059
+ find(project, key) {
75060
+ return projectState(project).seen.get(key);
75061
+ },
75062
+ all() {
75063
+ const all = [];
75064
+ for (const state of projects.values()) {
75065
+ for (const row3 of state.seen.values()) {
75066
+ if (row3.tombstone === true || row3.state !== "running")
75067
+ continue;
75068
+ all.push(row3);
75069
+ }
75070
+ }
75071
+ return Object.freeze(all);
75072
+ },
75073
+ async runAction(project, key, actionId) {
75074
+ try {
75075
+ const backend = backends.get(project);
75076
+ const record = projectState(project).seen.get(key);
75077
+ const action = record?.actions.find((item) => item.id === actionId);
75078
+ if (backend === void 0 || record === void 0 || action === void 0) {
75079
+ return { ok: false, reason: "action unavailable" };
75080
+ }
75081
+ if (!action.enabled || action.expiresAt <= Date.now() || action.version !== void 0 && action.version !== record.version) {
75082
+ return { ok: false, reason: "action expired" };
75083
+ }
75084
+ const cacheKey = invokeCacheKey(project, key, actionId, record.version);
75085
+ let entry = invokes.get(cacheKey);
75086
+ if (entry === void 0 || Date.now() - entry.at > INVOKE_CACHE_MS) {
75087
+ entry = { idempotencyKey: newIdempotencyKey(clientId), at: Date.now() };
75088
+ invokes.set(cacheKey, entry);
75089
+ }
75090
+ if (entry.result !== void 0)
75091
+ return entry.result;
75092
+ let timer = null;
75093
+ try {
75094
+ const timed = new Promise((_, reject) => {
75095
+ timer = setTimeout(() => reject(new Error("action timeout")), actionTimeoutMs);
75096
+ });
75097
+ const raw = await Promise.race([backend.invoke({
75098
+ project,
75099
+ key,
75100
+ actionId,
75101
+ token: action.token,
75102
+ version: record.version,
75103
+ idempotencyKey: entry.idempotencyKey
75104
+ }), timed]);
75105
+ const result = { ...raw, idempotencyKey: entry.idempotencyKey };
75106
+ if (result.ok) {
75107
+ entry.result = result;
75108
+ entry.at = Date.now();
75109
+ }
75110
+ return result;
75111
+ } finally {
75112
+ if (timer !== null)
75113
+ clearTimeout(timer);
75114
+ }
75115
+ } catch (error) {
75116
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };
75117
+ }
75118
+ },
75119
+ /** 暴露幂等键供上层在 action 事件里回传,迟到结果由它抑制二次 emit。 */
75120
+ idempotencyKeyFor(project, key, actionId, version) {
75121
+ return invokes.get(invokeCacheKey(project, key, actionId, version))?.idempotencyKey;
75122
+ },
75123
+ async acknowledge(request) {
75124
+ const backend = backends.get(request.project);
75125
+ if (backend === void 0)
75126
+ return;
75127
+ await backend.ack(request);
75128
+ },
75129
+ async create(input) {
75130
+ const backend = backends.get(input.project);
75131
+ if (backend?.create === void 0)
75132
+ return void 0;
75133
+ const result = await backend.create(input);
75134
+ if (result.record !== void 0)
75135
+ applyRows(input.project, [result.record]);
75136
+ return result;
75137
+ },
75138
+ has(project) {
75139
+ return backends.has(project);
75140
+ },
75141
+ stop() {
75142
+ for (const state of projects.values())
75143
+ state.epoch += 1;
75144
+ for (const off of followers.values())
75145
+ off();
75146
+ followers.clear();
75147
+ started = false;
75148
+ if (reconnectTimer !== null)
75149
+ clearTimeout(reconnectTimer);
75150
+ reconnectTimer = null;
75151
+ },
75152
+ dispose() {
75153
+ disposed = true;
75154
+ this.stop();
75155
+ projects.clear();
75156
+ invokes.clear();
75157
+ }
75158
+ };
75159
+ }
75160
+
74747
75161
  // dist/adv/tasks/TaskBar.js
74748
75162
  var import_react106 = require("react");
74749
75163
 
74750
75164
  // dist/adv/tasks/pool.js
74751
- var TASK_NOTIFICATIONS_PROTOCOL = 2;
74752
- var TASK_NOTIFICATIONS_KEY = /* @__PURE__ */ Symbol.for("dsh-plugin-core/task-notifications/v2");
74753
- var TASK_NOTIFICATIONS_EVENTS_KEY = /* @__PURE__ */ Symbol.for("dsh-plugin-core/task-notifications/events/v2");
74754
- var TASK_NOTIFICATIONS_CHANNEL = "dsh-plugin-core/task-notifications/v2";
75165
+ var TASK_NOTIFICATIONS_PROTOCOL = 5;
75166
+ var TASK_NOTIFICATIONS_KEY = /* @__PURE__ */ Symbol.for("dsh-plugin-core/task-notifications/v5");
75167
+ var TASK_NOTIFICATIONS_EVENTS_KEY = /* @__PURE__ */ Symbol.for("dsh-plugin-core/task-notifications/events/v5");
75168
+ var TASK_NOTIFICATIONS_CHANNEL = "dsh-plugin-core/task-notifications/v5";
75169
+ var SERVER_SHARD_ORIGIN = "__server__";
74755
75170
  var INVOKE_TIMEOUT_MS = 2e3;
74756
75171
  var DEFAULT_LEASE_MS = 5 * 6e4;
74757
75172
  var DEFAULT_POLL_INTERVAL_MS = 6e4;
@@ -74884,7 +75299,7 @@ function isActionInfos(value) {
74884
75299
  return Array.isArray(value) && value.every((item) => {
74885
75300
  if (!isRecord6(item))
74886
75301
  return false;
74887
- if (!Object.keys(item).every((key) => key === "label" || key === "icon" || key === "color"))
75302
+ if (!Object.keys(item).every((key) => key === "id" || key === "label" || key === "icon" || key === "color"))
74888
75303
  return false;
74889
75304
  if (!isOptionalString(item.label))
74890
75305
  return false;
@@ -74932,6 +75347,10 @@ function isTaskRecord(value) {
74932
75347
  if (value.maxDurationMs !== void 0 && (typeof value.maxDurationMs !== "number" || !Number.isFinite(value.maxDurationMs) || value.maxDurationMs < 0)) {
74933
75348
  return false;
74934
75349
  }
75350
+ if (value.version !== void 0 && (typeof value.version !== "number" || !Number.isFinite(value.version)))
75351
+ return false;
75352
+ if (value.deadlineAt !== void 0 && (typeof value.deadlineAt !== "number" || !Number.isFinite(value.deadlineAt)))
75353
+ return false;
74935
75354
  return typeof value.id === "string" && typeof value.project === "string" && typeof value.group === "string" && typeof value.title === "string" && (value.status === "running" || value.status === "done" || value.status === "failed") && Number.isFinite(value.startedAt) && Number.isFinite(value.updatedAt) && typeof value.origin === "string" && typeof value.backgrounded === "boolean";
74936
75355
  }
74937
75356
  function isNotice(value) {
@@ -75001,7 +75420,7 @@ function makeOrigin2() {
75001
75420
  function compareTasks(a, b) {
75002
75421
  return a.startedAt - b.startedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
75003
75422
  }
75004
- var TASK_NOTIFICATIONS_LOCK_PREFIX = "dsh-plugin-core/task-notifications/v2/";
75423
+ var TASK_NOTIFICATIONS_LOCK_PREFIX = "dsh-plugin-core/task-notifications/v5/";
75005
75424
  function lockNameFor(pageOrigin) {
75006
75425
  return `${TASK_NOTIFICATIONS_LOCK_PREFIX}${pageOrigin}`;
75007
75426
  }
@@ -75041,6 +75460,70 @@ function createTaskNotificationPool(options = {}) {
75041
75460
  const store = createStore2(() => EMPTY_SNAPSHOT);
75042
75461
  const shards = /* @__PURE__ */ new Map();
75043
75462
  const knownSeq = /* @__PURE__ */ new Map();
75463
+ function serverRecordToProjection(row3) {
75464
+ return {
75465
+ id: `${SERVER_SHARD_ORIGIN}:${row3.project}:${row3.key}`,
75466
+ key: row3.key,
75467
+ project: row3.project,
75468
+ group: row3.group,
75469
+ ...row3.groupLabel === void 0 ? {} : { groupLabel: row3.groupLabel },
75470
+ ...row3.projectLabel === void 0 ? {} : { projectLabel: row3.projectLabel },
75471
+ ...row3.icon === void 0 ? {} : { icon: row3.icon },
75472
+ ...row3.iconSvg === void 0 ? {} : { iconSvg: row3.iconSvg },
75473
+ title: row3.title,
75474
+ ...row3.detail === void 0 ? {} : { detail: row3.detail },
75475
+ ...row3.actions.length === 0 ? {} : { actions: row3.actions.map(({ id: id3, label, icon, color }) => ({ ...id3 === "" ? {} : { id: id3 }, label, icon, color })) },
75476
+ status: row3.state === "running" ? "running" : row3.state,
75477
+ startedAt: row3.startedAt,
75478
+ updatedAt: row3.updatedAt,
75479
+ origin: SERVER_SHARD_ORIGIN,
75480
+ backgrounded: false,
75481
+ ...row3.hidden === true ? { hidden: true } : {},
75482
+ ...row3.reason === void 0 ? {} : { reason: row3.reason },
75483
+ version: row3.version,
75484
+ deadlineAt: row3.deadlineAt
75485
+ };
75486
+ }
75487
+ function publishServerRows(rows) {
75488
+ const projections = rows.map(serverRecordToProjection);
75489
+ shards.set(SERVER_SHARD_ORIGIN, {
75490
+ origin: SERVER_SHARD_ORIGIN,
75491
+ seq: 0,
75492
+ tasks: Object.freeze(projections)
75493
+ });
75494
+ revision += 1;
75495
+ store.setState({ tasks: collect(), revision }, true);
75496
+ }
75497
+ const serverSettlers = /* @__PURE__ */ new Map();
75498
+ const serverHandles = /* @__PURE__ */ new Map();
75499
+ const deliveredNotices = /* @__PURE__ */ new Set();
75500
+ const settledResults = /* @__PURE__ */ new Map();
75501
+ function deliverTerminal(notice) {
75502
+ const row3 = notice.record;
75503
+ const cacheKey = `${row3.project}:${row3.key}`;
75504
+ if (deliveredNotices.has(notice.notificationId))
75505
+ return;
75506
+ deliveredNotices.add(notice.notificationId);
75507
+ const projection = serverRecordToProjection(row3);
75508
+ const settlement = {
75509
+ outcome: row3.state === "done" ? "done" : "failed",
75510
+ reason: row3.reason,
75511
+ task: projection
75512
+ };
75513
+ settledResults.set(cacheKey, settlement);
75514
+ bus().emit({ type: "settled", outcome: settlement.outcome, task: projection, remote: false });
75515
+ const waiter = serverSettlers.get(cacheKey);
75516
+ if (waiter !== void 0) {
75517
+ serverSettlers.delete(cacheKey);
75518
+ serverHandles.delete(cacheKey);
75519
+ waiter(settlement);
75520
+ }
75521
+ }
75522
+ const authoritative = createAuthoritativeEngine({
75523
+ clientId: origin,
75524
+ onChange: publishServerRows,
75525
+ onNotice: deliverTerminal
75526
+ });
75044
75527
  let seq = 0;
75045
75528
  let revision = 0;
75046
75529
  let idSeq2 = 0;
@@ -75310,14 +75793,66 @@ function createTaskNotificationPool(options = {}) {
75310
75793
  post({ kind: "invoke", origin, reqId, target, taskId, index: index3 });
75311
75794
  });
75312
75795
  }
75796
+ function emitAction(taskId, snapshot, index3, ok, actionId, reason, result, idempotencyKey) {
75797
+ bus().emit({
75798
+ type: "action",
75799
+ taskId,
75800
+ task: snapshot,
75801
+ ...actionId === void 0 ? {} : { actionId },
75802
+ index: index3,
75803
+ ok,
75804
+ ...reason === void 0 ? {} : { reason },
75805
+ ...result === void 0 ? {} : { result },
75806
+ ...idempotencyKey === void 0 ? {} : { idempotencyKey },
75807
+ remote: false
75808
+ });
75809
+ }
75810
+ function serverFallbackSnapshot(taskId) {
75811
+ const rest = taskId.startsWith(`${SERVER_SHARD_ORIGIN}:`) ? taskId.slice(SERVER_SHARD_ORIGIN.length + 1) : "";
75812
+ const separator = rest.indexOf(":");
75813
+ const project = separator >= 0 ? rest.slice(0, separator) : "";
75814
+ const key = separator >= 0 ? rest.slice(separator + 1) : "";
75815
+ return {
75816
+ id: taskId,
75817
+ ...key === "" ? {} : { key },
75818
+ project,
75819
+ group: "default",
75820
+ title: "",
75821
+ status: "failed",
75822
+ startedAt: 0,
75823
+ updatedAt: 0,
75824
+ origin: SERVER_SHARD_ORIGIN,
75825
+ backgrounded: false
75826
+ };
75827
+ }
75313
75828
  async function runAction(taskId, index3) {
75314
75829
  const record = locate(taskId);
75315
- if (record === void 0)
75830
+ const isServer = record?.origin === SERVER_SHARD_ORIGIN || record === void 0 && taskId.startsWith(`${SERVER_SHARD_ORIGIN}:`);
75831
+ if (record === void 0) {
75832
+ if (isServer)
75833
+ emitAction(taskId, serverFallbackSnapshot(taskId), index3, false, void 0, "task unavailable");
75316
75834
  return false;
75317
- if (record.timeoutMs !== void 0 && Date.now() - record.updatedAt > record.timeoutMs)
75835
+ }
75836
+ if (record.timeoutMs !== void 0 && Date.now() - record.updatedAt > record.timeoutMs) {
75837
+ if (isServer)
75838
+ emitAction(taskId, record, index3, false, record.actions?.[index3]?.id, "task expired");
75318
75839
  return false;
75319
- if (record.actions?.[index3] === void 0)
75840
+ }
75841
+ const action = record.actions?.[index3];
75842
+ if (action === void 0) {
75843
+ if (isServer)
75844
+ emitAction(taskId, record, index3, false, void 0, "action unavailable");
75320
75845
  return false;
75846
+ }
75847
+ if (isServer) {
75848
+ if (record.key === void 0 || action.id === void 0) {
75849
+ emitAction(taskId, record, index3, false, action.id, "action unavailable");
75850
+ return false;
75851
+ }
75852
+ const result = await authoritative.runAction(record.project, record.key, action.id);
75853
+ emitAction(taskId, record, index3, result.ok, action.id, result.reason, result.result, result.idempotencyKey);
75854
+ return result.ok;
75855
+ }
75321
75856
  if (record.origin === origin)
75322
75857
  return runLocal(taskId, index3);
75323
75858
  return requestInvoke(record.origin, taskId, index3);
@@ -75474,10 +76009,12 @@ function createTaskNotificationPool(options = {}) {
75474
76009
  }
75475
76010
  scheduleExpiry();
75476
76011
  schedulePoll();
76012
+ authoritative.start();
75477
76013
  }
75478
76014
  function refresh() {
75479
76015
  holdLiveness();
75480
76016
  post({ kind: "hello", origin });
76017
+ authoritative.visible();
75481
76018
  }
75482
76019
  function ensure(input) {
75483
76020
  const project = requireProject(input.project);
@@ -75494,6 +76031,9 @@ function createTaskNotificationPool(options = {}) {
75494
76031
  throw new Error("task notification timeoutMs must be a finite number >= 0");
75495
76032
  }
75496
76033
  const serverBacked = input.serverBacked === true;
76034
+ if (serverBacked && key !== void 0 && authoritative.has(project)) {
76035
+ throw new Error("authoritative project requires ensureServer(), not ensure()");
76036
+ }
75497
76037
  if (serverBacked && key === void 0) {
75498
76038
  throw new Error("task notification serverBacked requires a key");
75499
76039
  }
@@ -75681,6 +76221,57 @@ function createTaskNotificationPool(options = {}) {
75681
76221
  }
75682
76222
  return { handle, created: true };
75683
76223
  }
76224
+ async function ensureServer(input) {
76225
+ const project = requireProject(input.project);
76226
+ if (project === null)
76227
+ throw new Error("task notification project cannot be null when registering");
76228
+ if (input.key === void 0)
76229
+ throw new Error("server task requires a key");
76230
+ if (!authoritative.has(project)) {
76231
+ throw new Error(`project ${project} has no authoritative backend; call setTaskBackend first`);
76232
+ }
76233
+ const key = taskKey(input.key);
76234
+ const id3 = `${SERVER_SHARD_ORIGIN}:${project}:${key}`;
76235
+ const keyOfHandle = `${project}:${key}`;
76236
+ let handle = serverHandles.get(keyOfHandle);
76237
+ if (handle === void 0) {
76238
+ let isSettled = false;
76239
+ let resolveSettled = () => {
76240
+ };
76241
+ const settled = new Promise((resolve) => {
76242
+ resolveSettled = resolve;
76243
+ });
76244
+ handle = { id: id3, get isSettled() {
76245
+ return isSettled;
76246
+ }, settled };
76247
+ serverHandles.set(keyOfHandle, handle);
76248
+ const cached = settledResults.get(keyOfHandle);
76249
+ if (cached !== void 0) {
76250
+ settledResults.delete(keyOfHandle);
76251
+ serverHandles.delete(keyOfHandle);
76252
+ isSettled = true;
76253
+ resolveSettled(cached);
76254
+ } else {
76255
+ serverSettlers.set(keyOfHandle, (value) => {
76256
+ isSettled = true;
76257
+ resolveSettled(value);
76258
+ });
76259
+ }
76260
+ }
76261
+ const created = await authoritative.create({
76262
+ project,
76263
+ key,
76264
+ group: normalizeGroup(input.group),
76265
+ title: input.title,
76266
+ ...input.detail === void 0 ? {} : { detail: cloneDetail(input.detail) },
76267
+ ...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
76268
+ ...input.leaseMs === void 0 ? {} : { leaseMs: input.leaseMs },
76269
+ ...input.maxDurationMs === void 0 ? {} : { maxDurationMs: input.maxDurationMs }
76270
+ });
76271
+ if (created === void 0)
76272
+ throw new Error(`project ${project} backend does not support create`);
76273
+ return { handle, created: created.created };
76274
+ }
75684
76275
  function settleLocal(reason) {
75685
76276
  let settledCount = 0;
75686
76277
  for (const task of [...localShard()]) {
@@ -75706,6 +76297,7 @@ function createTaskNotificationPool(options = {}) {
75706
76297
  select: (groups, options2) => selectTaskNotifications(store.getState(), groups, options2),
75707
76298
  register: (input) => ensure(input).handle,
75708
76299
  ensure,
76300
+ ensureServer,
75709
76301
  broadcast,
75710
76302
  setStatusSource(project, source) {
75711
76303
  if (typeof project !== "string" || project.trim() === "") {
@@ -75714,9 +76306,23 @@ function createTaskNotificationPool(options = {}) {
75714
76306
  if (typeof source !== "function") {
75715
76307
  throw new Error("task notification status source must be a function");
75716
76308
  }
76309
+ if (authoritative.has(project)) {
76310
+ throw new Error(`project ${project} is in authoritative mode; setStatusSource is not allowed`);
76311
+ }
75717
76312
  statusSources.set(project, source);
75718
76313
  schedulePoll();
75719
76314
  },
76315
+ setTaskBackend(project, backend) {
76316
+ if (typeof project !== "string" || project.trim() === "") {
76317
+ throw new Error("task backend project must be a non-empty string");
76318
+ }
76319
+ if (store.getState().tasks.some((task) => task.project === project && task.serverBacked === true)) {
76320
+ throw new Error(`project ${project} still has legacy serverBacked tasks; settle them before switching`);
76321
+ }
76322
+ statusSources.delete(project);
76323
+ authoritative.attach(project, backend);
76324
+ authoritative.start();
76325
+ },
75720
76326
  settleLocal,
75721
76327
  runAction,
75722
76328
  canRestore: (task) => task.origin === origin,
@@ -75738,6 +76344,11 @@ function createTaskNotificationPool(options = {}) {
75738
76344
  for (const entry of pendingInvokes.values())
75739
76345
  entry.resolve(false);
75740
76346
  pendingInvokes.clear();
76347
+ authoritative.stop();
76348
+ serverSettlers.clear();
76349
+ serverHandles.clear();
76350
+ settledResults.clear();
76351
+ deliveredNotices.clear();
75741
76352
  if (channel !== null) {
75742
76353
  channel.onmessage = null;
75743
76354
  channel.close();
@@ -75776,10 +76387,14 @@ var taskNotifications = {
75776
76387
  select: (groups, options) => globalPool().select(groups, options),
75777
76388
  register: (input) => globalPool().register(input),
75778
76389
  ensure: (input) => globalPool().ensure(input),
76390
+ ensureServer: (input) => globalPool().ensureServer(input),
75779
76391
  broadcast: (input) => globalPool().broadcast(input),
75780
76392
  setStatusSource: (project, source) => {
75781
76393
  globalPool().setStatusSource(project, source);
75782
76394
  },
76395
+ setTaskBackend: (project, backend) => {
76396
+ globalPool().setTaskBackend(project, backend);
76397
+ },
75783
76398
  settleLocal: (reason) => globalPool().settleLocal(reason),
75784
76399
  runAction: (taskId, index3) => globalPool().runAction(taskId, index3),
75785
76400
  canRestore: (task) => globalPool().canRestore(task),
@@ -75816,6 +76431,11 @@ function ensureTask(title, options = {}) {
75816
76431
  function backgroundTask(title, options = {}) {
75817
76432
  return taskNotifications.ensure(notifyTaskInput(title, { ...options, serverBacked: true }));
75818
76433
  }
76434
+ function serverTask(title, options = {}) {
76435
+ if (options.key === void 0)
76436
+ return Promise.reject(new Error("notifyTask.server requires a key"));
76437
+ return taskNotifications.ensureServer(notifyTaskInput(title, { ...options, serverBacked: true }));
76438
+ }
75819
76439
  function runTask(title, work, options = {}) {
75820
76440
  let claim2;
75821
76441
  let key;
@@ -75841,6 +76461,7 @@ function runTask(title, work, options = {}) {
75841
76461
  var notifyTask = Object.assign(notifyTaskBase, {
75842
76462
  ensure: ensureTask,
75843
76463
  background: backgroundTask,
76464
+ server: serverTask,
75844
76465
  run: runTask
75845
76466
  });
75846
76467
  var taskNotificationEvents = {
@@ -76400,9 +77021,9 @@ function ReferencePage() {
76400
77021
  "tbody",
76401
77022
  null,
76402
77023
  [
76403
- [t3("buildCore"), `v${"0.36.2"}`],
76404
- [t3("buildDemo"), `v${"0.36.2"}`],
76405
- [t3("buildStamp"), "261116-123615-127"]
77024
+ [t3("buildCore"), `v${"0.38.0"}`],
77025
+ [t3("buildDemo"), `v${"0.38.0"}`],
77026
+ [t3("buildStamp"), "261116-161113-772"]
76406
77027
  ].map(
76407
77028
  ([label, value]) => (0, import_react110.createElement)(
76408
77029
  "tr",
@@ -76721,9 +77342,9 @@ function DemoPage() {
76721
77342
  lineHeight: "14px"
76722
77343
  }
76723
77344
  },
76724
- (0, import_react112.createElement)("span", null, `core v${"0.36.2"}`),
76725
- (0, import_react112.createElement)("span", null, `demo v${"0.36.2"}`),
76726
- (0, import_react112.createElement)("span", { style: { marginTop: "4px", fontSize: "9px" } }, "261116-123615-127")
77345
+ (0, import_react112.createElement)("span", null, `core v${"0.38.0"}`),
77346
+ (0, import_react112.createElement)("span", null, `demo v${"0.38.0"}`),
77347
+ (0, import_react112.createElement)("span", { style: { marginTop: "4px", fontSize: "9px" } }, "261116-161113-772")
76727
77348
  )
76728
77349
  )
76729
77350
  ),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-core-demo",
3
- "version": "0.36.2",
3
+ "version": "0.38.0",
4
4
  "description": "The shared UI foundation for DSH plugins, with a live component preview: design tokens, common controls, workspace browsing and notifications maintained in one place — install it to preview every component in a real host.",
5
5
  "icon": "./assets/icon-components.svg",
6
6
  "keywords": [